Skip to content

Instantly share code, notes, and snippets.

@abo-elleef
Created April 20, 2013 22:53
Show Gist options
  • Save abo-elleef/5427732 to your computer and use it in GitHub Desktop.
Save abo-elleef/5427732 to your computer and use it in GitHub Desktop.
require "net/imap"
require "mail"
def connect_to_mail_server (username , password,server ="imap.google.com",post=993,ssl=true)
imap = Net::IMAP.new(server,port,ssl)
imap.login(username,password)
return imap
end
def get_access_to_mail_boxes imap
["INBOX"].each do |box|
begin
imap.examine(mailbox)
rescue
p "mailbox: #{box} is not exists"
end
end
return imap
end
def search_for_matched_emails imap
message_ids = []
["search","words"].each do |word|
message_ids << imap.search([word,"BODY"])
end
message_ids.flatten!
return message_ids
end
def handle_attachments mail
mail.attachments.each do |a|
#remember to escape slashes in filename to be store correctly
file = File.open("/path_to_store_file_in/#{a.filename}","w+b")
file.write(a.body.decoded)
file.close()
end
end
def fetch_emails message_ids
message_ids.each do |id|
body = imap.fetch(messsage_id,"BODY[]")[0].attr["BODY[]"] #return the whole body
mail = Mail.new(body)
html_part = mail.html_part.decoded || "html part is empty"
plain_part = mail.plain_part.decoded || "html part is empty"
mail_subject = mail.subject || "message has no subject"
form = mail.from.first
to = mail.to.first
#remember to escape slashes in mail subject to be store correctly
file_name = "path_to_store_file_in" +subject+ ".html"
file = File.open(file_name,"w+b")
file.close
handle_attachments(mail)
end
end
imap = connect_to_mail_server("< username >","<password>")
imap = get_access_to_mail_boxes(imap)
message_ids = search_for_matched_emails(imap)
fetch_emails message_ids
imap.logout #to terminate the session with the mail server
full_email_body = imap.fetch(messsage_id,"BODY[TEXT]")[0].attr["BODY[TEXT]"] #return the whole body plan text and html parts
only_plain_part = imap.fetch(messsage_id,"BODY[1]")[0].attr["BODY[1]"] #return plan text part of the e-mail body
only_html_part = imap.fetch(messsage_id,"BODY[2]")[0].attr["BODY[2]"] #return HTML part of the e-mail body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment