Skip to content
Find file
Fetching contributors…
Cannot retrieve contributors at this time
423 lines (302 sloc) 20.6 KB

Action Mailer Basics

This guide should provide you with all you need to get started in sending and receiving emails from/to your application, and many internals of Action Mailer. It will also cover how to test your mailers.



Action Mailer allows you to send emails from your application using a mailer model and views.
So, in Rails, emails are used by creating models that inherit from ActionMailer::Base that live alongside other models in `app/models`. Those models have associated views that appear alongside controller views in `app/views`.

Sending Emails

This section will provide a step-by-step guide to creating a mailer and its views.

Walkthrough to generating a mailer

Create the mailer:

./script/generate mailer UserMailer
exists app/models/
create app/views/user_mailer
exists test/unit/
create test/fixtures/user_mailer
create app/models/user_mailer.rb
create test/unit/user_mailer_test.rb

So we got the model, the fixtures, and the tests all created for us

Edit the model:

Opening app/models/user_mailer.rb, you should see the empty mailer:

class UserMailer < ActionMailer::Base

Lets add a method called welcome_email, that will send an email to the user’s registered email address:

class UserMailer < ActionMailer::Base

def welcome_email(user) recipients from “My Awesome Site Notifications <>” subject “Welcome to My Awesome Site” sent_on body {:user => user, :url => “”} content_type “text/html” end


Here is a quick explanation of the options presented in the preceding method. For a full list of all available options, please have a look further down at the Complete List of ActionMailer user-settable attributes section.

recipients The recipients of the email. It can be a string or, if there are multiple recipients, an array of strings
from Who the email will appear to come from in the recipients’ mailbox
subject The subject of the email
sent_on Timestamp for the email
content_type The content type, by default is text/plain

The keys of the hash passed to `body` become instance variables in the view. Thus, in our example the mailer view will have a @user and a @url instance variables available.

Create the mailer view

Create a file called welcome_email.html.erb in #{RAILS_ROOT}/app/views/user_mailer/. This will be the template used for the email. This file will be used for html formatted emails. Had we wanted to send text-only emails, the file would have been called welcome_email.txt.erb, and we would have set the content type to text/plain in the mailer model.

The file can look like:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “”>

Welcome to, <%=h @user.first_name %>

You have successfully signed up to, and your username is: <%= @user.login %>.
To login to the site, just follow this link: <%=h @url %>.

Thanks for joining and have a great day!

Wire it up so that the system sends the email when a user signs up

There are three ways to achieve this. One is to send the email from the controller that sends the email, another is to put it in a before_create callback in the user model, and the last one is to use an observer on the user model. Whether you use the second or third methods is up to you, but staying away from the first is recommended. Not because it’s wrong, but because it keeps your controller clean, and keeps all logic related to the user model within the user model. This way, whichever way a user is created (from a web form, or from an API call, for example), we are guaranteed that the email will be sent.

Let’s see how we would go about wiring it up using an observer:

In config/environment.rb:

  1. Code that already exists do |config|
  2. Code that already exists
    config.active_record.observers = :user_observer

