2018-07-23 22:29:31 -04:00
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.**
2014-12-23 17:32:50 -05:00
2012-09-01 17:25:58 -04:00
Action Mailer Basics
====================
2009-02-05 20:57:02 -05:00
2018-12-27 18:11:39 -05:00
This guide provides you with all you need to get started in sending
emails from and to your application, and many internals of Action
2013-04-05 07:42:21 -04:00
Mailer. It also covers how to test your mailers.
2009-02-05 20:57:02 -05:00
2012-11-29 17:25:02 -05:00
After reading this guide, you will know:
2018-12-27 18:11:39 -05:00
* How to send email within a Rails application.
2012-12-07 16:31:27 -05:00
* How to generate and edit an Action Mailer class and mailer view.
* How to configure Action Mailer for your environment.
* How to test your Action Mailer classes.
2013-04-05 07:42:21 -04:00
2012-09-01 17:25:58 -04:00
--------------------------------------------------------------------------------
2009-02-05 20:57:02 -05:00
2019-12-17 03:48:45 -05:00
What is Action Mailer?
----------------------
2009-02-05 20:57:02 -05:00
2014-06-10 15:03:10 -04:00
Action Mailer allows you to send emails from your application using mailer classes
2018-03-21 17:52:33 -04:00
and views.
2018-02-01 19:25:23 -05:00
#### Mailers are similar to controllers
2018-03-21 17:52:33 -04:00
They inherit from `ActionMailer::Base` and live in `app/mailers` . Mailers also work
very similarly to controllers. Some examples of similarities are enumerated below.
Mailers have:
2018-02-01 19:25:23 -05:00
2018-03-21 17:52:33 -04:00
* Actions, and also, associated views that appear in `app/views` .
* Instance variables that are accessible in views.
* The ability to utilise layouts and partials.
* The ability to access a params hash.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
Sending Emails
--------------
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
This section will provide a step-by-step guide to creating a mailer and its
views.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Walkthrough to Generating a Mailer
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
#### Create the Mailer
2009-02-05 20:57:02 -05:00
2012-09-01 20:45:26 -04:00
```bash
2019-01-22 03:53:47 -05:00
$ bin/rails generate mailer UserMailer
2010-01-31 22:57:54 -05:00
create app/mailers/user_mailer.rb
2014-11-24 20:49:29 -05:00
create app/mailers/application_mailer.rb
2010-01-31 22:57:54 -05:00
invoke erb
create app/views/user_mailer
2014-11-24 20:49:29 -05:00
create app/views/layouts/mailer.text.erb
create app/views/layouts/mailer.html.erb
2010-01-31 22:57:54 -05:00
invoke test_unit
2012-10-08 00:59:42 -04:00
create test/mailers/user_mailer_test.rb
2014-11-24 20:49:29 -05:00
create test/mailers/previews/user_mailer_preview.rb
```
```ruby
# app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
2014-12-24 11:12:47 -05:00
default from: "from@example.com"
2014-11-24 20:49:29 -05:00
layout 'mailer'
end
# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
As you can see, you can generate mailers just like you use other generators with
2018-03-21 17:52:33 -04:00
Rails.
2013-04-05 07:42:21 -04:00
If you didn't want to use a generator, you could create your own file inside of
2017-08-08 04:23:20 -04:00
`app/mailers` , just make sure that it inherits from `ActionMailer::Base` :
2013-04-05 07:42:21 -04:00
```ruby
class MyMailer < ActionMailer::Base
end
```
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
#### Edit the Mailer
2009-02-05 20:57:02 -05:00
2018-03-21 17:52:33 -04:00
Mailers have methods called "actions" and they use views to structure their content.
Where a controller generates content like HTML to send back to the client, a Mailer
creates a message to be delivered via email.
2013-04-05 07:42:21 -04:00
2012-09-01 19:34:21 -04:00
`app/mailers/user_mailer.rb` contains an empty mailer:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2014-11-24 20:49:29 -05:00
class UserMailer < ApplicationMailer
2009-02-05 20:57:02 -05:00
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
Let's add a method called `welcome_email` , that will send an email to the user's
registered email address:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2014-11-24 20:49:29 -05:00
class UserMailer < ApplicationMailer
2012-09-21 14:55:42 -04:00
default from: 'notifications@example.com'
2010-01-31 22:57:54 -05:00
2017-09-13 13:17:00 -04:00
def welcome_email
@user = params[:user]
2012-09-21 14:55:42 -04:00
@url = 'http://example.com/login'
2013-04-05 07:42:21 -04:00
mail(to: @user .email, subject: 'Welcome to My Awesome Site')
2009-02-05 20:57:02 -05:00
end
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
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.
2009-02-05 20:57:02 -05:00
2014-06-10 15:03:10 -04:00
* `default Hash` - This is a hash of default values for any email you send from
this mailer. 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.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
#### Create a Mailer View
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
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:
2009-02-05 20:57:02 -05:00
2012-09-03 21:21:24 -04:00
```html+erb
2010-01-31 22:57:54 -05:00
<!DOCTYPE html>
2009-02-05 20:57:02 -05:00
< html >
< head >
2012-09-21 14:55:42 -04:00
< meta content = 'text/html; charset=UTF-8' http-equiv = 'Content-Type' / >
2009-02-05 20:57:02 -05:00
< / head >
< body >
2010-01-31 22:57:54 -05:00
< h1 > Welcome to example.com, < %= @user .name %></ h1 >
2009-02-05 20:57:02 -05:00
< p >
2010-02-01 03:59:45 -05:00
You have successfully signed up to example.com,
2013-08-07 16:08:53 -04:00
your username is: < %= @user .login %>.< br >
2010-02-01 03:59:45 -05:00
< / p >
< p >
2010-01-31 22:57:54 -05:00
To login to the site, just follow this link: < %= @url %>.
2009-02-05 20:57:02 -05:00
< / p >
< p > Thanks for joining and have a great day!< / p >
< / body >
< / html >
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
Let's also make a text part for this email. Not all clients prefer HTML emails,
and so sending both is best practice. To do this, create a file called
`welcome_email.text.erb` in `app/views/user_mailer/` :
2010-01-31 22:57:54 -05:00
2012-09-01 17:08:06 -04:00
```erb
2010-01-31 22:57:54 -05:00
Welcome to example.com, < %= @user .name %>
===============================================
2010-02-01 03:59:45 -05:00
You have successfully signed up to example.com,
your username is: < %= @user .login %>.
2010-01-31 22:57:54 -05:00
To login to the site, just follow this link: < %= @url %>.
Thanks for joining and have a great day!
2012-09-01 17:08:06 -04:00
```
2010-01-31 22:57:54 -05:00
2013-04-05 07:42:21 -04:00
When you call the `mail` method now, Action Mailer will detect the two templates
(text and HTML) and automatically generate a `multipart/alternative` email.
2009-02-24 07:29:25 -05:00
2013-04-05 07:42:21 -04:00
#### Calling the Mailer
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
Mailers are really just another way to render a view. Instead of rendering a
2020-05-23 14:02:45 -04:00
view and sending it over the HTTP protocol, they are sending it out through
the email protocols instead. Due to this, it makes sense to have your
2013-04-05 07:42:21 -04:00
controller tell the Mailer to send an email when a user is successfully created.
2009-02-05 20:57:02 -05:00
2019-03-08 14:14:49 -05:00
Setting this up is simple.
2010-01-31 22:57:54 -05:00
2020-05-23 14:02:45 -04:00
First, let's create a `User` scaffold:
2010-01-31 22:57:54 -05:00
2012-09-01 20:45:26 -04:00
```bash
2019-01-22 03:53:47 -05:00
$ bin/rails generate scaffold user name email login
$ bin/rails db:migrate
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2020-05-23 14:02:45 -04:00
Now that we have a user model to play with, we will edit the
`app/controllers/users_controller.rb` file, make it instruct the `UserMailer` to deliver
2013-04-05 07:42:21 -04:00
an email to the newly created user by editing the create action and inserting a
2017-09-24 12:46:28 -04:00
call to `UserMailer.with(user: @user).welcome_email` right after the user is successfully saved.
2014-08-20 08:34:37 -04:00
Action Mailer is nicely integrated with Active Job so you can send emails outside
of the request-response cycle, so the user doesn't have to wait on it:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2010-04-16 10:57:40 -04:00
class UsersController < ApplicationController
# POST /users
2011-04-26 11:23:57 -04:00
# POST /users.json
2010-04-16 10:57:40 -04:00
def create
@user = User.new(params[:user])
respond_to do |format|
if @user .save
2014-01-20 09:04:36 -05:00
# Tell the UserMailer to send a welcome email after save
2017-09-24 12:46:28 -04:00
UserMailer.with(user: @user ).welcome_email.deliver_later
2010-04-16 10:57:40 -04:00
2012-09-21 14:55:42 -04:00
format.html { redirect_to(@user, notice: 'User was successfully created.') }
format.json { render json: @user , status: :created, location: @user }
2010-04-16 10:57:40 -04:00
else
2012-09-21 14:55:42 -04:00
format.html { render action: 'new' }
format.json { render json: @user .errors, status: :unprocessable_entity }
2010-04-16 10:57:40 -04:00
end
end
2010-01-31 22:57:54 -05:00
end
2009-02-05 20:57:02 -05:00
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2020-05-23 14:02:45 -04:00
NOTE: Active Job's default behavior is to execute jobs via the `:async` adapter.
So, you can use `deliver_later` to send emails asynchronously.
2016-03-21 01:57:54 -04:00
Active Job's default adapter runs jobs with an in-process thread pool.
It's well-suited for the development/test environments, since it doesn't require
any external infrastructure, but it's a poor fit for production since it drops
pending jobs on restart.
If you need a persistent backend, you will need to use an Active Job adapter
that has a persistent backend (Sidekiq, Resque, etc).
2014-08-20 08:34:37 -04:00
2020-05-23 14:02:45 -04:00
NOTE: When calling `deliver_later` the job will be placed under `mailers` queue. Make sure Active Job adapter supports this queue, otherwise the job may be silently ignored preventing email delivery. You can change this queue name by specifying `config.action_mailer.deliver_later_queue_name` option.
2018-06-27 14:50:28 -04:00
2014-08-21 08:18:56 -04:00
If you want to send emails right away (from a cronjob for example) just call
`deliver_now` :
2014-08-20 08:34:37 -04:00
```ruby
class SendWeeklySummary
def run
User.find_each do |user|
2017-09-13 13:17:00 -04:00
UserMailer.with(user: user).weekly_summary.deliver_now
2014-08-20 08:34:37 -04:00
end
end
end
```
2017-09-24 12:46:28 -04:00
Any key value pair passed to `with` just becomes the `params` for the mailer
action. So `with(user: @user, account: @user.account)` makes `params[:user]` and
`params[:account]` available in the mailer action. Just like controllers have
params.
2016-02-13 06:36:16 -05:00
The method `welcome_email` returns an `ActionMailer::MessageDelivery` object which
2020-05-23 14:02:45 -04:00
can then be told to `deliver_now` or `deliver_later` to send itself out. The
`ActionMailer::MessageDelivery` object is a wrapper around a `Mail::Message` . If
2018-05-08 22:48:07 -04:00
you want to inspect, alter, or do anything else with the `Mail::Message` object you can
2014-08-20 08:34:37 -04:00
access it with the `message` method on the `ActionMailer::MessageDelivery` object.
2010-01-31 22:57:54 -05:00
2012-09-01 17:25:58 -04:00
### Auto encoding header values
2010-04-20 00:45:30 -04:00
2013-04-05 07:42:21 -04:00
Action Mailer handles the auto encoding of multibyte characters inside of
headers and bodies.
2010-04-20 00:45:30 -04:00
2013-04-05 07:42:21 -04:00
For more complex examples such as defining alternate character sets or
self-encoding text first, please refer to the
[Mail ](https://github.com/mikel/mail ) library.
2010-04-20 00:45:30 -04:00
2012-09-01 17:25:58 -04:00
### Complete List of Action Mailer Methods
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
There are just three methods that you need to send pretty much any email
message:
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
* `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.read('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.
2010-04-16 10:57:40 -04:00
2012-09-01 17:25:58 -04:00
#### Adding Attachments
2010-01-31 22:57:54 -05:00
2013-04-05 07:42:21 -04:00
Action Mailer makes it very easy to add attachments.
2010-01-31 22:57:54 -05:00
2013-04-05 07:42:21 -04:00
* Pass the file name and content and Action Mailer and the
[Mail gem ](https://github.com/mikel/mail ) will automatically guess the
2018-05-08 22:48:07 -04:00
mime_type, set the encoding, and create the attachment.
2010-01-31 22:57:54 -05:00
2012-09-03 21:21:24 -04:00
```ruby
attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
```
2010-01-31 22:57:54 -05:00
2013-06-29 10:00:54 -04:00
When the `mail` method will be triggered, it 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.
2013-04-05 07:42:21 -04:00
NOTE: Mail will automatically Base64 encode an attachment. If you want something
different, encode your content and pass in the encoded content and encoding in a
`Hash` to the `attachments` method.
2010-01-31 22:57:54 -05:00
2013-04-05 07:42:21 -04:00
* Pass the file name and specify headers and content and Action Mailer and Mail
will use the settings you pass in.
2010-01-31 22:57:54 -05:00
2012-09-03 21:21:24 -04:00
```ruby
encoded_content = SpecialEncode(File.read('/path/to/filename.jpg'))
2014-06-10 15:03:10 -04:00
attachments['filename.jpg'] = {
2016-02-13 10:05:41 -05:00
mime_type: 'application/gzip',
2014-06-10 15:03:10 -04:00
encoding: 'SpecialEncoding',
content: encoded_content
}
2012-09-03 21:21:24 -04:00
```
2010-01-31 22:57:54 -05:00
2013-04-05 07:42:21 -04:00
NOTE: If you specify an encoding, Mail will assume that your content is already
encoded and not try to Base64 encode it.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
#### Making Inline Attachments
2010-06-07 23:25:49 -04:00
2011-08-19 14:47:37 -04:00
Action Mailer 3.0 makes inline attachments, which involved a lot of hacking in pre 3.0 versions, much simpler and trivial as they should be.
2010-06-07 23:25:49 -04:00
2013-04-01 12:53:21 -04:00
* First, to tell Mail to turn an attachment into an inline attachment, you just call `#inline` on the attachments method within your Mailer:
2010-06-07 23:25:49 -04:00
2012-09-03 21:21:24 -04:00
```ruby
def welcome
attachments.inline['image.jpg'] = File.read('/path/to/image.jpg')
end
```
2010-06-07 23:25:49 -04:00
2013-04-05 07:42:21 -04:00
* 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:
2010-06-07 23:25:49 -04:00
2012-09-03 21:21:24 -04:00
```html+erb
< p > Hello there, this is our image< / p >
2010-06-07 23:25:49 -04:00
2012-09-03 21:21:24 -04:00
< %= image_tag attachments['image.jpg'].url %>
```
2010-06-07 23:25:49 -04:00
2013-04-05 07:42:21 -04:00
* 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:
2010-06-07 23:25:49 -04:00
2012-09-03 21:21:24 -04:00
```html+erb
< p > Hello there, this is our image< / p >
2010-06-07 23:25:49 -04:00
2014-09-16 03:32:38 -04:00
< %= image_tag attachments['image.jpg'].url, alt: 'My Photo', class: 'photos' %>
2012-09-03 21:21:24 -04:00
```
2010-06-07 23:25:49 -04:00
2012-09-01 17:25:58 -04:00
#### Sending Email To Multiple Recipients
2010-09-25 05:01:19 -04:00
2013-04-05 07:42:21 -04:00
It is possible to send email to one or more recipients in one email (e.g.,
informing all admins of a new signup) by setting the list of emails to the `:to`
key. The list of emails can be an array of email addresses or a single string
with the addresses separated by commas.
2010-09-25 05:01:19 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2015-08-06 15:35:05 -04:00
class AdminMailer < ApplicationMailer
2017-09-13 13:17:00 -04:00
default to: -> { Admin.pluck(:email) },
2012-09-21 14:55:42 -04:00
from: 'notification@example.com'
2010-12-19 07:27:20 -05:00
2011-08-19 14:47:37 -04:00
def new_registration(user)
@user = user
2012-09-21 14:55:42 -04:00
mail(subject: "New User Signup: #{@user.email}")
2010-09-25 05:01:19 -04:00
end
2011-08-19 14:47:37 -04:00
end
2012-09-01 17:08:06 -04:00
```
2010-09-25 05:01:19 -04:00
2013-04-05 07:42:21 -04:00
The same format can be used to set carbon copy (Cc:) and blind carbon copy
(Bcc:) recipients, by using the `:cc` and `:bcc` keys respectively.
2011-08-14 13:14:28 -04:00
2012-09-01 17:25:58 -04:00
#### Sending Email With Name
2010-09-25 05:19:28 -04:00
2013-04-05 07:42:21 -04:00
Sometimes you wish to show the name of the person instead of just their email
2019-06-10 09:47:46 -04:00
address when they receive the email. You can use `email_address_with_name` for
that:
2010-09-25 05:19:28 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2017-09-13 13:17:00 -04:00
def welcome_email
@user = params[:user]
2019-06-10 09:47:46 -04:00
mail(
to: email_address_with_name(@user.email, @user .name),
subject: 'Welcome to My Awesome Site'
)
2011-08-19 14:47:37 -04:00
end
2012-09-01 17:08:06 -04:00
```
2010-09-25 05:01:19 -04:00
2012-09-01 17:25:58 -04:00
### Mailer Views
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
Mailer views are located in the `app/views/name_of_mailer_class` directory. The
specific mailer view is known to the class because its name is the same as the
mailer method. 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.
2009-02-05 20:57:02 -05:00
To change the default mailer view for your action you do something like:
2012-09-01 17:08:06 -04:00
```ruby
2014-11-24 20:49:29 -05:00
class UserMailer < ApplicationMailer
2012-09-21 14:55:42 -04:00
default from: 'notifications@example.com'
2011-06-23 12:57:48 -04:00
2017-09-13 13:17:00 -04:00
def welcome_email
@user = params[:user]
2012-09-21 14:55:42 -04:00
@url = 'http://example.com/login'
2013-04-05 07:42:21 -04:00
mail(to: @user .email,
2012-09-21 14:55:42 -04:00
subject: 'Welcome to My Awesome Site',
template_path: 'notifications',
template_name: 'another')
2011-06-23 12:57:48 -04:00
end
end
2012-09-01 17:08:06 -04:00
```
2011-06-23 12:57:48 -04:00
2013-04-05 07:42:21 -04:00
In this case it will look for templates at `app/views/notifications` with name
`another` . You can also specify an array of paths for `template_path` , and they
will be searched in order.
2011-06-23 12:57:48 -04:00
2013-04-05 07:42:21 -04:00
If you want more flexibility you can also pass a block and render specific
templates or even render inline or text without using a template file:
2011-06-23 12:57:48 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2014-11-24 20:49:29 -05:00
class UserMailer < ApplicationMailer
2012-09-21 14:55:42 -04:00
default from: 'notifications@example.com'
2010-01-31 22:57:54 -05:00
2017-09-13 13:17:00 -04:00
def welcome_email
@user = params[:user]
2012-09-21 14:55:42 -04:00
@url = 'http://example.com/login'
2013-04-05 07:42:21 -04:00
mail(to: @user .email,
2012-09-21 14:55:42 -04:00
subject: 'Welcome to My Awesome Site') do |format|
2010-01-31 22:57:54 -05:00
format.html { render 'another_template' }
2016-12-03 01:28:59 -05:00
format.text { render plain: 'Render text' }
2010-01-31 22:57:54 -05:00
end
2009-07-25 11:03:58 -04:00
end
2009-02-05 20:57:02 -05:00
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
This will render the template 'another_template.html.erb' for the HTML part and
use the rendered text for the text part. The render command is the same one used
inside of Action Controller, so you can use all the same options, such as
`:text` , `:inline` etc.
2010-01-31 22:57:54 -05:00
2018-08-06 11:58:58 -04:00
If you would like to render a template located outside of the default `app/views/mailer_name/` directory, you can apply the `prepend_view_path` , like so:
```ruby
class UserMailer < ApplicationMailer
prepend_view_path "custom/path/to/mailer/view"
2018-12-27 18:11:39 -05:00
2018-08-06 11:58:58 -04:00
# This will try to load "custom/path/to/mailer/view/welcome_email" template
def welcome_email
# ...
end
end
```
You can also consider using the [append_view_path ](https://guides.rubyonrails.org/action_view_overview.html#view-paths ) method.
2016-02-24 11:36:41 -05:00
#### Caching mailer view
2017-08-26 07:44:09 -04:00
You can perform fragment caching in mailer views like in application views using the `cache` method.
2016-02-24 11:36:41 -05:00
2019-12-17 03:53:54 -05:00
```html+erb
2016-02-24 11:36:41 -05:00
< % cache do %>
< %= @company .name %>
< % end %>
```
And in order to use this feature, you need to configure your application with this:
2019-12-17 03:53:54 -05:00
```ruby
config.action_mailer.perform_caching = true
2016-02-24 11:36:41 -05:00
```
2017-08-26 06:49:13 -04:00
Fragment caching is also supported in multipart emails.
Read more about caching in the [Rails caching guide ](caching_with_rails.html ).
2012-09-01 17:25:58 -04:00
### Action Mailer Layouts
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
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.
2010-01-31 22:57:54 -05:00
2013-04-01 12:53:21 -04:00
In order to use a different file, call `layout` in your mailer:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2014-11-24 20:49:29 -05:00
class UserMailer < ApplicationMailer
2010-01-31 22:57:54 -05:00
layout 'awesome' # use awesome.(html|text).erb as the layout
2009-02-05 20:57:02 -05:00
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
Just like with controller views, use `yield` to render the view inside the
layout.
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
You can also pass in a `layout: 'layout_name'` option to the render call inside
2013-07-24 15:23:48 -04:00
the format block to specify different layouts for different formats:
2010-01-31 22:57:54 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2014-11-24 20:49:29 -05:00
class UserMailer < ApplicationMailer
2017-09-13 13:17:00 -04:00
def welcome_email
mail(to: params[:user].email) do |format|
2012-09-21 14:55:42 -04:00
format.html { render layout: 'my_layout' }
2010-01-31 22:57:54 -05:00
format.text
end
end
end
2012-09-01 17:08:06 -04:00
```
2010-01-31 22:57:54 -05:00
2013-04-05 07:42:21 -04:00
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.
2010-01-31 22:57:54 -05:00
2015-02-08 18:41:25 -05:00
### Previewing Emails
Action Mailer previews provide a way to see how emails look by visiting a
special URL that renders them. In the above example, the preview class for
`UserMailer` should be named `UserMailerPreview` and located in
`test/mailers/previews/user_mailer_preview.rb` . To see the preview of
`welcome_email` , implement a method that has the same name and call
`UserMailer.welcome_email` :
```ruby
class UserMailerPreview < ActionMailer::Preview
def welcome_email
2017-09-24 12:46:28 -04:00
UserMailer.with(user: User.first).welcome_email
2015-02-08 18:41:25 -05:00
end
end
```
Then the preview will be available in < http: / / localhost:3000 / rails / mailers / user_mailer / welcome_email > .
If you change something in `app/views/user_mailer/welcome_email.html.erb`
or the mailer itself, it'll automatically reload and render it so you can
visually see the new style instantly. A list of previews are also available
in < http: / / localhost:3000 / rails / mailers > .
By default, these preview classes live in `test/mailers/previews` .
This can be configured using the `preview_path` option. For example, if you
want to change it to `lib/mailer_previews` , you can configure it in
`config/application.rb` :
```ruby
config.action_mailer.preview_path = "#{Rails.root}/lib/mailer_previews"
```
2012-09-01 17:25:58 -04:00
### Generating URLs in Action Mailer Views
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
Unlike controllers, the mailer instance doesn't have any context about the
incoming request so you'll need to provide the `:host` parameter yourself.
As the `:host` usually is consistent across the application you can configure it
globally in `config/application.rb` :
```ruby
config.action_mailer.default_url_options = { host: 'example.com' }
```
2014-06-19 18:26:29 -04:00
Because of this behavior you cannot use any of the `*_path` helpers inside of
an email. Instead you will need to use the associated `*_url` helper. For example
instead of using
2019-12-17 03:53:54 -05:00
```html+erb
2014-06-19 18:26:29 -04:00
< %= link_to 'welcome', welcome_path %>
```
You will need to use:
2019-12-17 03:53:54 -05:00
```html+erb
2014-06-19 18:26:29 -04:00
< %= link_to 'welcome', welcome_url %>
```
By using the full URL, your links will now work in your emails.
2015-04-28 06:16:35 -04:00
#### Generating URLs with `url_for`
2013-04-05 07:42:21 -04:00
2017-01-25 16:12:57 -05:00
`url_for` generates a full URL by default in templates.
2013-04-05 07:42:21 -04:00
If you did not configure the `:host` option globally make sure to pass it to
`url_for` .
2010-01-31 22:57:54 -05:00
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```erb
2012-09-21 14:55:42 -04:00
< %= url_for(host: 'example.com',
controller: 'welcome',
action: 'greeting') %>
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2015-04-28 06:16:35 -04:00
#### Generating URLs with Named Routes
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
Email clients have no web context and so paths have no base URL to form complete
web addresses. Thus, you should always use the "_url" variant of named route
helpers.
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
If you did not configure the `:host` option globally make sure to pass it to the
2019-04-01 08:29:37 -04:00
URL helper.
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
```erb
< %= user_url(@user, host: 'example.com') %>
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2017-03-29 12:10:20 -04:00
NOTE: non-`GET` links require [rails-ujs ](https://github.com/rails/rails/blob/master/actionview/app/assets/javascripts ) or
2017-03-18 22:41:15 -04:00
[jQuery UJS ](https://github.com/rails/jquery-ujs ), and won't work in mailer templates.
They will result in normal `GET` requests.
2015-04-28 05:26:56 -04:00
2015-07-02 18:28:16 -04:00
### Adding images in Action Mailer Views
Unlike controllers, the mailer instance doesn't have any context about the
incoming request so you'll need to provide the `:asset_host` parameter yourself.
As the `:asset_host` usually is consistent across the application you can
2017-08-22 01:40:56 -04:00
configure it globally in `config/application.rb` :
2015-07-02 18:28:16 -04:00
```ruby
config.action_mailer.asset_host = 'http://example.com'
```
Now you can display an image inside your email.
```ruby
< %= image_tag 'image.jpg' %>
```
2012-09-01 17:25:58 -04:00
### Sending Multipart Emails
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
Action Mailer will automatically send multipart emails if you have different
2017-01-25 16:12:57 -05:00
templates for the same action. So, for our `UserMailer` example, if you have
2013-04-05 07:42:21 -04:00
`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.
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
The order of the parts getting inserted is determined by the `:parts_order`
inside of the `ActionMailer::Base.default` method.
2010-01-31 22:57:54 -05:00
2012-11-30 04:26:54 -05:00
### Sending Emails with Dynamic Delivery Options
2012-09-06 16:32:33 -04:00
2013-04-05 07:42:21 -04:00
If you wish to override the default delivery options (e.g. SMTP credentials)
while delivering emails, you can do this using `delivery_method_options` in the
mailer action.
2012-09-06 16:32:33 -04:00
2012-09-01 19:34:21 -04:00
```ruby
2014-11-24 20:49:29 -05:00
class UserMailer < ApplicationMailer
2017-09-13 13:17:00 -04:00
def welcome_email
@user = params[:user]
2012-09-06 16:32:33 -04:00
@url = user_url(@user)
2017-09-13 13:17:00 -04:00
delivery_options = { user_name: params[:company].smtp_user,
password: params[:company].smtp_password,
address: params[:company].smtp_host }
2013-04-05 07:42:21 -04:00
mail(to: @user .email,
subject: "Please see the Terms and Conditions attached",
delivery_method_options: delivery_options)
2012-09-06 16:32:33 -04:00
end
end
2012-09-01 19:34:21 -04:00
```
2012-09-06 16:32:33 -04:00
2013-03-08 17:29:58 -05:00
### Sending Emails without Template Rendering
2013-04-05 07:42:21 -04:00
There may be cases in which you want to skip the template rendering step and
supply the email body as a string. You can achieve this using the `:body`
2013-05-28 08:34:47 -04:00
option. In such cases don't forget to add the `:content_type` option. Rails
2013-04-05 07:42:21 -04:00
will default to `text/plain` otherwise.
2013-03-08 17:29:58 -05:00
```ruby
2014-11-24 20:49:29 -05:00
class UserMailer < ApplicationMailer
2017-09-13 13:17:00 -04:00
def welcome_email
mail(to: params[:user].email,
body: params[:email_body],
2013-04-05 07:42:21 -04:00
content_type: "text/html",
subject: "Already rendered!")
2013-03-08 17:29:58 -05:00
end
end
```
2012-11-30 04:26:54 -05:00
Action Mailer Callbacks
2018-12-27 18:11:39 -05:00
-----------------------
2012-11-30 04:26:54 -05:00
2013-04-05 07:42:21 -04:00
Action Mailer allows for you to specify a `before_action` , `after_action` and
`around_action` .
2012-11-30 04:26:54 -05:00
2013-04-05 07:42:21 -04:00
* Filters can be specified with a block or a symbol to a method in the mailer
class similar to controllers.
2012-11-30 04:26:54 -05:00
2013-04-05 07:42:21 -04:00
* You could use a `before_action` to populate the mail object with defaults,
delivery_method_options or insert default headers and attachments.
2012-11-30 04:26:54 -05:00
2017-09-13 13:17:00 -04:00
```ruby
class InvitationsMailer < ApplicationMailer
before_action { @inviter , @invitee = params[:inviter], params[:invitee] }
before_action { @account = params[:inviter].account }
default to: -> { @invitee .email_address },
from: -> { common_address(@inviter) },
reply_to: -> { @inviter .email_address_with_name }
def account_invitation
mail subject: "#{@inviter.name} invited you to their Basecamp (#{@account.name})"
end
def project_invitation
@project = params[:project]
@summarizer = ProjectInvitationSummarizer.new(@project.bucket)
mail subject: "#{@inviter.name.familiar} added you to a project in Basecamp (#{@account.name})"
end
end
```
2013-04-05 07:42:21 -04:00
* You could use an `after_action` to do similar setup as a `before_action` but
using instance variables set in your mailer action.
2012-11-30 04:26:54 -05:00
```ruby
2014-11-24 20:49:29 -05:00
class UserMailer < ApplicationMailer
2017-09-13 13:17:00 -04:00
before_action { @business , @user = params[:business], params[:user] }
2013-04-05 07:42:21 -04:00
after_action :set_delivery_options,
:prevent_delivery_to_guests,
:set_business_headers
2012-11-30 04:26:54 -05:00
2017-09-13 13:17:00 -04:00
def feedback_message
2012-11-30 04:26:54 -05:00
end
2017-09-13 13:17:00 -04:00
def campaign_message
2012-11-30 04:26:54 -05:00
end
private
2013-09-06 14:41:04 -04:00
def set_delivery_options
# You have access to the mail instance,
# @business and @user instance variables here
if @business && @business .has_smtp_settings?
mail.delivery_method.settings.merge!(@business.smtp_settings)
end
2012-11-30 04:26:54 -05:00
end
2013-09-06 14:41:04 -04:00
def prevent_delivery_to_guests
if @user && @user .guest?
mail.perform_deliveries = false
end
2012-11-30 04:26:54 -05:00
end
2013-09-06 14:41:04 -04:00
def set_business_headers
if @business
headers["X-SMTPAPI-CATEGORY"] = @business .code
end
2012-11-30 04:26:54 -05:00
end
end
```
* Mailer Filters abort further processing if body is set to a non-nil value.
2012-09-01 17:25:58 -04:00
Using Action Mailer Helpers
---------------------------
2009-02-05 20:57:02 -05:00
2019-09-15 19:09:22 -04:00
Action Mailer inherits from `AbstractController` , so you have access to most
of the same helpers as you do in Action Controller.
There are also some Action Mailer-specific helper methods available in
`ActionMailer::MailHelper` . For example, these allow accessing the mailer
instance from your view with `mailer` , and accessing the message as `message` :
```erb
< %= stylesheet_link_tag mailer.name.underscore %>
< h1 > < %= message.subject %>< / h1 >
```
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
Action Mailer Configuration
---------------------------
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
The following configuration options are best made in one of the environment
files (environment.rb, production.rb, etc...)
2009-02-05 20:57:02 -05:00
2012-09-03 21:21:24 -04:00
| Configuration | Description |
|---------------|-------------|
2012-09-01 19:34:21 -04:00
|`logger`|Generates 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.|
2019-05-07 06:32:20 -04:00
|`smtp_settings`|Allows detailed configuration for `:smtp` delivery method:< ul >< li > `:address` - Allows you to use a remote mail server. Just change it from its default `"localhost"` setting.</ li >< li > `:port` - On the off chance that your mail server doesn't run on port 25, you can change it.</ li >< li > `:domain` - If you need to specify a HELO domain, you can do it here.</ li >< li > `:user_name` - If your mail server requires authentication, set the username in this setting.</ li >< li > `:password` - If your mail server requires authentication, set the password in this setting.</ li >< li > `:authentication` - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of `:plain` (will send the password in the clear), `:login` (will send password Base64 encoded) or `:cram_md5` (combines a Challenge/Response mechanism to exchange information and a cryptographic Message Digest 5 algorithm to hash important information)</ li >< li > `:enable_starttls_auto` - Detects if STARTTLS is enabled in your SMTP server and starts to use it. Defaults to `true` .</ li >< li > `:openssl_verify_mode` - When using TLS, you can set how OpenSSL checks the certificate. This is really useful if you need to validate a self-signed and/or a wildcard certificate. You can use the name of an OpenSSL verify constant ('none' or 'peer') or directly the constant (`OpenSSL::SSL::VERIFY_NONE` or `OpenSSL::SSL::VERIFY_PEER` ).</ li >< li > `:ssl/:tls` - Enables the SMTP connection to use SMTP/TLS (SMTPS: SMTP over direct TLS connection)</ li ></ ul > |
2016-07-06 05:53:40 -04:00
|`sendmail_settings`|Allows you to override options for the `:sendmail` delivery method.< ul >< li > `:location` - The location of the sendmail executable. Defaults to `/usr/sbin/sendmail` .</ li >< li > `:arguments` - The command line arguments to be passed to sendmail. Defaults to `-i` .</ li ></ ul > |
2012-10-06 16:37:16 -04:00
|`raise_delivery_errors`|Whether or not errors should be raised if the email fails to be delivered. This only works if the external email server is configured for immediate delivery.|
2019-03-05 22:00:45 -05:00
|`delivery_method`|Defines a delivery method. Possible values are:< ul >< li > `:smtp` (default), can be configured by using `config.action_mailer.smtp_settings` .</ li >< li > `:sendmail`, can be configured by using `config.action_mailer.sendmail_settings` .</ li >< li > `:file`: save emails to files; can be configured by using `config.action_mailer.file_settings` .</ li >< li > `:test`: save emails to `ActionMailer::Base.deliveries` array.</ li ></ ul > See [API docs ](https://api.rubyonrails.org/classes/ActionMailer/Base.html ) for more info.|
2018-09-11 23:01:03 -04:00
|`perform_deliveries`|Determines whether deliveries are actually carried out when the `deliver` method is invoked on the Mail message. By default they are, but this can be turned off to help functional testing. If this value is `false` , `deliveries` array will not be populated even if `delivery_method` is `:test` .|
2012-09-01 19:34:21 -04:00
|`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_options`|Allows you to set default values for the `mail` method options (`:from`, `:reply_to` , etc.).|
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
For a complete writeup of possible configurations see the
2014-06-10 15:03:10 -04:00
[Configuring Action Mailer ](configuring.html#configuring-action-mailer ) in
2013-04-05 07:42:21 -04:00
our Configuring Rails Applications guide.
2012-09-01 17:25:58 -04:00
### Example Action Mailer Configuration
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
An example would be adding the following to your appropriate
`config/environments/$RAILS_ENV.rb` file:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2010-01-31 22:57:54 -05:00
config.action_mailer.delivery_method = :sendmail
# Defaults to:
# config.action_mailer.sendmail_settings = {
2012-09-21 14:55:42 -04:00
# location: '/usr/sbin/sendmail',
2016-07-06 05:53:40 -04:00
# arguments: '-i'
2010-01-31 22:57:54 -05:00
# }
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
2013-05-29 13:46:07 -04:00
config.action_mailer.default_options = {from: 'no-reply@example.com'}
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2013-04-05 07:42:21 -04:00
### Action Mailer Configuration for Gmail
2009-02-05 20:57:02 -05:00
2014-01-20 08:47:40 -05:00
As Action Mailer now uses the [Mail gem ](https://github.com/mikel/mail ), this
becomes as simple as adding to your `config/environments/$RAILS_ENV.rb` file:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2010-01-31 22:57:54 -05:00
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
2012-09-21 14:55:42 -04:00
address: 'smtp.gmail.com',
port: 587,
2013-04-05 07:42:21 -04:00
domain: 'example.com',
2012-09-21 14:55:42 -04:00
user_name: '< username > ',
password: '< password > ',
authentication: 'plain',
2018-01-09 01:29:49 -05:00
enable_starttls_auto: true }
2012-09-01 17:08:06 -04:00
```
2018-03-12 07:39:24 -04:00
NOTE: As of July 15, 2014, Google increased [its security measures ](https://support.google.com/accounts/answer/6010255 ) and now blocks attempts from apps it deems less secure.
2017-05-24 19:40:00 -04:00
You can change your Gmail settings [here ](https://www.google.com/settings/security/lesssecureapps ) to allow the attempts. If your Gmail account has 2-factor authentication enabled,
2017-05-24 12:38:57 -04:00
then you will need to set an [app password ](https://myaccount.google.com/apppasswords ) and use that instead of your regular password. Alternatively, you can
2015-09-20 06:57:11 -04:00
use another ESP to send email by replacing 'smtp.gmail.com' above with the address of your provider.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
Mailer Testing
--------------
2009-02-05 20:57:02 -05:00
2013-04-01 12:53:21 -04:00
You can find detailed instructions on how to test your mailers in the
2013-03-25 11:58:47 -04:00
[testing guide ](testing.html#testing-your-mailers ).
2013-01-26 11:04:06 -05:00
2018-10-04 16:13:17 -04:00
Intercepting and Observing Emails
2013-01-16 14:17:35 -05:00
-------------------
2014-06-10 15:03:10 -04:00
2018-10-04 16:13:17 -04:00
Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to register classes that are called during the mail delivery life cycle of every email sent.
### Intercepting Emails
Interceptors allow you to make modifications to emails before they are handed off to the delivery agents. An interceptor class must implement the `:delivering_email(message)` method which will be called before the email is sent.
2013-01-16 14:17:35 -05:00
```ruby
class SandboxEmailInterceptor
def self.delivering_email(message)
message.to = ['sandbox@example.com']
end
end
```
2013-04-05 07:42:21 -04:00
Before the interceptor can do its job you need to register it with the Action
Mailer framework. You can do this in an initializer file
`config/initializers/sandbox_email_interceptor.rb`
2013-01-16 14:17:35 -05:00
```ruby
2014-12-29 14:59:02 -05:00
if Rails.env.staging?
ActionMailer::Base.register_interceptor(SandboxEmailInterceptor)
end
2013-01-16 14:17:35 -05:00
```
2013-04-05 07:42:21 -04:00
NOTE: The example above uses a custom environment called "staging" for a
production like server but for testing purposes. You can read
2014-06-10 15:03:10 -04:00
[Creating Rails environments ](configuring.html#creating-rails-environments )
2013-04-05 07:42:21 -04:00
for more information about custom Rails environments.
2018-10-04 16:13:17 -04:00
### Observing Emails
Observers give you access to the email message after it has been sent. An observer class must implement the `:delivered_email(message)` method, which will be called after the email is sent.
```ruby
class EmailDeliveryObserver
def self.delivered_email(message)
EmailDelivery.log(message)
end
end
```
2018-12-27 18:11:39 -05:00
Like interceptors, you need to register observers with the Action Mailer framework. You can do this in an initializer file
2018-10-04 16:13:17 -04:00
`config/initializers/email_delivery_observer.rb`
```ruby
ActionMailer::Base.register_observer(EmailDeliveryObserver)
```