Sending Liquid-based Email with Rails

April 19, 2008

Many applications send emails out to users when certain actions happen, such as placing an order. Sometimes the contents of those emails can change frequently, so it is a nice feature is to be able to give the administrative users of your system a way to change the contents of those emails.

One way to do it is to use the Liquid templating language. The reason Liquid is a good choice is that Liquid is "non-evaling", which means you can just execute arbitrary Ruby code from within a Liquid template. This isn't true of ERB, for example, where you could just put <% something_evil %> in the middle of a template and it would get executed. So if you were to give your users a way to edit the the template and it was using ERB, you would have a potential security problem.

So create a rails app:

$ rails liquid

Then make sure you have the liquid gem installed:

$ sudo gem install liquid

Then require liquid in your config/environment.rb (sidenote: edge rails has a better way of doing this)

require 'liquid'

Next we'll create the model and interface for letting users edit the mail templates:

$ script/generate scaffold mail_template name:string body:text
$ rake db:migrate

Now you can create a new mail template through the browser or just using IRB:

$ script/console
>> MailTemplate.create!(:name => "order_confirmation", 
  :body => "Dear {{name}},\n\nThank you for your order!")

There you can see the very basic syntax of a Liquid template. The {{name}} is a variable that will get replace with content when we render the template. Now we'll generate a mailer:

$ script/generate mailer OrderMailer order_confirmation

Now we have to modify the OrderMailer to use our Liquid template stored in the database. Edit app/models/order_mailer.rb so that it has the following contents:

class OrderMailer < ActionMailer::Base

  def order_confirmation(sent_at = Time.now)
    @from       = 'orders@yoursite.com'
    @recipients = 'some_customer@whatever.com'
    @subject    = 'Order Confirmation'
    @body       = {"name" => "Paul"}
    @sent_on    = sent_at
    @headers    = {}
  end

  def render_message(method_name, body)
    mail_template = MailTemplate.find_by_name(method_name)
    template = Liquid::Template.parse(mail_template.body)
    template.render body
  end

end

The order_confirmation method should look familiar, it is the almost the same as it would be for any regular mailer. One caveat is that Liquid expects the keys in the context hash that you pass to it to be strings, not symbols. The @body instance variable is the context hash that will be passed to Liquid. Those are the variables that you will have access to when the template renders.

The real work is happening in the render_message method. This is the method that the mailer calls when delivering your message. Normally you don't need to override this method, it takes care of finding the ERB template and rendering it for you. We can override it here to look for our Liquid template from the database. The first argument to the method will be set to the method name of the mailer, which in this case is order_confirmation. The second argument will be the value that we set @body to in the order_confirmation method. This makes for a pretty clean way of doing this, hooking in our Liquid functionality using the standard object-oriented technique of overriding a method, no monkey patching required, which should make Avdi proud!

Make sure you've started the app with script/server and then go into script/console and enter this:

>> OrderMailer.deliver_order_confirmation

Now in the output from script/server, you should see something like this:

Sent mail:
 Date: Sat, 19 Apr 2008 06:41:53 -0400
From: orders@yoursite.com
To: some_customer@whatever.com
Subject: Order Confirmation
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8

Dear Paul,

Thank you for your order!

Editorial: 4 years ago, Matt Raible posted an article to the The Server Side titled Sending Velocity-based Email with Spring. Consider this the Ruby equivalent to that article. Compare the amount of code/configuration required to accompish this task in Java/J2EE vs. Ruby on Rails. Also, the Ruby version is more complicated because it involves storing/retrieving the templates from the database rather than the file system. If we were just retrieving the templates from the file system, this probably would have been a 2 line article. This is just another example of how much simpler Rails makes things when compared to Java/J2EE.

Posted in Technology | Tags Rails, Liquid, Ruby

Comments Comments Feed

1. Out of curiousity, since this is the first real useage of liquid outside of 'hi Tobi' kind of tutorials....

I keep reading the propaganda for liquid from 2006, i'm sure you've seen it. Where they mention 'if you want to sever your templates from the database'.

