Formatting Email Messages Using Templates

Problem

Contributed by: Dae San Hwang

You want more control over the format and layout of your messages than a generator gives you. You want to format email messages using template files.

Solution

This solution uses the CustomerMailer class from ."

app/model/customer_mailer.rb:

class CustomerMailer < ActionMailer::Base
 def welcome_message(cust_name, cust_email)
 @subject = "Welcome to Our Site"
 @body = {:name => cust_name, :email => cust_email}
 @recipients = cust_email
 @from = "webmaster@yourwebsite.com"
 @sent_on = Time.now
 end end

Note that @body is now assigned a Hash object instead of a String. This Hash object is used to pass variables to the Action View template.

When you generated the CustomerMailer class, the mailer generator also created a template file for the welcome_message method in app/views/customer_mailer directory. The template file for the welcome_message method is named welcome_message.rhtml.

Each key/value pair stored as a Hash member in @body is available as simple instance variables in welcome_message.rhtm l.

app/views/customer_mailer/welcome_message.rhtml:

Welcome, <%=@name %>
Thank you for registering!
Use your email address (<%=email %>) and password to log in.

Discussion

Other important instance variables you can set in the welcome_message method are @cc, @bcc, and @content_type. You can also compose the body of your email in HTML:

app/views/customer_mailer/welcome_message.rhtml:

<div style='background-color: #DDD; color: #555;'>
 <h3>Welcome, <%=@name %></h3>
 <p>Thank you for registering!</p>
 <p>Use your <em>email address (<%=email %>)</em> and <em>password</em> to log in.</p>
</div>

When you send HTML email, you need to set @content_type to "text/html" unless you have already configured default_content_type to "text/html" in config/environment.rb.

See Also