action_mailer_basics.md 23.8 KB
Newer Older
1 2
Action Mailer Basics
====================
3

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

6 7
After reading this guide, you will know:

8 9 10 11
* 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.
12
--------------------------------------------------------------------------------
13

14 15
Introduction
------------
16

17
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`.
18

19 20
Sending Emails
--------------
21

P
Pratik Naik 已提交
22
This section will provide a step-by-step guide to creating a mailer and its views.
23

24
### Walkthrough to Generating a Mailer
25

26
#### Create the Mailer
27

P
Prem Sichanugrist 已提交
28
```bash
29
$ rails generate mailer UserMailer
30 31 32 33
create  app/mailers/user_mailer.rb
invoke  erb
create    app/views/user_mailer
invoke  test_unit
M
Mike Moore 已提交
34
create    test/mailers/user_mailer_test.rb
35
```
36

37
So we got the mailer, the views, and the tests.
38

39
#### Edit the Mailer
40

41
`app/mailers/user_mailer.rb` contains an empty mailer:
42

43
```ruby
44
class UserMailer < ActionMailer::Base
45
  default from: 'from@example.com'
46
end
47
```
48

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

51
```ruby
52
class UserMailer < ActionMailer::Base
53
  default from: 'notifications@example.com'
54

55
  def welcome_email(user)
56
    @user = user
57 58
    @url  = 'http://example.com/login'
    mail(to: user.email, subject: 'Welcome to My Awesome Site')
59 60
  end
end
61
```
62

63
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.
64

65 66
* `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.
67

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

70
#### Create a Mailer View
71

72
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:
73

74
```html+erb
75
<!DOCTYPE html>
76 77
<html>
  <head>
78
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
79 80
  </head>
  <body>
81
    <h1>Welcome to example.com, <%= @user.name %></h1>
82
    <p>
83 84 85 86
      You have successfully signed up to example.com,
      your username is: <%= @user.login %>.<br/>
    </p>
    <p>
87
      To login to the site, just follow this link: <%= @url %>.
88 89 90 91
    </p>
    <p>Thanks for joining and have a great day!</p>
  </body>
</html>
92
```
93

94
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/`:
95

96
```erb
97 98 99
Welcome to example.com, <%= @user.name %>
===============================================

100 101
You have successfully signed up to example.com,
your username is: <%= @user.login %>.
102 103 104 105

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

Thanks for joining and have a great day!
106
```
107

108
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 已提交
109

110
#### Wire It Up So That the System Sends the Email When a User Signs Up
111

112
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, 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.
113

114
Setting this up is painfully simple.
115

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

P
Prem Sichanugrist 已提交
118
```bash
119
$ rails generate scaffold user name email login
120
$ rake db:migrate
121
```
122

123
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:
124

125
```ruby
126 127
class UsersController < ApplicationController
  # POST /users
128
  # POST /users.json
129 130 131 132 133 134 135 136
  def create
    @user = User.new(params[:user])

    respond_to do |format|
      if @user.save
        # Tell the UserMailer to send a welcome Email after save
        UserMailer.welcome_email(@user).deliver

137 138
        format.html { redirect_to(@user, notice: 'User was successfully created.') }
        format.json { render json: @user, status: :created, location: @user }
139
      else
140 141
        format.html { render action: 'new' }
        format.json { render json: @user.errors, status: :unprocessable_entity }
142 143
      end
    end
144
  end
145
end
146
```
147

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

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

152
### Auto encoding header values
153

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

156
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 Action Mailer 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.
157

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

160
### Complete List of Action Mailer Methods
161

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

164 165 166
* `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.
167

168
#### Custom Headers
169

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

172
* Defining a header field as a parameter to the `mail` method:
173

174
    ```ruby
175
    mail('X-Spam' => value)
176
    ```
177

178
* Passing in a key value assignment to the `headers` method:
179

180
    ```ruby
181
    headers['X-Spam'] = value
182
    ```
183

184
* Passing a hash of key value pairs to the `headers` method:
185

186
    ```ruby
187
    headers {'X-Spam' => value, 'X-Special' => another_value}
188
    ```
189

190
TIP: All `X-Value` headers per the RFC2822 can appear more than once. If you want to delete an `X-Value` header, you need to assign it a value of `nil`.
191

192
#### Adding Attachments
193 194 195 196 197

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.

198 199 200
    ```ruby
    attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
    ```
201

202
NOTE: 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.
203 204 205

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

