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

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

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

Or if you're on ruby 1.9.x TMail seems to have problems
I'm using Mail (https://github.com/mikel/mail )

body = imap.fetch(message_id,'BODY[TEXT]')[0].attr['BODY[TEXT]']
msg = imap.fetch(-1,'RFC822')[0].attr['RFC822']
mail = Mail.read_from_string msg

body = mail.body
from = mail.from 

Tags:

Ruby

Imap