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’.
-
# monkey patch action mailer to not use layouts for text/plain emails
-
module ActionMailer
-
class Base
-
private
-
def candidate_for_layout?(options)
-
(!options[:file] || options[:file].content_type != ‘text/plain’) && !@template.send(:_exempt_from_layout?, default_template_name)
-
end
-
end
-
end
If you can come up with some other better solution than this, then let us know.