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 50 51 52 53 54 55 56 57 58 59 60 61
| #!/usr/bin/ruby
require 'net/imap' require "mail" require 'net/http' require 'digest/sha1' require "date" require "json"
base = "/Users/renlu/mails/" imap = Net::IMAP.new('imap.exmail.qq.com') imap.login "username@domain.com", "password" boxes = [] for box in imap.list("","%") do boxes << Net::IMAP::decode_utf7(box.name) end for name in boxes do imap.select(Net::IMAP::encode_utf7(name)) imap.search(["ALL"]).each do |message_id| body = imap.fetch(message_id, 'RFC822')[0].attr['RFC822'] mail = Mail.new(body) envelope = imap.fetch(message_id, ["ENVELOPE","","FLAGS"])[0].attr["ENVELOPE"]
File.open("#{base}/#{message_id}.body", 'wb') do |file| file.write(body) end File.open("#{base}/#{message_id}.index", 'wb') do |file| info = { date:envelope.date, subject:envelope.subject, from:envelope.from, sender:envelope.from, reply_to:envelope.reply_to, to:envelope.to, cc:envelope.cc, bcc:envelope.bcc, in_reply_to:envelope.in_reply_to, message_id:envelope.message_id } file.write(JSON.dump(info)) end Dir.mkdir("#{base}/attach-#{message_id}/") if mail.attachments.length>0 mail.attachments.each do |attachment| if !File.exists?("#{base}/attach-#{message_id}/#{attachment.filename}") File.open("#{base}/attach-#{message_id}/#{attachment.filename}", 'wb') do |file| file.write(attachment.body.decoded) puts "#{message_id} attachment: #{attachment.filename}" end end
end imap.store(message_id ,"+FLAGS",[:SEEN]) end puts "mail from :#{Mail::Encodings.value_decode(envelope.from[0].name)}" end end
|