action_mailer_basics.md 23.4 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

8
WARNING. This guide is based on Rails 3.2. Some of the code shown here will not work in earlier versions of Rails.
9

10 11
Introduction
------------
12

13
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`.
14

15 16
Sending Emails
--------------
17

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

20
### Walkthrough to Generating a Mailer
21

22
#### Create the Mailer
23

P
Prem Sichanugrist 已提交
24
```bash
25
$ rails generate mailer UserMailer
26 27 28 29 30
create  app/mailers/user_mailer.rb
invoke  erb
create    app/views/user_mailer
invoke  test_unit
create    test/functional/user_mailer_test.rb
31
```
32

33
So we got the mailer, the views, and the tests.
34

35
#### Edit the Mailer
36

37
`app/mailers/user_mailer.rb` contains an empty mailer:
38

39
```ruby
40
class UserMailer < ActionMailer::Base
41
  default from: 'from@example.com'
42
end
43
```
44

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

47
```ruby
48
class UserMailer < ActionMailer::Base
49
  default from: 'notifications@example.com'
50

51
  def welcome_email(user)
52
    @user = user
53 54
    @url  = 'http://example.com/login'
    mail(to: user.email, subject: 'Welcome to My Awesome Site')
55 56
  end
end
57
```
58

59
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.
60

61 62
* `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.
63

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

66
#### Create a Mailer View
67

68
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:
69

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

90
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/`:
91

92
```erb
93 94 95
Welcome to example.com, <%= @user.name %>
===============================================

96 97
You have successfully signed up to example.com,
your username is: <%= @user.login %>.
98 99 100 101

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

Thanks for joining and have a great day!
102
```
103

104
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 已提交
105

106
#### Wire It Up So That the System Sends the Email When a User Signs Up
107

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

110
Setting this up is painfully simple.
111

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

P
Prem Sichanugrist 已提交
114
```bash
115
$ rails generate scaffold user name:string email:string login:string
116
$ rake db:migrate
117
```
118

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

121
```ruby
122 123
class UsersController < ApplicationController
  # POST /users
124
  # POST /users.json
125 126 127 128 129 130 131 132
  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

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

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

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

148
NOTE: In previous versions of Rails, you would call `deliver_welcome_email` or `create_welcome_email`. This has been deprecated in Rails 3.0 in favour of just calling the method name itself.
149

150
WARNING: Sending out an email should only take a fraction of a second. If you are planning on sending out many emails, or you have a slow domain resolution service, you might want to investigate using a background process like Delayed Job.
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`.
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. If you want to explicitly alter the order, you can either change the `:parts_order` or explicitly render the parts in a different order:
381

382
```ruby
383 384
class UserMailer < ActionMailer::Base
  def welcome_email(user)
385 386
    @user = user
    @url  = user_url(@user)
387 388
    mail(to: user.email,
         subject: 'Welcome to My Awesome Site') do |format|
389 390
      format.html
      format.text
391 392 393
    end
  end
end
394
```
395

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

398
### Sending Emails with Attachments
399

400
Attachments can be added by using the `attachments` method:
401

402
```ruby
403 404
class UserMailer < ActionMailer::Base
  def welcome_email(user)
405 406 407
    @user = user
    @url  = user_url(@user)
    attachments['terms.pdf'] = File.read('/path/terms.pdf')
408 409
    mail(to: user.email,
         subject: 'Please see the Terms and Conditions attached')
410 411
  end
end
412
```
413

414
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 已提交
415

416
#### Sending Emails with Dynamic Delivery Options
417

418
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.
419

420
```ruby
421 422 423 424
class UserMailer < ActionMailer::Base
  def welcome_email(user,company)
    @user = user
    @url  = user_url(@user)
V
Vijay Dev 已提交
425 426
    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)
427 428
  end
end
429
```
430

431 432
Receiving Emails
----------------
433

434
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:
435

436
* Implement a `receive` method in your mailer.
437

438
* Configure your email server to forward emails from the address(es) you would like your app to receive to `/path/to/app/script/rails runner 'UserMailer.receive(STDIN.read)'`.
439

440
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:
441

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

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

463 464
Using Action Mailer Helpers
---------------------------
465

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

468 469
Action Mailer Configuration
---------------------------
470 471 472

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

473 474
| Configuration | Description |
|---------------|-------------|
475 476 477 478 479 480 481 482 483 484
|`template_root`|Determines the base from which template references will be made.|
|`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>|
|`raise_delivery_errors`|Whether or not errors should be raised if the email fails to be delivered.|
|`delivery_method`|Defines a delivery method. Possible values are `:smtp` (default), `:sendmail`, `: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.).|
|`async`|Setting this flag will turn on asynchronous message sending, message rendering and delivery will be pushed to `Rails.queue` for processing.|
485

486
### Example Action Mailer Configuration
487

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

490
```ruby
491 492 493
config.action_mailer.delivery_method = :sendmail
# Defaults to:
# config.action_mailer.sendmail_settings = {
494 495
#   location: '/usr/sbin/sendmail',
#   arguments: '-i -t'
496 497 498
# }
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
499
config.action_mailer.default_options = {from: 'no-replay@example.org'}
500
```
501

502
### Action Mailer Configuration for GMail
503

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

506
```ruby
507 508
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
509 510 511 512 513 514 515
  address:              'smtp.gmail.com',
  port:                 587,
  domain:               'baci.lindsaar.net',
  user_name:            '<username>',
  password:             '<password>',
  authentication:       'plain',
  enable_starttls_auto: true  }
516
```
517

518 519
Mailer Testing
--------------
520

521
By default Action Mailer does not send emails in the test environment. They are just added to the `ActionMailer::Base.deliveries` array.
P
Pratik Naik 已提交
522 523

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

525
```ruby
526
class UserMailerTest < ActionMailer::TestCase
P
Pratik Naik 已提交
527 528
  def test_welcome_email
    user = users(:some_user_in_your_fixtures)
529

P
Pratik Naik 已提交
530
    # Send the email, then test that it got queued
531
    email = UserMailer.welcome_email(user).deliver
P
Pratik Naik 已提交
532
    assert !ActionMailer::Base.deliveries.empty?
533

P
Pratik Naik 已提交
534
    # Test the body of the sent email contains what we expect it to
P
Pratik Naik 已提交
535
    assert_equal [user.email], email.to
536
    assert_equal 'Welcome to My Awesome Site', email.subject
537
    assert_match "<h1>Welcome to example.com, #{user.name}</h1>", email.body.to_s
538
    assert_match 'you have joined to example.com community', email.body.to_s
539
  end
P
Pratik Naik 已提交
540
end
541
```
542

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

545 546
Asynchronous
------------
547

548
Rails provides a Synchronous Queue by default. If you want to use an Asynchronous one you will need to configure an async Queue provider like Resque. Queue providers are supposed to have a Railtie where they configure it's own async queue.
549

550
### Custom Queues
551

552
If you need a different queue than `Rails.queue` for your mailer you can use `ActionMailer::Base.queue=`:
553

554
```ruby
555
class WelcomeMailer < ActionMailer::Base
556
  self.queue = MyQueue.new
557
end
558
```
559

560
or adding to your `config/environments/$RAILS_ENV.rb`:
561

562
```ruby
563
config.action_mailer.queue = MyQueue.new
564
```
565

566
Your custom queue should expect a job that responds to `#run`.