Sending HTML emails with attachments in Rails

Here’s something you might have missed in Rails.

From ActionMailer’s Documentation:

Implicit template rendering is not performed if any attachments or parts have been added to the email. This means that you‘ll have to manually add each part to the email and set the content type of the email to multipart/alternative

If you want to have pretty html templates and have an attached file, you can’t just set the content_type to “text/html” and call attachment.  You need to do it separately, like so:

class SomeMailer < ActionMailer::Base

  # assumes that there's a file named pretty_template.html.erb in app/views/some_mailer
  def html_email_with_attachment(email_address, msg)
    recipients [email_address]
    from ""
    subject "This is an html email with an attachment"

    # have to set content_type explicitly
    content_type "multipart/alternative"

    # then set the html part.  Note that there is no call to body(), but 
    # the second argument is a hash containing what you'd put into body() normally.
    part(:content_type => "text/html",
         :body => render_message("pretty_template", :message => msg)

    attachment(:content_type => "text/csv",
               :filename => "attachment.csv",
               body => CSVGenerator.generate_csv_string)

    # as a note, all attachment is doing is adding transfer_encoding and disposition
    # part(:content_type => "text/csv",
    #      :transfer_encoding => "base64",
    #      :disposition => "attachment",
    #      :filename => "attachment.csv",
    #      :body => CSVGenerator.generate_csv_string)


There, now you can have html and your attachments too.  Reference:



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s