Adding multiple email attachments with Ruby on Rails

Jun 20, 2007

I was building some forms for a client that required the user be able to upload supporting documents along with the application. I had implemented emailable forms before with single attachments, but never multiple. Turns out, it was just as simple to do, I just needed to call the attach function for each file I wanted to attach.

Here is the method in my controller that calls the ActionMailer class to send the email, where params[:file1], params[:file2], and params[:file3] are the file_field_tag's from the form:

UPDATE: I've re-factored this after Shawn suggested that it could be simplified into an array and iterated over.

def submit_application
  @uploaded_files = []
  @uploaded_files << params[:file1]
  @uploaded_files << params[:file2]
  @uploaded_files << params[:file3]
  ContactMailer.deliver_email_with_attachments(params[:application], @uploaded_files)
  flash[:notice] = 'Your application has been submitted.  Thank you!'
  redirect_to application_home_url
rescue Exception => ex
  flash[:notice] = 'Uh oh!  There was an error sending your application.'
  redirect_to :back

And here is the ActionMailer method that attaches the files. I just need to iterate over the files, calling attach for each one.

def email_with_attachments(application_fields={},files=[])
  @headers = {}
  @sent_on = Time.now
  @recipients = 'client@domain.com'
  @from = 'info@domain.com'

  @subject = 'Here are some file attachments'
  application_fields.keys.each {|k| @body[k] = application_fields[k]}

  # attach files
  files.each do |file|
    attachment "application/octet-stream" do |a|
      a.body = file.read
      a.filename = file.original_filename
    end unless file.blank?

The "application/octet-stream" is the generic MIME type for attaching unknown file types.

Pretty simple!

Tagged: railsactionmaileremail attachmenttutorial