3

I'm using the mailmain gem to grab pop3 mail. This library uses the mail gem to break up the message body and attachments. I'm to the point where I can get the attachment in the pry command line like so:

14: Mailman.config.rails_root = '../'
15: 
16: Mailman::Application.run do
17:   to 'expenses@surveymonkey.com' do
18:     require 'debugger'; debugger
=> 19:     print message
20:   end
21: end

and I can get an individual attachment like so

[1] pry(#<Mailman::Router>)> a = message.attachments[0]
=> #<Mail::Part:70339703566060, Multipart: false, Headers: <Content-Type: image/jpeg;   name="70s-Jump-Suit.jpeg">, <Content-Transfer-Encoding: base64>, <Content-Disposition: attachment; filename="70s-Jump-Suit.jpeg"; size=38412; creation-date="Tue, 26 Jun 2012 22:11:10 GMT"; modification-date="Tue, 26 Jun 2012 22:11:10 GMT">, <Content-Description: 70s-Jump-Suit.jpeg>>

So, the question is, how do I save this data?

I'm close with this method, but I'm unable to properly save.

and I've tried stuff like this

[2] pry(#<Mailman::Router>)> File.open( '/tmp/output.jpg', "w+b", 0644 ) { |f| f.write a.raw_source }

but the output gets botched.

I just don't know enough about email encoding to get this to work.

Thanks in advance!

timsabat
  • 2,208
  • 3
  • 25
  • 34
  • Is the [`decoded()` method](http://rdoc.info/github/mikel/mail/Mail/Message#attachments-instance_method) the thing to use to get the actual binary data from the attachment? Probably `raw_source` is MIME-64 or whatever encoding was used... – sarnold Jun 26 '12 at 23:13
  • Hey, I found it! http://cbpowell.wordpress.com/2011/01/17/saving-attachments-with-ruby-1-9-2-rails-3-and-the-mail-gem/ – timsabat Jun 26 '12 at 23:22
  • Cool! When the system allows you to post your own answer, please do so, including a link to the cbpowell article. – sarnold Jun 26 '12 at 23:30

1 Answers1

3

Ah, here we go:

http://cbpowell.wordpress.com/2011/01/17/saving-attachments-with-ruby-1-9-2-rails-3-and-the-mail-gem/

# tmail is now a Mail object
tmail.attachments.each do |tattch|
  fn = tattch.filename
  begin
    File.open( fn, "w+b", 0644 ) { |f| f.write tattch.body.decoded }
  rescue Exception => e
    logger.error "Unable to save data for #{fn} because #{e.message}"
  end
end
timsabat
  • 2,208
  • 3
  • 25
  • 34
  • 1
    since links can sometimes break, it's best practice to post the entire answer. Also, don't forget to accept your own answer. ;-) – Tass Mar 27 '14 at 19:39