Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the body text of an email using ruby's net/imap library?

Tags:

ruby

imap

Maybe i've just got a bad brain today, but i suddenly can't figure out how to read an email with ruby's net/imap library. I've been at it for several hours. I typed several variations of "ruby imap read body" into google and have explored many sites. All of them have examples on how to pull attachments, sync e-mail servers, work with gmail etc... Some (like chilkat) are actually shareware libraries that do this for you. I have looked at the net/imap documentation and though there are several examples for doing everything but reading the body text.

I've worked with net/imap before but i've only needed to pull down the attachments in an inbox to a directory. I've asked in #ruby and #rubyonrails to no avail - no one could figure it out.


imap=Net::IMAP.new('mail.xks.com') #of course these are not real
imap.login('web1_xk3','pxx2006')
imap.select('INBOX')
imap.search(["SENTSINCE",(Time.now-1.day).strftime("%d-%b-%Y")]).each do |msgid|
     body = imap.fetch(msgid,"BODY")[0].attr["BODY"]
     ##insert code for getting the text from the body here
     ##body.class is BodyTypeText 
end

P.S. Though I do make a reference to active support in the code, this is sans-rails so that means no action-mailer

like image 272
awesome_person Avatar asked Jul 08 '09 23:07

awesome_person


2 Answers

Piggybacking off @Bjer's answer, here's a complete solution using the mail gem and gmail_xoauth gem to log into gmail using OAuth2 and parses all the emails:

imap = Net::IMAP.new('imap.gmail.com', 993, usessl = true, certs = nil, verify = false)
imap.authenticate('XOAUTH2', '[email protected]', 'access_token_goes_here')
imap.select('INBOX')
imap.search(['ALL']).each do |message_id|

    msg = imap.fetch(message_id,'RFC822')[0].attr['RFC822']
    mail = Mail.read_from_string msg

    puts mail.subject
    puts mail.text_part.body.to_s
    puts mail.html_part.body.to_s

end
like image 147
Andrew Avatar answered Sep 19 '22 17:09

Andrew


If you just want just the body content of the message you can use:

body = imap.fetch(message_id,'BODY[TEXT]')[0].attr['BODY[TEXT]']

The IMAP API is a bit esoteric though. If you want to deal with the whole message, I would recommend using TMail to parse it into an easier to use format:

msg = imap.fetch(message_id,'RFC822')[0].attr['RFC822']
mail = TMail::Mail.parse(msg)
body = mail.body
like image 30
geofflane Avatar answered Sep 21 '22 17:09

geofflane