action_mailer_basics.md 26.4 KB
Newer Older
1
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON http://guides.rubyonrails.org.**
X
Xavier Noria 已提交
2

3 4
Action Mailer Basics
====================
5

F
Fiona Tay 已提交
6
This guide provides you with all you need to get started in sending and
7 8
receiving emails from and to your application, and many internals of Action
Mailer. It also covers how to test your mailers.
9

10 11
After reading this guide, you will know:

12 13 14 15
* How to send and receive email within a Rails application.
* 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.
16

17
--------------------------------------------------------------------------------
18

19 20
Introduction
------------
21

22 23 24 25
Action Mailer allows you to send emails from your application using mailer classes
and views. Mailers work very similarly to controllers. They inherit from
`ActionMailer::Base` and live in `app/mailers`, and they have associated views
that appear in `app/views`.
26

27 28
Sending Emails
--------------
29

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

33
### Walkthrough to Generating a Mailer
34

35
#### Create the Mailer
36

P
Prem Sichanugrist 已提交
37
```bash
38
$ bin/rails generate mailer UserMailer
39
create  app/mailers/user_mailer.rb
40
create  app/mailers/application_mailer.rb
41 42
invoke  erb
create    app/views/user_mailer
43 44
create    app/views/layouts/mailer.text.erb
create    app/views/layouts/mailer.html.erb
45
invoke  test_unit
M
Mike Moore 已提交
46
create    test/mailers/user_mailer_test.rb
47 48 49 50 51 52
create    test/mailers/previews/user_mailer_preview.rb
```

```ruby
# app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
D
Dan Bernier 已提交
53
  default from: "from@example.com"
54 55 56 57 58 59
  layout 'mailer'
end

# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
end
60
```
61

62 63 64 65 66 67 68 69 70 71 72
As you can see, you can generate mailers just like you use other generators with
Rails. Mailers are conceptually similar to controllers, and so we get a mailer,
a directory for views, and a test.

If you didn't want to use a generator, you could create your own file inside of
app/mailers, just make sure that it inherits from `ActionMailer::Base`:

```ruby
class MyMailer < ActionMailer::Base
end
```
73

74
#### Edit the Mailer
75

76 77 78 79 80
Mailers are very similar to Rails controllers. They also have methods called
"actions" and use views to structure the content. Where a controller generates
content like HTML to send back to the client, a Mailer creates a message to be
delivered via email.

81
`app/mailers/user_mailer.rb` contains an empty mailer:
82

83
```ruby
84
class UserMailer < ApplicationMailer
85
end
86
```
87

88 89
Let's add a method called `welcome_email`, that will send an email to the user's
registered email address:
90

91
```ruby
92
class UserMailer < ApplicationMailer
93
  default from: 'notifications@example.com'
94

95
  def welcome_email(user)
96
    @user = user
97
    @url  = 'http://example.com/login'
98
    mail(to: @user.email, subject: 'Welcome to My Awesome Site')
99 100
  end
end
101
```
102

103 104 105
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.
106

107 108 109 110 111
* `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.
112

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

116
#### Create a Mailer View
117

118 119
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:
120

121
```html+erb
122
<!DOCTYPE html>
123 124
<html>
  <head>
125
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
126 127
  </head>
  <body>
128
    <h1>Welcome to example.com, <%= @user.name %></h1>
129
    <p>
130
      You have successfully signed up to example.com,
131
      your username is: <%= @user.login %>.<br>
132 133
    </p>
    <p>
134
      To login to the site, just follow this link: <%= @url %>.
135 136 137 138
    </p>
    <p>Thanks for joining and have a great day!</p>
  </body>
</html>
139
```
140

141 142 143
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/`:
144

145
```erb
146 147 148
Welcome to example.com, <%= @user.name %>
===============================================

149 150
You have successfully signed up to example.com,
your username is: <%= @user.login %>.
151 152 153 154

To login to the site, just follow this link: <%= @url %>.

Thanks for joining and have a great day!
155
```
156

157 158
When you call the `mail` method now, Action Mailer will detect the two templates
(text and HTML) and automatically generate a `multipart/alternative` email.
P
Pratik Naik 已提交
159

160
#### Calling the Mailer
161

162 163
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
164
email protocols instead. Due to this, it makes sense to just have your
165
controller tell the Mailer to send an email when a user is successfully created.
166

167
Setting this up is painfully simple.
168

169
First, let's create a simple `User` scaffold:
170

P
Prem Sichanugrist 已提交
171
```bash
172 173
$ bin/rails generate scaffold user name email login
$ bin/rake db:migrate
174
```
175

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

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

