This repository has been archived by the owner on Jan 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathaction_mailer_basics.html
728 lines (670 loc) · 37 KB
/
action_mailer_basics.html
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
438
439
440
441
442
443
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
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Ruby on Rails Guides: Action Mailer Basics</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
</head>
<body class="guide">
<div id="topNav">
<div class="wrapper">
<strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
<a href="http://rubyonrails.org/">Overview</a> |
<a href="http://rubyonrails.org/download">Download</a> |
<a href="http://rubyonrails.org/deploy">Deploy</a> |
<a href="http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/overview">Code</a> |
<a href="http://rubyonrails.org/screencasts">Screencasts</a> |
<a href="http://rubyonrails.org/documentation">Documentation</a> |
<a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
<a href="http://rubyonrails.org/community">Community</a> |
<a href="http://weblog.rubyonrails.org/">Blog</a>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
<ul class="nav">
<li><a href="index.html">홈</a></li>
<li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">목차</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<dl class="L">
<dt>시작</dt>
<dd><a href="getting_started.html">레일즈 시작하기</a></dd>
<dt>모델(Models)</dt>
<dd><a href="migrations.html">레일즈 데이터베이스 마이그레이션</a></dd>
<dd><a href="active_record_validations_callbacks.html">액티브 레코드 데이터 검증(Validation)과 Callback(콜백)</a></dd>
<dd><a href="association_basics.html">액티브 레코드 Association(관계)</a></dd>
<dd><a href="active_record_querying.html">액티브 레코드 쿼리 인터페이스</a></dd>
<dt>뷰(Views)</dt>
<dd><a href="layouts_and_rendering.html">레이아웃(Layouts)과 렌더링(Rendering)</a></dd>
<dd><a href="form_helpers.html">액션 뷰 폼 핼퍼(Action View Form Helpers)</a></dd>
<dt>컨트롤러(Controllers)</dt>
<dd><a href="action_controller_overview.html">액션 컨트롤러 둘러보기</a></dd>
<dd><a href="routing.html">외부 요청에 대한 레일즈 라우팅</a></dd>
</dl>
<dl class="R">
<dt>심화내용</dt>
<dd><a href="active_support_core_extensions.html">액티브 서포트(Active Support) 확장(Core Extensions)</a></dd>
<dd><a href="i18n.html">레일즈 국제화I(nternationalization) API</a></dd>
<dd><a href="action_mailer_basics.html">액션 메일러의 기본</a></dd>
<dd><a href="testing.html">레일즈 어플리케이션 테스트하기</a></dd>
<dd><a href="security.html">레일즈 어플리케이션의 보안</a></dd>
<dd><a href="debugging_rails_applications.html">레일즈 어플리케이션 디버깅</a></dd>
<dd><a href="performance_testing.html">레일즈 어플리케이션 성능 테스트하기</a></dd>
<dd><a href="configuring.html">레일즈 어플리케이션 설정</a></dd>
<dd><a href="command_line.html">레일즈 커멘드라인 도구와 Rake 테스크</a></dd>
<dd><a href="caching_with_rails.html">레일즈를 이용한 캐싱</a></dd>
<dt>레일즈 확장하기(Extending Rails)</dt>
<dd><a href="plugins.html">레일즈 플러그인 작성의 기본</a></dd>
<dd><a href="rails_on_rack.html">렉 위의 레일즈(Rails on Rack)</a></dd>
<dd><a href="generators.html">레일즈 제너레이터(Generator) 제작과 수정</a></dd>
<dt>루비 온 레이즈에 기여하기</dt>
<dd><a href="contributing_to_ruby_on_rails.html">루비 온 레이즈에 기여하기</a></dd>
<dd><a href="api_documentation_guidelines.html">API 문서 가이드라인</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">루비 온 레일즈 가이드에 대한 가이드라인</a></dd>
<dt>Release Notes</dt>
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
</dl>
</div>
</li>
<li><a href="contribute.html">기여하기</a></li>
<li><a href="credits.html">수고하신 분들</a></li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<h2>Action Mailer Basics</h2>
<p>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.</p>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#introduction">Introduction</a></li><li><a href="#sending-emails">Sending Emails</a><ul><li><a href="#walkthrough-to-generating-a-mailer">Walkthrough to Generating a Mailer</a></li> <li><a href="#auto-encoding-header-values">Auto encoding header values</a></li> <li><a href="#complete-list-of-action-mailer-methods">Complete List of Action Mailer Methods</a></li> <li><a href="#mailer-views">Mailer Views</a></li> <li><a href="#action-mailer-layouts">Action Mailer Layouts</a></li> <li><a href="#generating-urls-in-action-mailer-views">Generating URLs in Action Mailer Views</a></li> <li><a href="#sending-multipart-emails">Sending Multipart Emails</a></li> <li><a href="#sending-emails-with-attachments">Sending Emails with Attachments</a></li></ul></li><li><a href="#receiving-emails">Receiving Emails</a></li><li><a href="#using-action-mailer-helpers">Using Action Mailer Helpers</a></li><li><a href="#action-mailer-configuration">Action Mailer Configuration</a><ul><li><a href="#example-action-mailer-configuration">Example Action Mailer Configuration</a></li> <li><a href="#action-mailer-configuration-for-gmail">Action Mailer Configuration for GMail</a></li></ul></li><li><a href="#mailer-testing">Mailer Testing</a></li><li><a href="#changelog">Changelog</a></li></ol></div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<div class='warning'><p>This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.</p></div>
<h3 id="introduction">1 Introduction</h3>
<p>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 <tt>ActionMailer::Base</tt> and live in <tt>app/mailers</tt>. Those mailers have associated views that appear alongside controller views in <tt>app/views</tt>.</p>
<h3 id="sending-emails">2 Sending Emails</h3>
<p>This section will provide a step-by-step guide to creating a mailer and its views.</p>
<h4 id="walkthrough-to-generating-a-mailer">2.1 Walkthrough to Generating a Mailer</h4>
<h5 id="create-the-mailer">2.1.1 Create the Mailer</h5>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
rails 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
</pre>
</div>
</notextile>
<p>So we got the mailer, the views, and the tests.</p>
<h5 id="edit-the-mailer">2.1.2 Edit the Mailer</h5>
<p><tt>app/mailers/user_mailer.rb</tt> contains an empty mailer:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class UserMailer < ActionMailer::Base
default :from => "[email protected]"
end
</pre>
</div>
</notextile>
<p>Let’s add a method called <tt>welcome_email</tt>, that will send an email to the user’s registered email address:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class UserMailer < ActionMailer::Base
default :from => "[email protected]"
def welcome_email(user)
@user = user
@url = "http://example.com/login"
mail(:to => user.email,
:subject => "Welcome to My Awesome Site")
end
end
</pre>
</div>
</notextile>
<p>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.</p>
<ul>
<li><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</li>
<li><tt>mail</tt> – The actual email message, we are passing the <tt>:to</tt> and <tt>:subject</tt> headers in.</li>
</ul>
<p>Just like controllers, any instance variables we define in the method become available for use in the views.</p>
<h5 id="create-a-mailer-view">2.1.3 Create a Mailer View</h5>
<p>Create a file called <tt>welcome_email.html.erb</tt> in <tt>app/views/user_mailer/</tt>. This will be the template used for the email, formatted in <span class="caps">HTML</span>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<!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>
</pre>
</div>
</notextile>
<p>It is also a good idea to make a text part for this email, to do this, create a file called <tt>welcome_email.text.erb</tt> in <tt>app/views/user_mailer/</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
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!
</pre>
</div>
</notextile>
<p>When you call the <tt>mail</tt> method now, Action Mailer will detect the two templates (text and <span class="caps">HTML</span>) and automatically generate a <tt>multipart/alternative</tt> email.</p>
<h5 id="wire-it-up-so-that-the-system-sends-the-email-when-a-user-signs-up">2.1.4 Wire It Up So That the System Sends the Email When a User Signs Up</h5>
<p>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 <span class="caps">HTTP</span> 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.</p>
<p>Setting this up is painfully simple.</p>
<p>First off, we need to create a simple <tt>User</tt> scaffold:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate scaffold user name:string email:string login:string
$ rake db:migrate
</pre>
</div>
</notextile>
<p>Now that we have a user model to play with, we will just edit the <tt>app/controllers/users_controller.rb</tt> make it instruct the UserMailer to deliver an email to the newly created user by editing the create action and inserting a call to <tt>UserMailer.welcome_email</tt> right after the user is successfully saved:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class UsersController < ApplicationController
# POST /users
# POST /users.xml
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
format.html { redirect_to(@user, :notice => 'User was successfully created.') }
format.xml { render :xml => @user, :status => :created, :location => @user }
else
format.html { render :action => "new" }
format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
end
end
</pre>
</div>
</notextile>
<p>This provides a much simpler implementation that does not require the registering of observers and the like.</p>
<p>The method <tt>welcome_email</tt> returns a Mail::Message object which can then just be told <tt>deliver</tt> to send itself out.</p>
<div class='note'><p>In previous versions of Rails, you would call <tt>deliver_welcome_email</tt> or <tt>create_welcome_email</tt>. This has been deprecated in Rails 3.0 in favour of just calling the method name itself.</p></div>
<div class='warning'><p>Sending out one 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.</p></div>
<h4 id="auto-encoding-header-values">2.2 Auto encoding header values</h4>
<p>Action Mailer now handles the auto encoding of multibyte characters inside of headers and bodies.</p>
<p>If you are using <span class="caps">UTF</span>-8 as your character set, you do not have to do anything special, just go ahead and send in <span class="caps">UTF</span>-8 data to the address fields, subject, keywords, filenames or body of the email and ActionMailer 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-<span class="caps">ASCII</span>.</p>
<p>For more complex examples such as defining alternate character sets or self encoding text first, please refer to the Mail library.</p>
<h4 id="complete-list-of-action-mailer-methods">2.3 Complete List of Action Mailer Methods</h4>
<p>There are just three methods that you need to send pretty much any email message:</p>
<ul>
<li><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></li>
<li><tt>attachments</tt> – Allows you to add attachments to your email, for example <tt>attachments[‘file-name.jpg’] = File.read(‘file-name.jpg’)</tt></li>
<li><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.</li>
</ul>
<h5 id="custom-headers">2.3.1 Custom Headers</h5>
<p>Defining custom headers are simple, you can do it one of three ways:</p>
<ul>
<li>Defining a header field as a parameter to the <tt>mail</tt> method:</li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
mail("X-Spam" => value)
</pre>
</div>
</notextile>
<ul>
<li>Passing in a key value assignment to the <tt>headers</tt> method:</li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
headers["X-Spam"] = value
</pre>
</div>
</notextile>
<ul>
<li>Passing a hash of key value pairs to the <tt>headers</tt> method:</li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
headers {"X-Spam" => value, "X-Special" => another_value}
</pre>
</div>
</notextile>
<div class='info'><p>All <tt>X-Value</tt> headers per the RFC2822 can appear more than one time. If you want to delete an <tt>X-Value</tt> header, you need to assign it a value of <tt>nil</tt>.</p></div>
<h5 id="adding-attachments">2.3.2 Adding Attachments</h5>
<p>Adding attachments has been simplified in Action Mailer 3.0.</p>
<ul>
<li>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.</li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
</pre>
</div>
</notextile>
<div class='note'><p>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 <tt>Hash</tt> to the <tt>attachments</tt> method.</p></div>
<ul>
<li>Pass the file name and specify headers and content and Action Mailer and Mail will use the settings you pass in.</li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
encoded_content = SpecialEncode(File.read('/path/to/filename.jpg'))
attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
:encoding => 'SpecialEncoding',
:content => encoded_content }
</pre>
</div>
</notextile>
<div class='note'><p>If you specify an encoding, Mail will assume that your content is already encoded and not try to Base64 encode it.</p></div>
<h5 id="making-inline-attachments">2.3.3 Making Inline Attachments</h5>
<p>ActionMailer 3.0 makes inline attachments, which involved a lot of hacking in pre 3.0 versions, much simpler and trivial as they should be.</p>
<ul>
<li>Firstly, to tell Mail to turn an attachment into an inline attachment, you just call <tt>#inline</tt> on the attachments method within your Mailer:</li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def welcome
attachments.inline['image.jpg'] = File.read('/path/to/image.jpg')
end
</pre>
</div>
</notextile>
<ul>
<li>Then in your view, you can just reference <tt>attachments[]</tt> as a hash and specify which attachment you want to show, calling <tt>url</tt> on it and then passing the result into the <tt>image_tag</tt> method:</li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<p>Hello there, this is our image</p>
<%= image_tag attachments['image.jpg'].url %>
</pre>
</div>
</notextile>
<ul>
<li>As this is a standard call to <tt>image_tag</tt> you can pass in an options hash after the attachment url as you could for any other image:</li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<p>Hello there, this is our image</p>
<%= image_tag attachments['image.jpg'].url, :alt => 'My Photo',
:class => 'photos' %>
</pre>
</div>
</notextile>
<h5 id="sending-email-to-multiple-recipients">2.3.4 Sending Email To Multiple Recipients</h5>
<p>It is possible to send email to one or more recipients in one email (for e.g. informing all admins of a new signup) by setting the list of emails to the <tt>:to</tt> key. The <tt>to:</tt> key however expects a string so you have join the list of recipients using a comma.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class AdminMailer < ActionMailer::Base
default :to => Admin.all.map(&:email).join(", "),
:from => "[email protected]"
def new_registration(user)
@user = user
mail(:subject => "New User Signup: #{@user.email}")
end
end
</pre>
</div>
</notextile>
<h5 id="sending-email-with-name">2.3.5 Sending Email With Name</h5>
<p>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 email address in the format <tt>“Name <email>”</tt>.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def welcome_email(user)
@user = user
email_with_name = "#{@user.name} <#{@user.email}>"
mail(:to => email_with_name,
:subject => "Welcome to My Awesome Site")
end
</pre>
</div>
</notextile>
<h4 id="mailer-views">2.4 Mailer Views</h4>
<p>Mailer views are located in the <tt>app/views/name_of_mailer_class</tt> 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 <tt>welcome_email</tt> method will be in <tt>app/views/user_mailer/welcome_email.html.erb</tt> for the <span class="caps">HTML</span> version and <tt>welcome_email.text.erb</tt> for the plain text version.</p>
<p>To change the default mailer view for your action you do something like:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class UserMailer < ActionMailer::Base
default :from => "[email protected]"
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
</pre>
</div>
</notextile>
<p>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.</p>
<h4 id="action-mailer-layouts">2.5 Action Mailer Layouts</h4>
<p>Just like controller views, you can also have mailer layouts. The layout name needs to be the same as your mailer, such as <tt>user_mailer.html.erb</tt> and <tt>user_mailer.text.erb</tt> to be automatically recognized by your mailer as a layout.</p>
<p>In order to use a different file just use:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class UserMailer < ActionMailer::Base
layout 'awesome' # use awesome.(html|text).erb as the layout
end
</pre>
</div>
</notextile>
<p>Just like with controller views, use <tt>yield</tt> to render the view inside the layout.</p>
<p>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:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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
</pre>
</div>
</notextile>
<p>Will render the <span class="caps">HTML</span> 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.</p>
<h4 id="generating-urls-in-action-mailer-views">2.6 Generating URLs in Action Mailer Views</h4>
<p>URLs can be generated in mailer views using <tt>url_for</tt> or named routes.</p>
<p>Unlike controllers, the mailer instance doesn’t have any context about the incoming request so you’ll need to provide the <tt>:host</tt>, <tt>:controller</tt>, and <tt>:action</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= url_for(:host => "example.com",
:controller => "welcome",
:action => "greeting") %>
</pre>
</div>
</notextile>
<p>When using named routes you only need to supply the <tt>:host</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= user_url(@user, :host => "example.com") %>
</pre>
</div>
</notextile>
<p>Email clients have no web context and so paths have no base <span class="caps">URL</span> to form complete web addresses. Thus, when using named routes only the “_url” variant makes sense.</p>
<p>It is also possible to set a default host that will be used in all mailers by setting the <tt>:host</tt> option in the <tt>ActionMailer::Base.default_url_options</tt> hash as follows:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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
</pre>
</div>
</notextile>
<h4 id="sending-multipart-emails">2.7 Sending Multipart Emails</h4>
<p>Action Mailer will automatically send multipart emails if you have different templates for the same action. So, for our UserMailer example, if you have <tt>welcome_email.text.erb</tt> and <tt>welcome_email.html.erb</tt> in <tt>app/views/user_mailer</tt>, Action Mailer will automatically send a multipart email with the <span class="caps">HTML</span> and text versions setup as different parts.</p>
<p>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:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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
</pre>
</div>
</notextile>
<p>Will put the <span class="caps">HTML</span> part first, and the plain text part second.</p>
<h4 id="sending-emails-with-attachments">2.8 Sending Emails with Attachments</h4>
<p>Attachments can be added by using the <tt>attachment</tt> method:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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
</pre>
</div>
</notextile>
<p>The above will send a multipart email with an attachment, properly nested with the top level being <tt>multipart/mixed</tt> and the first part being a <tt>multipart/alternative</tt> containing the plain text and <span class="caps">HTML</span> email messages.</p>
<h3 id="receiving-emails">3 Receiving Emails</h3>
<p>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 to:</p>
<ul>
<li>Implement a <tt>receive</tt> method in your mailer.</li>
</ul>
<ul>
<li>Configure your email server to forward emails from the address(es) you would like your app to receive to <tt>/path/to/app/script/rails runner 'UserMailer.receive(STDIN.read)'</tt>.</li>
</ul>
<p>Once a method called <tt>receive</tt> 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 <tt>receive</tt> instance method. Here’s an example:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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
</pre>
</div>
</notextile>
<h3 id="using-action-mailer-helpers">4 Using Action Mailer Helpers</h3>
<p>Action Mailer now just inherits from Abstract Controller, so you have access to the same generic helpers as you do in Action Controller.</p>
<h3 id="action-mailer-configuration">5 Action Mailer Configuration</h3>
<p>The following configuration options are best made in one of the environment files (environment.rb, production.rb, etc…)</p>
<table>
<tr>
<td>template_root</td>
<td>Determines the base from which template references will be made.</td>
</tr>
<tr>
<td>logger</td>
<td>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.</td>
</tr>
<tr>
<td>smtp_settings</td>
<td>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 <span class="caps">HELO</span> 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></ul></td>
</tr>
<tr>
<td>sendmail_settings</td>
<td>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></td>
</tr>
<tr>
<td>raise_delivery_errors</td>
<td>Whether or not errors should be raised if the email fails to be delivered.</td>
</tr>
<tr>
<td>delivery_method</td>
<td>Defines a delivery method. Possible values are :smtp (default), :sendmail, :file and :test.</td>
</tr>
<tr>
<td>perform_deliveries</td>
<td>Determines whether deliveries are actually carried out when the <tt>deliver</tt> method is invoked on the Mail message. By default they are, but this can be turned off to help functional testing.</td>
</tr>
<tr>
<td>deliveries</td>
<td>Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.</td>
</tr>
</table>
<h4 id="example-action-mailer-configuration">5.1 Example Action Mailer Configuration</h4>
<p>An example would be adding the following to your appropriate <tt>config/environments/env.rb</tt> file:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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
</pre>
</div>
</notextile>
<h4 id="action-mailer-configuration-for-gmail">5.2 Action Mailer Configuration for GMail</h4>
<p>As Action Mailer now uses the Mail gem, this becomes as simple as adding to your <tt>config/environments/env.rb</tt> file:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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 }
</pre>
</div>
</notextile>
<h3 id="mailer-testing">6 Mailer Testing</h3>
<p>By default Action Mailer does not send emails in the test environment. They are just added to the <tt>ActionMailer::Base.deliveries</tt> array.</p>
<p>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:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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.welcome_email(user).deliver
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
</pre>
</div>
</notextile>
<p>In the test we send the email and store the returned object in the <tt>email</tt> 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.</p>
<h3 id="changelog">7 Changelog</h3>
<ul>
<li>September 30, 2010: Fixed typos and reformatted Action Mailer configuration table for better understanding. <a href="http://jaimeiniesta.com">Jaime Iniesta</a></li>
</ul>
<h3>Feedback</h3>
<p>
You're encouraged to help in keeping the quality of this guide.
</p>
<p>
If you see any typos or factual errors you are confident to
patch, please clone <a href="https://github.com/lifo/docrails">docrails</a>
and push the change yourself. That branch of Rails has public write access.
Commits are still reviewed, but that happens after you've submitted your
contribution. <a href="https://github.com/lifo/docrails">docrails</a> is
cross-merged with master periodically.
</p>
<p>
You may also find incomplete content, or stuff that is not up to date.
Please do add any missing documentation for master. Check the
<a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
for style and conventions.
</p>
<p>
Issues may also be reported in <a href="https://github.com/lifo/docrails/issues">Github</a>.
</p>
<p>And last but not least, any kind of discussion regarding Ruby on Rails
documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
</p>
</div>
</div>
</div>
<hr class="hide" />
<div id="footer">
<div class="wrapper">
<p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p>
<p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
</div>
</div>
<script type="text/javascript" src="javascripts/guides.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
<script type="text/javascript">
SyntaxHighlighter.all()
</script>
</body>
</html>