aboutsummaryrefslogtreecommitdiffstats
path: root/railties/guides/source/action_mailer_basics.textile
blob: 2405b8f28c1dafee8f9929324d7bc5464318816b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
h2. Action Mailer Basics

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

endprologue.

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

h3. Introduction

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

h3. Sending Emails

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

h4. Walkthrough to Generating a Mailer

h5. Create the Mailer

<shell>
./script/generate mailer UserMailer
create  app/mailers/user_mailer.rb
invoke  erb
create    app/views/user_mailer
invoke  test_unit
create    test/functional/user_mailer_test.rb
</shell>

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

h5. Edit the Mailer

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

<ruby>
class UserMailer < ActionMailer::Base
  default :from => "from@example.com"
end
</ruby>

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

<ruby>
class UserMailer < ActionMailer::Base
  default :from => "notifications@example.com"

  def welcome_email(user)
    @user = user
    @url  = "http://example.com/login"
    mail(:to => user.email,
         :subject => "Welcome to My Awesome Site")
  end

end
</ruby>

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 ActionMailer user-settable attributes section.

* <tt>default Hash</tt> - This is a hash of default values for any email you send, in this case we are setting the <tt>:from</tt> 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 <tt>:to</tt> and <tt>:subject</tt> headers in|

And instance variables we define in the method become available for use in the view.

h5. Create a Mailer View

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

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

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/+:

<erb>
Welcome to example.com, <%= @user.name %>
===============================================

You have successfully signed up to example.com,
your username is: <%= @user.login %>.

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

Thanks for joining and have a great day!
</erb>

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

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

There are three ways to achieve this. One is to send the email from the controller that sends the email, another is to put it in a +before_create+ callback in the user model, and the last one is to use an observer on the user model. Whether you use the second or third methods is up to you, but staying away from the first is recommended. Not because it's wrong, but because it keeps your controller clean, and keeps all logic related to the user model within the user model. This way, whichever way a user is created (from a web form, or from an API call, for example), we are guaranteed that the email will be sent.

Let's see how we would go about wiring it up using an observer.

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

<shell>
$ script/generate scaffold user name:string email:string login:string
$ rake db:migrate
</shell>

Now that we have a user model to play with, edit +config/application.rb+ and register the observer:

<ruby>
module MailerGuideCode
  class Application < Rails::Application
    # ...
    config.active_record.observers = :user_observer
  end
end
</ruby>

You can make a +app/observers+ directory and Rails will automatically load it for you (Rails will automatically load anything in the +app+ directory as of version 3.0)

Now create a file called +user_observer.rb+ in +app/observers+ and make it look like:

<ruby>
class UserObserver < ActiveRecord::Observer
  def after_create(user)
    UserMailer.welcome_email(user).deliver
  end
end
</ruby>

Notice how we call <tt>UserMailer.welcome_email(user)</tt>? Even though in the <tt>user_mailer.rb</tt> file we defined an instance method, we are calling the method_name +welcome_email(user)+ on the class.  This is a peculiarity of Action Mailer.

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

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


h4. Complete List of Action Mailer Methods

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

* <tt>headers</tt> - Specifies any header on the email you want, you can pass a hash of header field names and value pairs, or you can call <tt>headers[:field_name] = 'value'</tt>
* <tt>attachments</tt> - Allows you to add attachments to your email, for example <tt>attachments['file-name.jpg'] = File.read('file-name.jpg')</tt>
* <tt>mail</tt> - 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.

h5. Custom Headers

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

* Defining a header field as a parameter to the +mail+ method:

<ruby>
mail(:x_spam => value)
</ruby>

* Passing in a key value assignment to the +headers+ method:

<ruby>
headers[:x_spam] = value
</ruby>

* Passing a hash of key value pairs to the +headers+ method:

<ruby>
headers {:x_spam => value, :x_special => another_value}
</ruby>

h5. Adding Attachments

Adding attachments has been simplified in Action Mailer 3.0.

* Pass the file name and content and Action Mailer and the Mail gem will automatically guess the mime_type, set the encoding and create the attachment.

<ruby>
attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
</ruby>

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.

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

<ruby>
encoded_content = SpecialEncode(File.read('/path/to/filename.jpg'))
attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
                               :encoding => 'SpecialEncoding',
                               :content => encoded_content }
</ruby>

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

h4. Mailer Views

Mailer views are located in the +app/views/name_of_mailer_class+ directory. The specific mailer view is known to the class because it's name is the same as the mailer method. So for example, in our example from above, our mailer view for the +welcome_email+ method will be in +app/views/user_mailer/welcome_email.html.erb+ for the HTML version and +welcome_email.text.erb+ for the plain text version.

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

