More at Overview | Download | Deploy | Code | Screencasts | Documentation | Ecosystem | Community | Blog

Action Mailer Basics

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

This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.

1 Introduction

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

2 Sending Emails

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

2.1 Walkthrough to Generating a Mailer

2.1.1 Create the Mailer
rails generate mailer UserMailer create app/mailers/user_mailer.rb invoke erb create app/views/user_mailer invoke test_unit create test/functional/user_mailer_test.rb

So we got the mailer, the fixtures, and the tests.

2.1.2 Edit the Mailer

app/mailers/user_mailer.rb contains an empty mailer:

class UserMailer < ActionMailer::Base default :from => "" end

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

class UserMailer < ActionMailer::Base default :from => "" def welcome_email(user) @user = user @url = "" mail(:to =>, :subject => "Welcome to My Awesome Site") end end

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

  • default Hash – This is a hash of default values for any email you send, in this case we are setting the :from header to a value for all messages in this class, this can be overridden on a per email basis
  • mail – The actual email message, we are passing the :to and :subject headers in.

Just like controllers, any instance variables we define in the method become available for use in the views.

2.1.3 Create a Mailer View

Create a file called welcome_email.html.erb in app/views/user_mailer/. This will be the template used for the email, formatted in HTML:

<!DOCTYPE html> <html> <head> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /> </head> <body> <h1>Welcome to, <%= %></h1> <p> You have successfully signed up to, your username is: <%= @user.login %>.<br/> </p> <p> To login to the site, just follow this link: <%= @url %>. </p> <p>Thanks for joining and have a great day!</p> </body> </html>

It is also a good idea to make a text part for this email, to do this, create a file called welcome_email.text.erb in app/views/user_mailer/:

Welcome to, <%= %> =============================================== You have successfully signed up to, your username is: <%= @user.login %>. To login to the site, just follow this link: <%= @url %>. Thanks for joining and have a great day!

When you call the mail method now, Action Mailer will detect the two templates (text and HTML) and automatically generate a multipart/alternative email.

2.1.4 Wire It Up So That the System Sends the Email When a User Signs Up

There are several ways to do this, some people create Rails Observers to fire off emails, others do it inside of the User Model. However, in Rails 3, mailers are really just another way to render a view. Instead of rendering a view and sending out the HTTP protocol, they are just sending it out through the Email protocols instead. Due to this, it makes sense to just have your controller tell the mailer to send an email when a user is successfully created.

Setting this up is painfully simple.

First off, we need to create a simple User scaffold:

$ rails generate scaffold user name:string email:string login:string $ rake db:migrate

Now that we have a user model to play with, we will just edit the app/controllers/users_controller.rb make it instruct the UserMailer to deliver an email to the newly created user by editing the create action and inserting a call to UserMailer.welcome_email right after the user is successfully saved:

class UsersController < ApplicationController # POST /users # POST /users.xml def create @user =[:user]) respond_to do |format| if # Tell the UserMailer to send a welcome Email after save UserMailer.welcome_email(@user).deliver format.html { redirect_to(@user, :notice => 'User was successfully created.') } format.xml { render :xml => @user, :status => :created, :location => @user } else format.html { render :action => "new" } format.xml { render :xml => @user.errors, :status => :unprocessable_entity } end end end end

This provides a much simpler implementation that does not require the registering of observers and the like.

The method welcome_email returns a Mail::Message object which can then just be told deliver to send itself out.

In previous versions of Rails, you would call deliver_welcome_email or create_welcome_email however in Rails 3.0 this has been deprecated in favour of just calling the method name itself.

Sending out one email should only take a fraction of a second, if you are planning on sending out many emails, or you have a slow domain resolution service, you might want to investigate using a background process like delayed job.

2.2 Auto encoding header values

Action Mailer now handles the auto encoding of multibyte characters inside of headers and bodies.