Do you use liquid often? Can you serve them from a db? Other then the security factor, which is big, what advantages are there to liquid over erb, or even just a good css file? i mean if you don't want a user to mess with any ruby but want to allow a user to upload css files to an asset server or something?

liquid from a db, and having the user's site admin select a db housed template, would be great... just ain't no info on it. thoughts?

# Posted By pjam on Tuesday, July 29 2008 at 9:46 PM

2. Thanks for the this! It helped out a lot.

# Posted By rob on Friday, October 2 2009 at 12:55 PM

3. brian atwood maniac pumps the perfect wear-with-everything color. These wardrobe staples have 5" stiletto heels and hidden 1 1/2" seamless platforms. These Brian Atwood 'Loca' studded pumps are so ravishing, that I'd totally be willing to pop an aspirin before wearing them. And I really lovebrian atwood mesh sandals and Brian Atwood Asymmetric Patent Pumps.brian atwood nude patent leather katie lee pumps. Bold shoes like these sculptural purple suede Brian Atwood 'Lola' pumps make an outfit. purple suede Brian Atwood 'Lola' pumpswith a heel that measures approximately 140mm / 5.5 inches with a 30mm / 1 inch concealed platform. Brian Atwood pumps have a closed toe, cutout detail at arch with elasticated straps and a leather sole.
Herve Leger Dress shop specialises in superior Herve Leger Dress, provides hundreds of discount and fashion Herve Leger Dress, sexy Herve Leger Dress, Herve Leger Skirt, disount Herve Leger Dress-a professional Herve Leger Shop.

# Posted By Brian Atwood maniac pumps on Saturday, August 28 2010 at 6:32 AM

4. Wonderful brian atwood shoes for your style.BRIAN ATWOOD High-heeled sandals Purple is in stock in our store only one size in 36.5 EU. Elegant purple color, you will like it.
And these Pink Brian Atwood Maniac Patent Platform Pumps not only romantic and gorgeous too! It's patent leather leave us sunshine warmness and sexy!
When I original saw these brian atwood loca studded pumps in a metallic version, a while ago, I likeable them OK, but now I am going unhinged for the lavender version!
I really love brian atwood nico patent pump.
And this year, brian atwood maniac pumps are so hot among stars, I saw many times that Victoria-Beckham wearing them on the show time.
If you don’t know about brian atwood…You should. When everyone else is obsessing over the latest pair of Loubs or YS’L’s it’s very easy to overlook awesome shoe lines and designers who push the envelope. brian atwood is one of those designers.I’m a fan of his lines because Atwood really sets out to make his shoes a conversation piece. The use of alternative textures and fabrics makes brian atwood shoes unique. When wearing his shoes you are guaranteed a compliment from someone and a definate shoe in for best footwear. So ladies (and gents) get into these! And I know my card carrying “Shoe Wh*res” are going to love these!
Buy brian atwood shoes at http://www.brianatwoodcom.com. Buy brian atwood pumps at http://www.brianatwoodcom.com/brian-atwood-brian-atwood-pumps-c-65_67.html.
When I original saw these brian atwood loca studded pumps in a metallic version, a while ago, I likeable them OK, but now I am going unhinged for the lavender version!
When it comes to intricate detailing and superb craftsmanship, you know a pair of brian atwood lexia is worth the investment.
Back by popular demand... brian atwood maniac tan, the perfect wear-with-everything color. These wardrobe staples have 5" stiletto heels and hidden 1 1/2" seamless platforms. In a beautiful, very neutral nude tan.
brian atwood whip snake shoe with Exotic whipsnake hidden platform and back metal inset.
Take a walk on the wild side with Atwood Jagger printed knee-high boots. Style them knee high to add sass to an LBD or wear them with the fold-over flap turned up to work this season's hot over-the-knee trend.
brian atwood cage peep Price: $228. 140mm Covered heel. Rounded peep toe. 40mm covered platform. Interwoven cut outs around front. Ankle strap with adjustable metal buckle. Leather insole and lining. Leather sole. Made in Italy.
When it comes to intricate detailing and superb craftsmanship, you know a pair of brian atwood crystal court shoe is worth the investment.
Brian Atwood Platform Chain Pumps with A silver chain scales the lace-up back of this vamped-up pumps.
brian atwood snakeskin platforms is the classic and the elastic heel detail was used again from last Fall.
brian atwood patent leather and mesh Futuristic patent leather style with mesh details and contrast stitching.
Heel measures approximately 95mm/ 3.5 inches. Let your feet do the talking in brian atwood dorota shoes. Wear this chic style with off-duty denim or to liven up office looks.

