-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfetcher.rb
49 lines (43 loc) · 1.79 KB
/
fetcher.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
require 'net/imap'
require 'mail'
require 'yaml'
#Retrieve settings from external file
settings = YAML.load_file('settings.yml')
#Start the actual work
imap = Net::IMAP.new(settings['imap_host'], settings['imap_port'], settings['imap_ssl'], nil, false)
if settings['imap_auth_mechanism'].nil?
imap.login(settings['imap_user'], settings['imap_password'])
else
imap.authenticate(settings['imap_auth_mechanism'], settings['imap_user'], settings['imap_password'])
end
imap.select('INBOX')
#Select unseen messages only
imap.search(["NOT", "SEEN"]).each do |message_id|
#Get the full content
raw = imap.fetch(message_id, "BODY[]")[0].attr["BODY[]"]
imap.store(message_id, '+FLAGS', [:Seen])
#Parse it with mail library
mail = Mail.read_from_string(raw)
token = mail.to.to_s
#If multipart or auth token not included, then discard the mail
if mail.multipart? or (not settings['token_email'].nil? and not token.include?(settings['token_email'].to_s))
imap.copy(message_id, 'Untreated')
else
content = mail.body.decoded.force_encoding(mail.charset).encode("UTF-8")
subject = mail.subject
date = mail.date.strftime("%Y-%m-%d-%H-%M-%S")
#Adding title (i.e. subject from email)) with dokuwiki syntax
content = "==== " + subject.to_s + " ====\n\n" + content.to_s
#Formating a link to be inserted in the dokuwiki start page
link = "\n\n[[#{date}|#{subject}]]"
#Here, create the file and write the content in the dokuwiki folder
File.umask(0012)
File.open(settings['local_folder']+date+'.txt', 'w:UTF-8') {|f| f.write(content) }
File.open(settings['local_folder']+'start.txt', 'a:UTF-8') {|f| f.write(link) }
puts "One message treated"
imap.copy(message_id, 'Treated')
end
imap.store(message_id, '+FLAGS', [:Deleted])
end
imap.expunge #Delete all mails with deleted flags
imap.close