The Spaghetti Refactory Established 2015

Attach files and configure `delivery_method` in Rails ActionMailer

Today is a twofer!

Attachments in ActionMailer for Rails

First, I never tried sending attachments in a Rails mailer before, but it is incredibly easy. Just throw this line into your mailer method:

attachments["screenshot.png"] = File.read("#{Rails.root}/public/images/screenshot.png")

And of course, replace the file name in the attachments hash with what you want the attachment name to be, and then replace the path in the File.read with your attachment's path.

Specify :delivery_method for individual mailer methods

This part can come in handy if you have a specific mailer method that you want to actually send in the testing environment, instead of just outputting to a file or to the log. The specific use case I have for this is when I have finicky intermittent test failures when running our test suite on my CI service (something I've talked about elsewhere). This method grabs the screenshot that was taken when the error occurred, and it emails it to the email passed in:

def error_email(email, public_image=nil)
attachments["screenshot.png"] = File.read("#{Rails.root}/public/images/screenshot.png")
mail(to: email, subject: 'Capybara error', delivery_method: :smtp)
end

Since this is happening on my CI server and I can't look at any tmp files it creates, I need the email to actually send via SMTP, but I still want every other mailer method to deliver via the :file method because I don't want to get a boatload of emails every time the test suite runs.

Pretty nifty! Thanks to jankubr on StackOverflow for this one.