184
```ruby
185 186
class UsersController < ApplicationController
  # POST /users
187
  # POST /users.json
188 189 190 191 192
  def create
    @user = User.new(params[:user])

    respond_to do |format|
      if @user.save
193
        # Tell the UserMailer to send a welcome email after save
194
        UserMailer.welcome_email(@user).deliver_later
195

196 197
        format.html { redirect_to(@user, notice: 'User was successfully created.') }
        format.json { render json: @user, status: :created, location: @user }
198
      else
199 200
        format.html { render action: 'new' }
        format.json { render json: @user.errors, status: :unprocessable_entity }
201 202
      end
    end
203
  end
204
end
205
```
206

207 208 209
NOTE: Active Job's default behavior is to execute jobs ':inline'. So, you can use
`deliver_later` now to send emails, and when you later decide to start sending
them from a background job, you'll only need to set up Active Job to use a queueing
210 211
backend (Sidekiq, Resque, etc).

212 213
If you want to send emails right away (from a cronjob for example) just call
`deliver_now`:
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229

```ruby
class SendWeeklySummary
  def run
    User.find_each do |user|
      UserMailer.weekly_summary(user).deliver_now
    end
  end
end
```

The method `welcome_email` returns a `ActionMailer::MessageDelivery` object which
can then just be told `deliver_now` or `deliver_later` to send itself out. The
`ActionMailer::MessageDelivery` object is just a wrapper around a `Mail::Message`. If
you want to inspect, alter or do anything else with the `Mail::Message` object you can
access it with the `message` method on the `ActionMailer::MessageDelivery` object.
230

231
### Auto encoding header values
232

233 234
Action Mailer handles the auto encoding of multibyte characters inside of
headers and bodies.
235

236 237 238
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.
239

240
### Complete List of Action Mailer Methods
241

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

245 246 247 248 249 250 251 252
* `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.
253

254
#### Adding Attachments
255

256
Action Mailer makes it very easy to add attachments.
257

258 259 260
* Pass the file name and content and Action Mailer and the
  [Mail gem](https://github.com/mikel/mail) will automatically guess the
  mime_type, set the encoding and create the attachment.
261

262 263 264
    ```ruby
    attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
    ```
265

266 267 268 269 270
  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.

271 272 273
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.
274

275 276
* Pass the file name and specify headers and content and Action Mailer and Mail
  will use the settings you pass in.
277

278 279
    ```ruby
    encoded_content = SpecialEncode(File.read('/path/to/filename.jpg'))
280 281 282 283 284
    attachments['filename.jpg'] = {
      mime_type: 'application/x-gzip',
      encoding: 'SpecialEncoding',
      content: encoded_content
    }
285
    ```
286

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

290
#### Making Inline Attachments
291

292
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.
293

294
* First, to tell Mail to turn an attachment into an inline attachment, you just call `#inline` on the attachments method within your Mailer:
295

296 297 298 299 300
    ```ruby
    def welcome
      attachments.inline['image.jpg'] = File.read('/path/to/image.jpg')
    end
    ```
301

302 303 304
* 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:
305

306 307
    ```html+erb
    <p>Hello there, this is our image</p>
308

309 310
    <%= image_tag attachments['image.jpg'].url %>
    ```
311

312 313
* 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:
314

315 316
    ```html+erb
    <p>Hello there, this is our image</p>
317

318
    <%= image_tag attachments['image.jpg'].url, alt: 'My Photo', class: 'photos' %>
319
    ```
320

321
#### Sending Email To Multiple Recipients
322

323 324 325 326
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.
327

328
```ruby
329
class AdminMailer < ActionMailer::Base
330 331
  default to: Proc.new { Admin.pluck(:email) },
          from: 'notification@example.com'
V
Vijay Dev 已提交
332

333 334
  def new_registration(user)
    @user = user
335
    mail(subject: "New User Signup: #{@user.email}")
336
  end
337
end
338
```
339

340 341
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.
342

343
#### Sending Email With Name
344

345 346
Sometimes you wish to show the name of the person instead of just their email
address when they receive the email. The trick to doing that is to format the
347
email address in the format `"Full Name <email>"`.
348

349
```ruby
350 351
def welcome_email(user)
  @user = user
352
  email_with_name = %("#{@user.name}" <#{@user.email}>)
353
  mail(to: email_with_name, subject: 'Welcome to My Awesome Site')
354
end
355
```
356

357
### Mailer Views
358

359 360 361 362 363
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.
364 365 366

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