<ruby>
class UserMailer < ActionMailer::Base
  default :from => "notifications@example.com"

  def welcome_email(user)
    @user = user
    @url  = "http://example.com/login"
    mail(:to => user.email,
         :subject => "Welcome to My Awesome Site") do |format|
      format.html { render 'another_template' }
      format.text { render 'another_template' }
    end
  end

end
</ruby>

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

h4. Action Mailer Layouts

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

In order to use a different file just use:

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

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

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

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

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

h4. Generating URLs in Action Mailer Views

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

Unlike controllers, the mailer instance doesn't have any context about the incoming request so you'll need to provide the +:host+, +:controller+, and +:action+:

<erb>
<%= url_for(:host => "example.com",
            :controller => "welcome",
            :action => "greeting") %>
</erb>

When using named routes you only need to supply the +:host+:

<erb>
<%= user_url(@user, :host => "example.com") %>
</erb>

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

It is also possible to set a default host that will be used in all mailers by setting the +:host+ option in the +ActionMailer::Base.default_url_options+ hash as follows:

<ruby>
class UserMailer < ActionMailer::Base
  default_url_options[:host] = "example.com"

  def welcome_email(user)
    @user = user
    @url  = user_url(@user)
    mail(:to => user.email,
         :subject => "Welcome to My Awesome Site")
  end
end
</ruby>

h4. Sending Multipart Emails

Action Mailer will automatically send multipart emails if you have different templates for the same action. So, for our UserMailer example, if you have +welcome_email.text.erb+ and +welcome_email.html.erb+ in +app/views/user_mailer+, Action Mailer will automatically send a multipart email with the HTML and text versions setup as different parts.

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

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

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

h4. Sending Emails with Attachments

Attachments can be added by using the +attachment+ method:

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

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

h3. Receiving Emails

Receiving and parsing emails with Action Mailer can be a rather complex endeavour. Before your email reaches your Rails app, you would have had to configure your system to somehow forward emails to your app, which needs to be listening for that. So, to receive emails in your Rails app you'll need:

* Implement a +receive+ method in your mailer.

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

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:

<ruby>
class UserMailer < ActionMailer::Base
  def receive(email)
    page = Page.find_by_address(email.to.first)
    page.emails.create(
      :subject => email.subject,
      :body => email.body
    )

    if email.has_attachments?
      for attachment in email.attachments
        page.attachments.create({
          :file => attachment,
          :description => email.subject
        })
      end
    end
  end
end
</ruby>

h3. Using Action Mailer Helpers

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

h3. Action Mailer Configuration

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

|template_root|Determines the base from which template references will be made.|
|logger|the logger is used for generating information on the mailing run if available. Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.|
|smtp_settings|Allows detailed configuration for :smtp delivery method: :address - Allows you to use a remote mail server. Just change it from its default "localhost" setting.  :port  - On the off chance that your mail server doesn't run on port 25, you can change it.  :domain - If you need to specify a HELO domain, you can do it here.  :user_name - If your mail server requires authentication, set the username in this setting.  :password - If your mail server requires authentication, set the password in this setting.  :authentication - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of :plain, :login, :cram_md5.|
|sendmail_settings|Allows you to override options for the :sendmail delivery method.  :location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail.  :arguments - The command line arguments. Defaults to -i -t.|
|raise_delivery_errors|Whether or not errors should be raised if the email fails to be delivered.|
|delivery_method|Defines a delivery method. Possible values are :smtp (default), :sendmail, and :test.|
|perform_deliveries|Determines whether deliver_* methods are actually carried out. By default they are, but this can be turned off to help functional testing.|
|deliveries|Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.|

h4. Example Action Mailer Configuration

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

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

h4. Action Mailer Configuration for GMail

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

<ruby>
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  :address              => "smtp.gmail.com",
  :port                 => 587,
  :domain               => 'baci.lindsaar.net',
  :user_name            => '<username>',
  :password             => '<password>',
  :authentication       => 'plain',
  :enable_starttls_auto => true  }
</ruby>

h3. Mailer Testing

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

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

<ruby>
class UserMailerTest < ActionMailer::TestCase
  def test_welcome_email
    user = users(:some_user_in_your_fixtures)

    # Send the email, then test that it got queued
    email = UserMailer.deliver_welcome_email(user)
    assert !ActionMailer::Base.deliveries.empty?

    # Test the body of the sent email contains what we expect it to
    assert_equal [user.email], email.to
    assert_equal "Welcome to My Awesome Site", email.subject
    assert_match /<h1>Welcome to example.com, #{user.name}<\/h1>/, email.encoded
    assert_match /Welcome to example.com, #{user.name}/, email.encoded
  end
end
</ruby>

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

h3. Changelog

"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/25