415 - Sending HTML emails in Rails using LoginEngine’s UserNotify model

I was having trouble with my latest project quite a while back in that I couldn’t get LogineEngine’s UserNotify model to correctly send HTML emails.  I would keep setting the Content-type header to “text/html” but it would always revert back to “text/plain”.  Grrrr!

Well, the issue lies in its use of Rails’ ActionMailer gem. It seems there is a particularly annoying bug in that ActionMailer unassumedly gobbles up certain common headers, even if properly set and replaces them with default settings (or rather, ignores them.)  There’s a patch in the bug, but we prefer to keep as clean a version of Rails as possible to make upgrading and versioning much easier for our production environment.  Note that even though the referenced bug may not seem to apply, the root problem causes both this issue and the one described in the bug (and another for using the proper headers to help thread conversations using In-Reply-To headers).
The solution lies in the RDocs for ActionMailer, so I’m very surprised that no one else has mentioned this solution yet.  It’s so easy of one I kicked myself for taking so long to find it.  Basically, instead of trying to set the Content-Type header, you need to set the @content-type variable equal to “text/html” in the action you have which sets up your email before it gets sent.  Don’t forget that SMTP RFCs say you need a “Mime-Version: 1.0″ header when setting the content-type header.  Below is the code to insert into your setup action, or the action you use to send the mail if you don’t have an action to setup from, etc…

@content_type = “text/html”
@headers[‘Mime-Version’] = 1.0

As an additonal tip, don’t forget to make sure your from address is properly formatted.  It should include a name AND email address of the form:

@from = “My Email Address Name <user@domain.com>”

This will make sure that your email is less readily identified as spam.

No Comments yet »

RSS feed for comments on this post. TrackBack URI

Leave a comment

Note: This post is over 5 years old. You may want to check later in this blog to see if there is new information relevant to your comment.

Powered by Wordpress and based on the Subnixus theme as modified by Blue Needle