367
```ruby
368
class UserMailer < ApplicationMailer
369
  default from: 'notifications@example.com'
370 371 372

  def welcome_email(user)
    @user = user
373
    @url  = 'http://example.com/login'
374
    mail(to: @user.email,
375 376 377
         subject: 'Welcome to My Awesome Site',
         template_path: 'notifications',
         template_name: 'another')
378 379
  end
end
380
```
381

382 383 384
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.
385

386 387
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:
388

389
```ruby
390
class UserMailer < ApplicationMailer
391
  default from: 'notifications@example.com'
392

393
  def welcome_email(user)
394
    @user = user
395
    @url  = 'http://example.com/login'
396
    mail(to: @user.email,
397
         subject: 'Welcome to My Awesome Site') do |format|
398
      format.html { render 'another_template' }
399
      format.text { render text: 'Render text' }
400
    end
P
Pratik Naik 已提交
401
  end
402
end
403
```
404

405 406 407 408
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.
409

410
### Action Mailer Layouts
411

412 413 414 415
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.
416

417
In order to use a different file, call `layout` in your mailer:
418

419
```ruby
420
class UserMailer < ApplicationMailer
421
  layout 'awesome' # use awesome.(html|text).erb as the layout
422
end
423
```
424

425 426
Just like with controller views, use `yield` to render the view inside the
layout.
427

428
You can also pass in a `layout: 'layout_name'` option to the render call inside
429
the format block to specify different layouts for different formats:
430

431
```ruby
432
class UserMailer < ApplicationMailer
433
  def welcome_email(user)
434 435
    mail(to: user.email) do |format|
      format.html { render layout: 'my_layout' }
436 437 438 439
      format.text
    end
  end
end
440
```
441

442 443
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.
444

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
### 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
    UserMailer.welcome_email(User.first)
  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"
```

478
### Generating URLs in Action Mailer Views
479

480 481 482 483 484 485 486 487 488 489
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' }
```

490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
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

```
<%= link_to 'welcome', welcome_path %>
```

You will need to use:

```
<%= link_to 'welcome', welcome_url %>
```

By using the full URL, your links will now work in your emails.

506 507
#### generating URLs with `url_for`

508
`url_for` generate full URL by default in templates.
509 510 511

If you did not configure the `:host` option globally make sure to pass it to
`url_for`.
512

513

514
```erb
515 516 517
<%= url_for(host: 'example.com',
            controller: 'welcome',
            action: 'greeting') %>
518
```
519

520
#### generating URLs with named routes
521

522 523 524
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.
525

526 527
If you did not configure the `:host` option globally make sure to pass it to the
url helper.
528

529 530
```erb
<%= user_url(@user, host: 'example.com') %>
531
```
532

533
### Sending Multipart Emails
534

535 536 537 538 539
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.
540

541 542
The order of the parts getting inserted is determined by the `:parts_order`
inside of the `ActionMailer::Base.default` method.
543

544
### Sending Emails with Dynamic Delivery Options
545

546 547 548
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.
549

550
```ruby
551
class UserMailer < ApplicationMailer
V
Vijay Dev 已提交
552
  def welcome_email(user, company)
553 554
    @user = user
    @url  = user_url(@user)
555 556 557 558 559 560
    delivery_options = { user_name: company.smtp_user,
                         password: company.smtp_password,
                         address: company.smtp_host }
    mail(to: @user.email,
         subject: "Please see the Terms and Conditions attached",
         delivery_method_options: delivery_options)
561 562
  end
end
563
```
564

565 566
### Sending Emails without Template Rendering

567 568
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`
569
option. In such cases don't forget to add the `:content_type` option. Rails
570
will default to `text/plain` otherwise.
571 572

```ruby
573
class UserMailer < ApplicationMailer
V
Vijay Dev 已提交
574
  def welcome_email(user, email_body)
575 576 577 578
    mail(to: user.email,
         body: email_body,
         content_type: "text/html",
         subject: "Already rendered!")
579 580 581 582
  end
end
```

583 584
Receiving Emails
----------------
585

586 587 588 589
Receiving and parsing emails with Action Mailer can be a rather complex
endeavor. 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 to:
590

591
* Implement a `receive` method in your mailer.
592

593 594 595
* Configure your email server to forward emails from the address(es) you would
  like your app to receive to `/path/to/app/bin/rails runner
  'UserMailer.receive(STDIN.read)'`.
596

597 598 599 600
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:
601

602
```ruby
603
class UserMailer < ApplicationMailer
604
  def receive(email)
605
    page = Page.find_by(address: email.to.first)
