multipart emails with mailer templates

December 23, 2008 written by Surendra Singhi .

Update: The code given below here causes the exception notification plugin to stop working, get the fixed code from this post. It also contains a better technique to organize the mailers.

Rails 2.2 has added a very cool new feature which allows the use of layouts for mailer-templates, just like the way layouts can be used for views. This is great, but there is one gotcha, when you try sending a multi-part email (both text and html, as you should be), it wraps the mail content with the same layout for both the text/plain version and the text/html version.

After digging around a bit in the ActionMailer code, I came up with the following monkey patch, which will use the layout only for the text/html version of the email. You can put this code in your environment.rb file, it won’t use layout when the mail-template content type is ‘text/plain’.

  1. # monkey patch action mailer to not use layouts for text/plain emails
  2. module ActionMailer
  3.   class Base
  4.     private
  5.     def candidate_for_layout?(options)
  6.       (!options[:file] || options[:file].content_type != ‘text/plain’) && !@template.send(:_exempt_from_layout?, default_template_name)
  7.     end
  8.   end
  9. end

If you can come up with some other better solution than this, then let us know.

Tags: , ,

7 Comments

  1. avatar Joren Six Says:

    Thanks.

  2. avatar erwin Says:

    thanks a lot you saved my day !
    was struggling with multiparts for a long day …

    erwin

  3. avatar organizing mailers and mailer templates | evolving the web... Says:

    [...] patch written for action mailer to not use layouts for text/plain email was causing problem with exception notification plugin, so I have modified it slightly so that it [...]

  4. avatar Dan Sharp Says:

    Wow! I wish I discovered this yesterday. I spent too many hours trying to monkeypatch this myself but not really knowing where or how to do it and thus just flailed.

    This patch worked perfectly. :-)

    Thank you!

    -Danimal

  5. avatar Jared Mehle Says:

    I just wanted to leave a note saying this bug has been fixed in Rails 2.3 even though Lighthouse #1799 remains open.

  6. avatar Ted Burrett Says:

    My friend on Facebook shared this link with me and I’m not dissapointed that I came to your blog.

  7. avatar Dan Sharp Says:

    Jared,

    Thanks for the heads-up. My templates were messing up in 2.3. Turns out that it’s working correctly now. That is to say, in app/views/layouts you can have “foo.text.html.erb” and “foo.text.plain.erb” and then in your mailer code you have: “layout ‘foo’” and it will pull the right layout for each part depending upon the part type. This works well now… lets me have a global email template with differences for HTML and plain types. Yay!

    (I like it when my monkey patches file gets smaller and smaller as Rails progresses!)

Leave a Reply