/ actionmailer

CSS and ActionMailer in Rails3.

Lately, I was working on a project where I found an issue that emails sent using ActionMailer were not applying css styles to the html elements of the email. On adding style tag in the email view files, I was able to view stylings on thunderbird mail and ymail but still I was unable to view css stylings for emails in gmail.

On furthur investigating the issue, I found that gmail requires inline stylings to be applied to the email templates. I found some gems which could fix this problem by converting external css to inline css. I tried the roadie gem but it had dependency on Nokogiri version(and was conflicting with the one in my project).

The easiest and most efficient way to fix this issue, that I found was premailer_rails gem. This gem automatically converts external css to inline css, no extra code is required.

My code looked like the following after adding the gem:

gemfile:

gem 'premailer-rails'
gem 'nokogiri'
# or
gem 'hpricot'

Instead of adding to individual templates, I added styles in the layout. I used style_sheet_tag to include external css:

In the layouts folder:

!!!
%html{:lang => "en"}
%head
%meta{:content => "text/html; charset=utf-8", "http-equiv" => "Content-Type"}/
  = stylesheet_link_tag "mailer"
%body
  = yield

The styles that needed to be applied to the emails were in the file mailer.css.scss

REFERENCES:

https://github.com/fphilipe/premailer-rails