If you are using UTF-8 as your character set, you do not have to do anything special, just go ahead and send in UTF-8 data to the address fields, subject, keywords, filenames or body of the email and ActionMailer will auto encode it into quoted printable for you in the case of a header field or Base64 encode any body parts that are non US-ASCII.

For more complex examples, such as defining alternate character sets or self encoding text first, please refer to the Mail library.

2.3 Complete List of Action Mailer Methods

There are just three methods that you need to send pretty much any email message:

  • headers – Specifies any header on the email you want, you can pass a hash of header field names and value pairs, or you can call headers[:field_name] = ‘value’
  • attachments – Allows you to add attachments to your email, for example attachments[‘file-name.jpg’] =‘file-name.jpg’)
  • mail – Sends the actual email itself. You can pass in headers as a hash to the mail method as a parameter, mail will then create an email, either plain text, or multipart, depending on what email templates you have defined.
2.3.1 Custom Headers

Defining custom headers are simple, you can do it one of three ways:

  • Defining a header field as a parameter to the mail method:
mail("X-Spam" => value)
  • Passing in a key value assignment to the headers method:
headers["X-Spam"] = value
  • Passing a hash of key value pairs to the headers method:
headers {"X-Spam" => value, "X-Special" => another_value}

All X-Value headers per the RFC2822 can appear more than one time. If you want to delete an X-Value header, you need to assign it a value of nil.

2.3.2 Adding Attachments

Adding attachments has been simplified in Action Mailer 3.0.

  • Pass the file name and content and Action Mailer and the Mail gem will automatically guess the mime_type, set the encoding and create the attachment.
attachments['filename.jpg'] ='/path/to/filename.jpg')

Mail will automatically Base64 encode an attachment, if you want something different, pre encode your content and pass in the encoded content and encoding in a Hash to the attachments method.

  • Pass the file name and specify headers and content and Action Mailer and Mail will use the settings you pass in.
encoded_content = SpecialEncode('/path/to/filename.jpg')) attachments['filename.jpg'] = {:mime_type => 'application/x-gzip', :encoding => 'SpecialEncoding', :content => encoded_content }

If you specify an encoding, Mail will assume that your content is already encoded and not try to Base64 encode it.

2.3.3 Making Inline Attachments

Inline attachments are now possible in ActionMailer. While previously in the pre 3.0 version of Rails, you could do inline attachments, it involved a lot of hacking and determination to pull it off.

ActionMailer now makes inline attachments as trivial as they should be.

  • Firstly, to tell Mail to turn an attachment into an inline attachment, you just call #inline on the attachments method within your Mailer:
def welcome attachments.inline['image.jpg'] ='/path/to/image.jpg') end
  • Then in your view, you can just reference attachments[] as a hash and specify which attachment you want to show, calling url on it and then passing the result into the image_tag method:
<p>Hello there, this is our image</p> <%= image_tag attachments['image.jpg'].url %>
  • As this is a standard call to image_tag you can pass in an options hash after the attachment url as you could for any other image:
<p>Hello there, this is our image</p> <%= image_tag attachments['image.jpg'].url, :alt => 'My Photo', :class => 'photos' %>

2.4 Mailer Views

Mailer views are located in the app/views/name_of_mailer_class directory. 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.text.erb for the plain text version.

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

class UserMailer < ActionMailer::Base default :from => "" def welcome_email(user) @user = user @url = "" mail(:to =>, :subject => "Welcome to My Awesome Site") do |format| format.html { render 'another_template' } format.text { render 'another_template' } end end end

Will render ‘another_template.text.erb’ and ‘another_template.html.erb’. The render command is the same one used inside of Action Controller, so you can use all the same options, such as :text etc.

2.5 Action Mailer Layouts

Just like controller views, you can also have mailer layouts. The layout name needs to be the same as your mailer, such as user_mailer.html.erb and user_mailer.text.erb to be automatically recognized by your mailer as a layout.

In order to use a different file just use:

