Inlining CSS in ActionMailer 3 (Rails 3.0)

As most of you already know, a bunch of online mail readers (like Hotmail, Gmail, …) don’t handle stylesheets very well, they prefer inline styling (

TamTam is a gem created by Dave Hoover and Brian Tatnall that does all the dirty work for us. Before Rails 3 there was a plugin called inline_css (by the same authors) that used TamTam to automatically inlined all mails sent by ActionMailer. Since Rails 3, however, the ActionMailer internals have changed, and the plugin stopped working.

For my own use I created a module called InlineCss that I include in the mailers I need inlining for. This is the code:

module InlineCss
  def render(*args)
    if (template = args.first[:template]) && template.mime_type.html?
      # Be warned, this code expects a <style> tag in the head of your layout.
      TamTam.inline(:document => super)

This code sees if I am working with a template and if that template has a HTML MIME-type, it inline’s it with TamTam.

In my mailers I just include it. If you want to have this in all mailers, just add an initializer that includes InlineCss in ActionMailer::Base, and it should work