Send email with attachment in Ruby

Haroon picture Haroon · Jul 7, 2010 · Viewed 15.8k times · Source

I need to send an email with an attachment via Ruby.

Been searching around but haven't found any simple script example to do this.

Closest I've found is ActionMailer but that seems to require a bunch of other scripts to to run. (NOTE: I am not using Ruby on Rails)

Answer

Daniel Abrahamsson picture Daniel Abrahamsson · Jul 7, 2010

Have you checked out Mail? That is what the new ActionMailer API in Rails 3 is built upon.

"Mail is an internet library for Ruby that is designed to handle emails generation, parsing and sending in a simple, rubyesque manner."

Here comes a quick example from the docs:

require 'mail'

@mail = Mail.new
file_data = File.read('path/to/myfile.pdf')
@mail.attachments['myfile.pdf'] = { :mime_type => 'application/x-pdf',
                                    :content => file_data }

Update: Or even more simply:

@mail = Mail.new
@mail.add_file("/path/to/file.jpg")