Storing Gmail messages offline using the Omah gem

require 'gmail'
require 'omah'

gmail = Gmail.new("somebody@gmail.com", "*****")

a = gmail.inbox.emails

# fields we are interested in:
#
#    :from,  :message_id, :to, :subject, :date, :body.decoded, 
#    :text_part.to_s, html_part.to_s

messages = a.map.with_index.inject([]) do |r, x|

  gmail_msg, i = x
  msg = gmail_msg.message

  puts 'i :'  + i.inspect
  begin
    r << {
      id:         msg.message_id,
      from:       msg.from.is_a?(Array) ? msg.from.join(', ') : msg.from,
      to:         msg.to.is_a?(Array) ? msg.to.join(', ') : msg.to,
      subject:    msg.subject,
      date:       msg.date.to_s,
      body_text:  (msg.text_part ? msg.text_part.body.decoded : msg.body.decoded),
      body_html:  (msg.html_part ? msg.html_part.body.decoded : msg.body.decoded)
    }
  rescue
    puts 'warning: ' + ($!).inspect
  end
r

end

o = Omah.new

# messages are stored to the file dynarexdaily.xml
o.store messages

Note: It doesn't currently handle file attachments.

Resources