206 207
    ```ruby
    encoded_content = SpecialEncode(File.read('/path/to/filename.jpg'))
208 209 210
    attachments['filename.jpg'] = {mime_type: 'application/x-gzip',
                                   encoding: 'SpecialEncoding',
                                   content: encoded_content }
211
    ```
212

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

215
#### Making Inline Attachments
216

217
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.
218

219
* Firstly, to tell Mail to turn an attachment into an inline attachment, you just call `#inline` on the attachments method within your Mailer:
220

221 222 223 224 225
    ```ruby
    def welcome
      attachments.inline['image.jpg'] = File.read('/path/to/image.jpg')
    end
    ```
226

227
* 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:
228

229 230
    ```html+erb
    <p>Hello there, this is our image</p>
231

232 233
    <%= image_tag attachments['image.jpg'].url %>
    ```
234

235
* 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:
236

237 238
    ```html+erb
    <p>Hello there, this is our image</p>
239

240 241
    <%= image_tag attachments['image.jpg'].url, alt: 'My Photo',
                                                class: 'photos' %>
242
    ```
243

244
#### Sending Email To Multiple Recipients
245

246
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.
247

248
```ruby
249
class AdminMailer < ActionMailer::Base
250 251
  default to: Proc.new { Admin.pluck(:email) },
          from: 'notification@example.com'
V
Vijay Dev 已提交
252

253 254
  def new_registration(user)
    @user = user
255
    mail(subject: "New User Signup: #{@user.email}")
256
  end
257
end
258
```
259

260
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.
261

262
#### Sending Email With Name
263 264

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
265
to format the email address in the format `"Name <email>"`.
266

267
```ruby
268 269 270
def welcome_email(user)
  @user = user
  email_with_name = "#{@user.name} <#{@user.email}>"
271
  mail(to: email_with_name, subject: 'Welcome to My Awesome Site')
272
end
273
```
274

275
### Mailer Views
276

277
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.
278 279 280

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

281
```ruby
282
class UserMailer < ActionMailer::Base
283
  default from: 'notifications@example.com'
284 285 286

  def welcome_email(user)
    @user = user
287 288 289 290 291
    @url  = 'http://example.com/login'
    mail(to: user.email,
         subject: 'Welcome to My Awesome Site',
         template_path: 'notifications',
         template_name: 'another')
292 293
  end
end
294
```
295

296
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.
297 298 299

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:

300
```ruby
301
class UserMailer < ActionMailer::Base
302
  default from: 'notifications@example.com'
303

304
  def welcome_email(user)
305
    @user = user
306 307 308
    @url  = 'http://example.com/login'
    mail(to: user.email,
         subject: 'Welcome to My Awesome Site') do |format|
309
      format.html { render 'another_template' }
310
      format.text { render text: 'Render text' }
311
    end
P
Pratik Naik 已提交
312
  end
313

314
end
315
```
316

317
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.
318

319
### Action Mailer Layouts
320

321
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.
322 323

In order to use a different file just use:
324

325
```ruby
326
class UserMailer < ActionMailer::Base
327
  layout 'awesome' # use awesome.(html|text).erb as the layout
328
end
329
```
330

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

333
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:
334

335
```ruby
336 337
class UserMailer < ActionMailer::Base
  def welcome_email(user)
338 339
    mail(to: user.email) do |format|
      format.html { render layout: 'my_layout' }
340 341 342 343
      format.text
    end
  end
end
344
```
345

346
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.
347

348
### Generating URLs in Action Mailer Views
349

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

352
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`:
353

354
```erb
355 356 357
<%= url_for(host: 'example.com',
            controller: 'welcome',
            action: 'greeting') %>
358
```
359

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

362
```erb
363
<%= user_url(@user, host: 'example.com') %>
364
```
365

P
Pratik Naik 已提交
366
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.
367

368
It is also possible to set a default host that will be used in all mailers by setting the `:host` option as a configuration option in `config/application.rb`:
369

370
```ruby
371
config.action_mailer.default_url_options = { host: 'example.com' }
372
```
373

374
If you use this setting, you should pass 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.
375

376
### Sending Multipart Emails
377

378
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.
379

380
The order of the parts getting inserted is determined by the `:parts_order` inside of the `ActionMailer::Base.default` method.
381

382
### Sending Emails with Attachments
383

384
Attachments can be added by using the `attachments` method:
385

386
```ruby
387 388
class UserMailer < ActionMailer::Base
  def welcome_email(user)
389 390 391
    @user = user
    @url  = user_url(@user)
    attachments['terms.pdf'] = File.read('/path/terms.pdf')