606
    page.emails.create(
607 608
      subject: email.subject,
      body: email.body
609 610 611
    )

    if email.has_attachments?
612
      email.attachments.each do |attachment|
613
        page.attachments.create({
614 615
          file: attachment,
          description: email.subject
616 617 618 619 620
        })
      end
    end
  end
end
621
```
622

623 624 625
Action Mailer Callbacks
---------------------------

626 627
Action Mailer allows for you to specify a `before_action`, `after_action` and
`around_action`.
628

629 630
* Filters can be specified with a block or a symbol to a method in the mailer
  class similar to controllers.
631

632 633
* You could use a `before_action` to populate the mail object with defaults,
  delivery_method_options or insert default headers and attachments.
634

635 636
* You could use an `after_action` to do similar setup as a `before_action` but
  using instance variables set in your mailer action.
637 638

```ruby
639
class UserMailer < ApplicationMailer
640 641 642
  after_action :set_delivery_options,
               :prevent_delivery_to_guests,
               :set_business_headers
643 644 645 646 647 648 649 650 651 652 653 654 655 656

  def feedback_message(business, user)
    @business = business
    @user = user
    mail
  end

  def campaign_message(business, user)
    @business = business
    @user = user
  end

  private

657 658 659 660 661 662
    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
663 664
    end

665 666 667 668
    def prevent_delivery_to_guests
      if @user && @user.guest?
        mail.perform_deliveries = false
      end
669 670
    end

671 672 673 674
    def set_business_headers
      if @business
        headers["X-SMTPAPI-CATEGORY"] = @business.code
      end
675 676 677 678 679 680
    end
end
```

* Mailer Filters abort further processing if body is set to a non-nil value.

681 682
Using Action Mailer Helpers
---------------------------
683

684 685
Action Mailer now just inherits from `AbstractController`, so you have access to
the same generic helpers as you do in Action Controller.
686

687 688
Action Mailer Configuration
---------------------------
689

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

693 694
| Configuration | Description |
|---------------|-------------|
695
|`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.|
696
|`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`, `:login`, `:cram_md5`.</li><li>`:enable_starttls_auto` - Set this to `false` if there is a problem with your server certificate that you cannot resolve.</li></ul>|
697
|`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 -t`.</li></ul>|
698
|`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.|
699
|`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](http://api.rubyonrails.org/classes/ActionMailer/Base.html) for more info.|
700 701 702
|`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.|
|`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.).|
703

704
For a complete writeup of possible configurations see the
705
[Configuring Action Mailer](configuring.html#configuring-action-mailer) in
706 707
our Configuring Rails Applications guide.

708
### Example Action Mailer Configuration
709

710 711
An example would be adding the following to your appropriate
`config/environments/$RAILS_ENV.rb` file:
712

713
```ruby
714 715 716
config.action_mailer.delivery_method = :sendmail
# Defaults to:
# config.action_mailer.sendmail_settings = {
717 718
#   location: '/usr/sbin/sendmail',
#   arguments: '-i -t'
719 720 721
# }
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
722
config.action_mailer.default_options = {from: 'no-reply@example.com'}
723
```
724

725
### Action Mailer Configuration for Gmail
726

727 728
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:
729

730
```ruby
731 732
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
733 734
  address:              'smtp.gmail.com',
  port:                 587,
735
  domain:               'example.com',
736 737 738 739
  user_name:            '<username>',
  password:             '<password>',
  authentication:       'plain',
  enable_starttls_auto: true  }
740
```
741

742 743
Mailer Testing
--------------
744

745
You can find detailed instructions on how to test your mailers in the
746
[testing guide](testing.html#testing-your-mailers).
747

748 749
Intercepting Emails
-------------------
750

751 752 753 754
There are situations where you need to edit an email before it's
delivered. Fortunately Action Mailer provides hooks to intercept every
email. You can register an interceptor to make modifications to mail messages
right before they are handed to the delivery agents.
755 756 757 758 759 760 761 762 763

```ruby
class SandboxEmailInterceptor
  def self.delivering_email(message)
    message.to = ['sandbox@example.com']
  end
end
```

764 765 766
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`
767 768

```ruby
J
Josh Cheek 已提交
769 770 771
if Rails.env.staging?
  ActionMailer::Base.register_interceptor(SandboxEmailInterceptor)
end
772 773
```

774 775
NOTE: The example above uses a custom environment called "staging" for a
production like server but for testing purposes. You can read
776
[Creating Rails environments](configuring.html#creating-rails-environments)
777
for more information about custom Rails environments.