You can place the observer in app/models where it will be loaded automatically by Rails. Another option is to create an app/observers folder to store all your observers, and add that to your load path. Open config/environment.rb and make it look like:

  1. Code that already exists do |config|
  2. Code that already exists
    config.load_paths += %W(#{RAILS_ROOT}/app/observers)
    config.active_record.observers = :user_observer

Now create a file called user_observer in app/models or app/observers depending on where you stored it, and make it look like:

class UserObserver < ActiveRecord::Observer
def after_create(user)

Notice how we call deliver_welcome_email? In Action Mailer we send emails by calling deliver_name_of_method. In UserMailer, we defined a method called welcome_email, and so we deliver the email by calling deliver_welcome_email. The next section will go through how Action Mailer achieves this.

Action Mailer and dynamic deliver_ methods

So how does Action Mailer understand this deliver_welcome_email call? If you read the documentation (, you will find this in the “Sending Emails” section:

You never instantiate your mailer class. Rather, your delivery instance methods are automatically wrapped in class methods that start with the word deliver_ followed by the name of the mailer method that you would like to deliver.

So, how exactly does this work?

Looking at the ActionMailer::Base source, you will find this:

def method_missing(method_symbol, parameters)#:nodoc:
case method_symbol.id2name
when /^create_([_a-z]\w
)/ then new($1, parameters).mail
when /^deliver_([_a-z]\w
)/ then new($1, *parameters).deliver!
when “new” then nil
else super

Hence, if the method name starts with deliver_ followed by any combination of lowercase letters or underscore, method_missing calls new on your mailer class (UserMailer in our example above), sending the combination of lower case letters or underscore, along with the parameters. The resulting object is then sent the deliver! method, which well… delivers it.

Complete List of ActionMailer user-settable attributes

bcc Specify the BCC addresses for the message
body Define the body of the message. This is either a Hash (in which case it specifies the variables to pass to the template when it is rendered), or a string, in which case it specifies the actual text of the message.
cc Specify the CC addresses for the message.
charset Specify the charset to use for the message. This defaults to the default_charset specified for ActionMailer::Base.
content_type Specify the content type for the message. This defaults to <text/plain in most cases, but can be automatically set in some situations.
from Specify the from address for the message.
reply_to Specify the address (if different than the “from” address) to direct replies to this message.
headers Specify additional headers to be added to the message.
implicit_parts_order Specify the order in which parts should be sorted, based on content-type. This defaults to the value for the default_implicit_parts_order.
mime_version Defaults to “1.0”, but may be explicitly given if needed.
recipient The recipient addresses for the message, either as a string (for a single address) or an array (for multiple addresses).
sent_on The date on which the message was sent. If not set (the default), the header will be set by the delivery agent.
subject Specify the subject of the message.
template Specify the template name to use for current message. This is the “base” template name, without the extension or directory, and may be used to have multiple mailer methods share the same template.

Mailer Views

Mailer views are located in /app/views/name_of_mailer_class. The specific mailer view is known to the class because it’s name is the same as the mailer method. So for example, in our example from above, our mailer view for the welcome_email method will be in /app/views/user_mailer/welcome_email.html.erb for the html version and welcome_email.txt.erb for the plain text version.

To change the default mailer view for your action you do something like:

class UserMailer < ActionMailer::Base

def welcome_email(user) recipients from “My Awesome Site Notifications<>” subject “Welcome to My Awesome Site” sent_on body {:user => user, :url => “”} content_type “text/html”
  1. change the default from welcome_email.[html, txt].erb
    template “some_other_template” # this will be in app/views/user_mailer/some_other_template.[html, txt].erb


Action Mailer Layouts

Just like controller views, you can also have mailer layouts. The layout name needs to end in mailer to be automatically recognized by your mailer as a layout. So in our UserMailer example, we need to call our layout usermailer.[html,txt].erb. In order to use a different file just use:

class UserMailer < ActionMailer::Base

layout ‘awesome’ # will use awesome.html.erb as the layout


Just like with controller views, use yield to render the view inside the layout.

Generating URL’s in Action Mailer views

URLs can be generated in mailer views using url_for or named routes.
Unlike controllers from Action Pack, the mailer instance doesn’t have any context about the incoming request, so you’ll need to provide all of the details needed to generate a URL.

When using url_for you’ll need to provide the :host, :controller, and :action:

<%= url_for(:host => “”, :controller => “welcome”, :action => “greeting”) %>

When using named routes you only need to supply the :host:

<%= users_url(:host => “”) %>

You will want to avoid using the name_of_route_path form of named routes because it doesn’t make sense to generate relative URLs in email messages. The reason that it doesn’t make sense is because the email is opened on a mail client outside of your environment. Since the email is not being served by your server, a URL like “/users/show/1”, will have no context. In order for the email client to properly link to a URL on your server it needs something like “”.

It is also possible to set a default host that will be used in all mailers by setting the :host option in
the ActionMailer::Base.default_url_options hash as follows:

ActionMailer::Base.default_url_options[:host] = “”

This can also be set as a configuration option in config/environment.rb:

config.action_mailer.default_url_options = { :host => “” }

If you do decide to set a default :host for your mailers you will want to use the :only_path => false option when using url_for. This will ensure that absolute URLs are generated because the url_for view helper will, by default, generate relative URLs when a :host option isn’t explicitly provided.

Sending multipart emails

Action Mailer will automatically send multipart emails if you have different templates for the same action. So, for our UserMailer example, if you have welcome_email.txt.erb and welcome_email.html.erb in app/views/user_mailer, Action Mailer will automatically send a multipart email with the html and text versions setup as different parts.

To explicitly specify multipart messages, you can do something like:

class UserMailer < ActionMailer::Base

def welcome_email(user) recipients user.email_address subject “New account information” from “” content_type “multipart/alternative” part :content_type => “text/html”, :body => “

html content, can also be the name of an action that you call

” part “text/plain” do |p| p.body = “text content, can also be the name of an action that you call” end end


Sending emails with attachments

Attachments can be added by using the attachment method:

class UserMailer < ActionMailer::Base

def welcome_email(user) recipients user.email_address subject “New account information” from “” content_type “multipart/alternative” attachment :content_type => “image/jpeg”, :body =>“an-image.jpg”) attachment “application/pdf” do |a| a.body = generate_your_pdf_here() end end


Receiving Emails

Receiving and parsing emails with Action Mailer can be a rather complex endeavour. Before your email reaches your Rails app, you would have had to configure your system to somehow forward emails to your app, which needs to be listening for that.
So, to receive emails in your Rails app you’ll need:

1. Configure your email server to forward emails from the address(es) you would like your app to receive to /path/to/app/script/runner \‘UserMailer.receive(’

2. Implement a receive method in your mailer

Once a method called receive is defined in any mailer, Action Mailer will parse the raw incoming email into an email object, decode it, instantiate a new mailer, and pass the email object to the mailer object‘s receive method. Here’s an example:

class UserMailer < ActionMailer::Base

def receive(email) page = Page.find_by_address( page.emails.create( :subject => email.subject, :body => email.body ) if email.has_attachments? for attachment in email.attachments page.attachments.create({ :file => attachment, :description => email.subject }) end end end


Using Action Mailer Helpers

Action Mailer classes have 4 helper methods available to them:

add_template_helper(helper_module) Makes all the (instance) methods in the helper module available to templates rendered through this controller.
helper(*args, &block) Declare a helper: helper :foo requires ‘foo_helper’ and includes FooHelper in the template class. helper FooHelper includes FooHelper in the template class. helper { def foo() “#{bar} is the very best” end } evaluates the block in the template class, adding method foo. helper(:three, BlindHelper) { def mice() ‘mice’ end } does all three.
helper_method Declare a controller method as a helper. For example, helper_method :link_to def link_to(name, options) … end makes the link_to controller method available in the view.
helper_attr Declare a controller attribute as a helper. For example, helper_attr :name attr_accessor :name makes the name and name= controller methods available in the view. The is a convenience wrapper for helper_method.

Action Mailer Configuration

The following configuration options are best made in one of the environment files (environment.rb, production.rb, etc…)

template_root Determines the base from which template references will be made.
logger the logger is used for generating information on the mailing run if available. Can be set to nil for no logging. Compatible with both Ruby’s own Logger and Log4r loggers.
smtp_settings Allows detailed configuration for :smtp delivery method: :address – Allows you to use a remote mail server. Just change it from its default “localhost” setting. :port – On the off chance that your mail server doesn’t run on port 25, you can change it. :domain – If you need to specify a HELO domain, you can do it here. :user_name – If your mail server requires authentication, set the username in this setting. :password – If your mail server requires authentication, set the password in this setting. :authentication – If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of :plain, :login, :cram_md5.
sendmail_settings Allows you to override options for the :sendmail delivery method. :location – The location of the sendmail executable. Defaults to /usr/sbin/sendmail. :arguments – The command line arguments. Defaults to -i -t.
raise_delivery_errors Whether or not errors should be raised if the email fails to be delivered.
delivery_method Defines a delivery method. Possible values are :smtp (default), :sendmail, and :test.
perform_deliveries Determines whether deliver_* methods are actually carried out. By default they are, but this can be turned off to help functional testing.
deliveries Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.
default_charset The default charset used for the body and to encode the subject. Defaults to UTF-8. You can also pick a different charset from inside a method with charset.
default_content_type The default content type used for the main part of the message. Defaults to “text/plain”. You can also pick a different content type from inside a method with content_type.
default_mime_version The default mime version used for the message. Defaults to 1.0. You can also pick a different value from inside a method with mime_version.
default_implicit_parts_order When a message is built implicitly (i.e. multiple parts are assembled from templates which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to [“text/html”, “text/enriched”, “text/plain”]. Items that appear first in the array have higher priority in the mail client and appear last in the mime encoded message. You can also pick a different order from inside a method with implicit_parts_order.

Example Action Mailer Configuration

An example would be:

ActionMailer::Base.delivery_method = :sendmail
ActionMailer::Base.sendmail_settings = {
:location => ‘/usr/sbin/sendmail’,
:arguments => ‘-i -t’
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.default_charset = “iso-8859-1”

Action Mailer Configuration for GMail

Instructions copied from http://

First you must install the action_mailer_tls plugin from, then all you have to do is configure action mailer.

ActionMailer::Base.smtp_settings = {
:address => “”,
:port => 587,
:domain => “”,
:user_name => “”,
:password => “password”,
:authentication => :plain

Configure Action Mailer to recognize HAML templates

In environment.rb, add the following line:


Mailer Testing

Testing mailers involves 2 things. One is that the mail was queued and the other that the body contains what we expect it to contain. With that in mind, we could test our example mailer from above like so:

class UserMailerTest < ActionMailer::TestCase
tests UserMailer

def test_welcome_email user = users(:some_user_in_your_fixtures)
  1. Send the email, then test that it got queued
    email = UserMailer.deliver_welcome_email(user)
    assert !ActionMailer::Base.deliveries.empty?
  1. Test the body of the sent email contains what we expect it to
    assert_equal [],
    assert_equal “Welcome to My Awesome Site”, email.subject
    assert email.body =~ /Welcome to, #{user.first_name}/

What have we done? Well, we sent the email and stored the returned object in the email variable. We then ensured that it was sent (the first assert), then, in the second batch of assertion, we ensure that the email does indeed contain the values that we expect.


This guide presented how to create a mailer and how to test it. In reality, you may find that writing your tests before you actually write your code to be a rewarding experience. It may take some time to get used to TDD (Test Driven Development), but coding this way achieves two major benefits. Firstly, you know that the code does indeed work, because the tests fail (because there’s no code), then they pass, because the code that satisfies the tests was written. Secondly, when you start with the tests, you don’t have to make time AFTER you write the code, to write the tests, then never get around to it. The tests are already there and testing has now become part of your coding regimen.

Jump to Line
Something went wrong with that request. Please try again.