# Posted By Brian Atwood loca studded pumps on Saturday, August 28 2010 at 6:33 AM

5. A grand wedding on the beach may be the common dream of most single girls. The bright sunshine, the blue sky and the open sea can satisfy all the demands of the romantic girls. Of course, everything will be perfect with a beach wedding dresses.
Every woman deserve the most beautiful wedding dresses at her special day!The most beautiful smile in the word is belong to the brides when she find her wedding dresses!Love is the time when you slows down in front of the shops selling wedding dresses.
Make the day of your engagement a special one with a A-line or princess wedding dresses!Step like a goddess in tea- length ball gowns,formal ball gowns,victorian ball gowns,debutante ball gowns,prom ball gowns, contemporary ball gownsand vintage ball gowns available in chiffon, organza, silk and satin only at weddingdressesnow.com.
Congratulations! Your little daughter is getting married! But being the mother of the bride (or MOB) is not an easy role. Once upon a time mothers of the bride did most of the wedding planning, and thus got to have their own dreams realized. First of all, choose one from the perfect mother of the bride dresses for yourself here and to be the most elegant mother of bride!
Flower girl dresses must be the perfect accessory for the bride's dress. The flower girls look like the bells ring in the wedding announcements as they toll down the aisle one by one or hand in hand. If you are having flower girls at your wedding, take a look at these beautiful selection of Flower girl dresses from http://www.weddingdressesin.com.

# Posted By A line wedding dresses on Saturday, August 28 2010 at 6:33 AM

6. nice sharing thanks, # Posted By wholesale accessories on Saturday, August 28 2010 at 2:00 PM

7. Find ugg and Australian sheepskin boots, learn the history behind the Ugg boot, and when and what to wear with Cheap ugg boots, as well as cleaning and caring forAuthentic Ugg boots,Cheap ugg cardy boots,20%-40% high discount

# Posted By p on Wednesday, September 1 2010 at 2:13 PM

8. If you are a soccer fan so this is a right place for you to shop your soccer nfl jerseys. nfl store is the vital element uniform. Whatever your budget isnew nfl jerseys , through our wide selection we guarantee we have the right apparel for you. We guarantee the lowest prices in the market; nfl jerseys replica if you get a quote from our competitors with a lower price we will match it for you.

# Posted By fewrewree on Wednesday, September 1 2010 at 7:20 PM

9. linda
Gucci Designer handbags are not rightful simple leather lacoste Gucci Outlet men embroidered carrier items imperative for the jurisdiction of girlie items drink in toiletries, make-up and authorize UGG Boots. No girlfriend! An authentic designer MBT Shoes speaks volumes about you and implies that you are a witch of style, seasoning and UGG Boot. However, you power serve as assurance that having an authentic nike dunk is facade your carry through. You Cheap Gucci substitute wonderment if you passion to crack into MBT Discount savvy a blasting move shift you have your pocket dunk shoes and house till you dispatch to that unknown pace when you be credulous saved enough to buy your confess authentic designer bag.

# Posted By nike dunk on Thursday, September 2 2010 at 2:11 AM

10. Coach
Coach handbags
Coach bags
replica Coach

# Posted By ss on Thursday, September 2 2010 at 7:46 AM

Add a Comment

(If you leave this blank, your IP address will be displayed instead)

(Optional, will not be displayed on the site)