392 393
    mail(to: user.email,
         subject: 'Please see the Terms and Conditions attached')
394 395
  end
end
396
```
397

398
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.
P
Pratik Naik 已提交
399

400
### Sending Emails with Dynamic Delivery Options
401

402
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.
403

404
```ruby
405
class UserMailer < ActionMailer::Base
V
Vijay Dev 已提交
406
  def welcome_email(user, company)
407 408
    @user = user
    @url  = user_url(@user)
V
Vijay Dev 已提交
409 410
    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)
411 412
  end
end
413
```
414

415 416
### Sending Emails without Template Rendering

V
Vijay Dev 已提交
417
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` option.
418 419 420 421
In such cases don't forget to add the `:content_type` option. Rails will default to `text/plain` otherwise.

```ruby
class UserMailer < ActionMailer::Base
V
Vijay Dev 已提交
422
  def welcome_email(user, email_body)
423 424 425 426 427
    mail(to: user.email, body: email_body, content_type: "text/html", subject: "Already rendered!")
  end
end
```

428 429
Receiving Emails
----------------
430

431
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:
432

433
* Implement a `receive` method in your mailer.
434

435
* 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)'`.
436

437
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:
438

439
```ruby
440 441 442 443
class UserMailer < ActionMailer::Base
  def receive(email)
    page = Page.find_by_address(email.to.first)
    page.emails.create(
444 445
      subject: email.subject,
      body: email.body
446 447 448
    )

    if email.has_attachments?
449
      email.attachments.each do |attachment|
450
        page.attachments.create({
451 452
          file: attachment,
          description: email.subject
453 454 455 456 457
        })
      end
    end
  end
end
458
```
459

460 461 462
Action Mailer Callbacks
---------------------------

463
Action Mailer allows for you to specify a `before_action`, `after_action` and `around_action`.
464 465 466

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

467
* You could use a `before_action` to prepopulate the mail object with defaults, delivery_method_options or insert default headers and attachments.
468

469
* You could use an `after_action` to do similar setup as a `before_action` but using instance variables set in your mailer action.
470 471 472

```ruby
class UserMailer < ActionMailer::Base
473
  after_action :set_delivery_options, :prevent_delivery_to_guests, :set_business_headers
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510

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

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

  private

  def set_delivery_options
    # You have access to the mail instance and @business and @user instance variables here
    if @business && @business.has_smtp_settings?
      mail.delivery_method.settings.merge!(@business.smtp_settings)
    end
  end

  def prevent_delivery_to_guests
    if @user && @user.guest?
      mail.perform_deliveries = false
    end
  end

  def set_business_headers
    if @business
      headers["X-SMTPAPI-CATEGORY"] = @business.code
    end
  end
end
```

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

511 512
Using Action Mailer Helpers
---------------------------
513

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

516 517
Action Mailer Configuration
---------------------------
518 519 520

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

521 522
| Configuration | Description |
|---------------|-------------|
523 524 525
|`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.|
|`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>|
|`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>|
526
|`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.|
527 528 529 530
|`delivery_method`|Defines a delivery method. Possible values are `:smtp` (default), `:sendmail`, `:file` and `:test`.|
|`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.).|
531

532
### Example Action Mailer Configuration
533

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

536
```ruby
537 538 539
config.action_mailer.delivery_method = :sendmail
# Defaults to:
# config.action_mailer.sendmail_settings = {
540 541
#   location: '/usr/sbin/sendmail',
#   arguments: '-i -t'
542 543 544
# }
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
545
config.action_mailer.default_options = {from: 'no-replay@example.org'}
546
```
547

548
### Action Mailer Configuration for GMail
549

550
As Action Mailer now uses the Mail gem, this becomes as simple as adding to your `config/environments/$RAILS_ENV.rb` file:
551

552
```ruby
553 554
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
555 556 557 558 559 560 561
  address:              'smtp.gmail.com',
  port:                 587,
  domain:               'baci.lindsaar.net',
  user_name:            '<username>',
  password:             '<password>',
  authentication:       'plain',
  enable_starttls_auto: true  }
562
```
563

564 565
Mailer Testing
--------------
566

567 568
You can find detailed instructions on how to test your mailers in our
[testing guide](testing.html#testing-your-mailers).
569

570 571 572 573 574 575 576 577 578 579 580 581
Intercepting Emails
-------------------
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.

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

A
Akira Matsuda 已提交
582
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`
583 584 585 586 587

```ruby
ActionMailer::Base.register_interceptor(SandboxEmailInterceptor) if Rails.env.staging?
```

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