Despite my personal opinion that the only valid format for email is plaintext ASCII clients still insist on their webapps sending HTML emails. Although Rails' ActionMailer does almost everything one could want when it comes to 'pretty' emails, I find it to be deficient in one area: caching.

If you look at any HTML formatted mail-shot it'll usually contain the legend "To view this online, click here". The main reason for this being that most email tools suck at rendering HTML. Therefore, it makes sense to give the recipient the chance to view the message in their browser. To do this, the originating system can't fire-and-forget email; it needs to cache a version for viewing online.

Has_web_fallback gives you transparent, easy caching of ActionMailer HTML emails. We make extensive use of it at itison.com as you can see from this sample welcome email.

An example speaks a thousand words:

    class MemberMailer  < ActionMailer::Base
    
      has_web_fallback :signup_complete, :keep_for=>7.days
    
       def signup_complete(user)
        # ...
       end
    
       def recover_password 
       end
    end

In the view, an instance variable pointing to the cache URL is generated automatically.

    <p>If you're having difficulty viewing this email,<%= link_to "view it online.", APPLICATION_URL+@web_fallback_url %></p>

This assumes that you have set an APPLICATION_URL constant, of course. Everyone has a different way of dealing with the absolute URL in mailer templates so that's left to your own taste.

MemberMailer.deliver_signup_complete(user)

This will send the email as you'd expect, but also writes the HTML portion of the message to public/system/#class#/#action#/#uuid#. To help with housekeeping, the gem comes with a pair of rake tasks for dealing with out-of-date caches.

    rake has_web_fallback:clean CLASS=MemberMailer
    rake has_web_fallback:clean_all

Any cached message that's older than its declared lifespan (defaulting to 7 days) will be deleted.

Has_web_fallback is entirely transparent to the rest of the application and should play nicely with most setups. You can use it as a plugin from Github or a gem from Gemcutter. Issues can be reported on Github and alll feedback is welcomed.

Leave a Comment

You can use the Markdown for links, strong, and emphasis tags in your comment.

From Nov 8th, 2009.

This article is tagged with ruby, rails, actionmailer, projects, and email.

Commenting is currently enabled. There are 0 comments so far.

Related Articles.

Easy user data with TextExpander

Nabaztag.

Mass attribute assignment in Rails.

has_web_fallback

Nesting Snippets In TextExpander.