class UserMailer < ActionMailer::Base layout 'awesome' # use awesome.(html|text).erb as the layout end

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

You can also pass in a :layout => ‘layout_name’ option to the render call inside the format block to specify different layouts for different actions:

class UserMailer < ActionMailer::Base def welcome_email(user) mail(:to => do |format| format.html { render :layout => 'my_layout' } format.text end end end

Will render the HTML part using the my_layout.html.erb file and the text part with the usual user_mailer.text.erb file if it exists.

2.6 Generating URLs in Action Mailer Views

URLs can be generated in mailer views using url_for or named routes.

Unlike controllers, the mailer instance doesn’t have any context about the incoming request so 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:

<%= user_url(@user, :host => "") %>

Email clients have no web context and so paths have no base URL to form complete web addresses. Thus, when using named routes only the “_url” variant makes sense.

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:

class UserMailer < ActionMailer::Base default_url_options[:host] = "" def welcome_email(user) @user = user @url = user_url(@user) mail(:to =>, :subject => "Welcome to My Awesome Site") end end

2.7 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.text.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.

The order of the parts getting inserted is determined by the :parts_order inside of the ActionMailer::Base.default method. If you want to explicitly alter the order, you can either change the :parts_order or explicitly render the parts in a different order:

class UserMailer < ActionMailer::Base def welcome_email(user) @user = user @url = user_url(@user) mail(:to =>, :subject => "Welcome to My Awesome Site") do |format| format.html format.text end end end

Will put the HTML part first, and the plain text part second.

2.8 Sending Emails with Attachments

Attachments can be added by using the attachment method:

class UserMailer < ActionMailer::Base def welcome_email(user) @user = user @url = user_url(@user) attachments['terms.pdf'] ='/path/terms.pdf') mail(:to =>, :subject => "Please see the Terms and Conditions attached") end end

The above will send a multipart email with an attachment, properly nested with the top level being multipart/mixed and the first part being a multipart/alternative containing the plain text and HTML email messages.

3 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:

  • Implement a receive method in your mailer.
  • Configure your email server to forward emails from the address(es) you would like your app to receive to /path/to/app/script/rails runner 'UserMailer.receive('.

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 receive instance 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 end

4 Using Action Mailer Helpers

Action Mailer now just inherits from Abstract Controller, so you have access to the same generic helpers as you do in Action Controller.

5 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.

5.1 Example Action Mailer Configuration

An example would be adding the following to your appropriate config/environments/env.rb file:

config.action_mailer.delivery_method = :sendmail # Defaults to: # config.action_mailer.sendmail_settings = { # :location => '/usr/sbin/sendmail', # :arguments => '-i -t' # } config.action_mailer.perform_deliveries = true config.action_mailer.raise_delivery_errors = true

5.2 Action Mailer Configuration for GMail

As Action Mailer now uses the Mail gem, this becomes as simple as adding to your config/environments/env.rb file:

config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { :address => "", :port => 587, :domain => '', :user_name => '<username>', :password => '<password>', :authentication => 'plain', :enable_starttls_auto => true }

6 Mailer Testing

By default Action Mailer does not send emails in the test environment. They are just added to the ActionMailer::Base.deliveries array.

Testing mailers normally involves two things: One is that the mail was queued, and the other one that the email is correct. With that in mind, we could test our example mailer from above like so:

class UserMailerTest < ActionMailer::TestCase def test_welcome_email user = users(:some_user_in_your_fixtures) # Send the email, then test that it got queued email = UserMailer.deliver_welcome_email(user) assert !ActionMailer::Base.deliveries.empty? # 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_match /<h1>Welcome to, #{}<\/h1>/, email.encoded assert_match /Welcome to, #{}/, email.encoded end end

In the test we send the email and store the returned object in the email variable. We then ensure that it was sent (the first assert), then, in the second batch of assertions, we ensure that the email does indeed contain the what we expect.

7 Changelog

Lighthouse ticket