Skip to content
This repository
Browse code

Finalised first draft of Active Mailer Basics guide

  • Loading branch information...
commit 9f097e3c83d36607bad55e2da8fcf2a2845a772e 1 parent 8e98b43
Ahmed El-Daly aeldaly authored

Showing 1 changed file with 159 additions and 25 deletions. Show diff stats Hide diff stats

  1. +159 25 railties/doc/guides/source/action_mailer_basics.txt
184 railties/doc/guides/source/action_mailer_basics.txt
... ... @@ -1,17 +1,17 @@
1 1 Action Mailer Basics
2 2 ====================
3 3
4   -This guide should provide you with all you need to get started in sending emails from your application, and will also cover how to test your mailers.
  4 +This guide should provide you with all you need to get started in sending and receiving emails from/to your application, and many internals of the ActionMailer class. It will also cover how to test your mailers.
5 5
6 6 == Introduction
7 7 Action Mailer allows you to send email from your application using a mailer model and views.
8   -Yes, that is correct, in Rails, emails are used by creating Models that inherit from ActionMailer::Base. They live alongside other models in /app/models BUT they have views just like controllers that appear alongside other views in app/views.
  8 +Yes, that is correct, in Rails, emails are used by creating models that inherit from ActionMailer::Base. They live alongside other models in /app/models BUT they have views just like controllers that appear alongside other views in app/views.
9 9
10 10 == Sending Emails
11 11 Let's say you want to send a welcome email to a user after they signup. Here is how you would go about this:
12 12
13 13 === Walkthrough to generating a Mailer
14   -==== 1. Create the mailer:
  14 +==== Create the mailer:
15 15 [source, shell]
16 16 -------------------------------------------------------
17 17 ./script/generate mailer UserMailer
@@ -25,7 +25,9 @@ create test/unit/user_mailer_test.rb
25 25
26 26 So we got the model, the fixtures, and the tests all created for us
27 27
28   -==== 2. Edit the model:
  28 +==== Edit the model:
  29 +
  30 +If you look at app/models/user_mailer.rb, you will see:
29 31 [source, ruby]
30 32 -------------------------------------------------------
31 33 class UserMailer < ActionMailer::Base
@@ -34,7 +36,6 @@ end
34 36 -------------------------------------------------------
35 37
36 38 Lets add a method called welcome_email, that will send an email to the user's registered email address:
37   -
38 39 [source, ruby]
39 40 -------------------------------------------------------
40 41 class UserMailer < ActionMailer::Base
@@ -52,15 +53,18 @@ end
52 53 -------------------------------------------------------
53 54
54 55 So what do we have here?
55   -recipients: who the recipients are, put in an array for multiple, ie, @recipients = ["user1@example.com", "user2@example.com"]
56   -from: Who the email will appear to come from in the recipients' mailbox
57   -subject: The subject of the email
58   -sent_on: Timestamp for the email
59   -content_type: The content type, by default is text/plain
  56 +[width="100%", cols="20%,80%"]
  57 +|======================================================
  58 +|recipients| who the recipients are, put in an array for multiple, ie, @recipients = ["user1@example.com", "user2@example.com"]
  59 +|from| Who the email will appear to come from in the recipients' mailbox
  60 +|subject| The subject of the email
  61 +|sent_on| Timestamp for the email
  62 +|content_type| The content type, by default is text/plain
  63 +|======================================================
60 64
61 65 How about @body[:user]? Well anything you put in the @body hash will appear in the mailer view (more about mailer views below) as an instance variable ready for you to use, ie, in our example the mailer view will have a @user instance variable available for its consumption.
62 66
63   -==== 3. Create the mailer view
  67 +==== Create the mailer view
64 68 Create a file called welcome_email.html.erb in #{RAILS_ROOT}/app/views/user_mailer/ . This will be the template used for the email. This file will be used for html formatted emails. Had we wanted to send text-only emails, the file would have been called welcome_email.txt.erb, and we would have set the content type to text/plain in the mailer model.
65 69
66 70 The file can look like:
@@ -73,7 +77,6 @@ The file can look like:
73 77 </head>
74 78 <body>
75 79 <h1>Welcome to example.com, <%= @user.first_name %></h1>
76   -
77 80 <p>
78 81 You have successfully signed up to example.com, and your username is: <%= @user.login %>.<br/>
79 82 To login to the site, just follow this link: <%= @url %>.
@@ -83,10 +86,12 @@ The file can look like:
83 86 </html>
84 87 -------------------------------------------------------
85 88
86   -==== 4. Wire it up so that the system sends the email when a user signs up
87   -There are 3 was 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 block 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.
  89 +==== Wire it up so that the system sends the email when a user signs up
  90 +There are 3 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 block 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.
88 91
89   -Edit #{RAILS_ROOT}/config/environment.rb
  92 +Let's see how we would go about wiring it up using an observer:
  93 +
  94 +In config/environment.rb:
90 95 [source, ruby]
91 96 -------------------------------------------------------
92 97 # Code that already exists
@@ -100,7 +105,7 @@ Rails::Initializer.run do |config|
100 105 end
101 106 -------------------------------------------------------
102 107
103   -There was a bit of a debate on where to put observers. I put them in models, but you can create #{RAILS_ROOT}/app/observers if you like, and add that to your load path. Open #{RAILS_ROOT}/config/environment.rb and make it look like:
  108 +There was a bit of a debate on where to put observers. Some people put them in app/models, but a cleaner method may be to create an app/observers folder to store all observers, and add that to your load path. Open config/environment.rb and make it look like:
104 109 [source, ruby]
105 110 -------------------------------------------------------
106 111 # Code that already exists
@@ -117,7 +122,7 @@ end
117 122 -------------------------------------------------------
118 123
119 124 ALMOST THERE :) Now all we need is that danged observer, and we're done:
120   -Create a file called user_observer in #{RAILS_ROOT}/app/models or #{RAILS_ROOT}/app/observers, and make it look like:
  125 +Create a file called user_observer in app/models or app/observers depending on where you stored it, and make it look like:
121 126 [source, ruby]
122 127 -------------------------------------------------------
123 128 class UserObserver < ActiveRecord::Observer
@@ -155,7 +160,7 @@ def method_missing(method_symbol, *parameters)#:nodoc:
155 160 end
156 161 -------------------------------------------------------
157 162
158   -Ah, this makes things so much clearer :) so if the method name starts with deliver_ followed by any combination of lowercase letters or underscore, method missing calls new on your mailer class UserMailer in our example above, sending the combination of lower case letters or underscore, along with the parameter. The resulting object is then sent the deliver! method, which well... delivers it.
  163 +Ah, this makes things so much clearer :) so if the method name starts with deliver_ followed by any combination of lowercase letters or underscore, method missing calls new on your mailer class (UserMailer in our example above), sending the combination of lower case letters or underscore, along with the parameter. The resulting object is then sent the deliver! method, which well... delivers it.
159 164
160 165 === Complete List of ActionMailer user-settable attributes
161 166
@@ -215,7 +220,7 @@ end
215 220 -------------------------------------------------------
216 221
217 222 === Action Mailer Layouts
218   -Just like controller views, you can also have mailer layouts. The layout needs end in _mailer to be automatically recognized by your mailer as a layout. So in our UserMailer example, we need to call our layout user_mailer.[html,txt].erb. In order to use a different file just use:
  223 +Just like controller views, you can also have mailer layouts. The layout name needs to end in _mailer to be automatically recognized by your mailer as a layout. So in our UserMailer example, we need to call our layout user_mailer.[html,txt].erb. In order to use a different file just use:
219 224
220 225 [source, ruby]
221 226 -------------------------------------------------------
@@ -228,12 +233,145 @@ end
228 233
229 234 Just like with controller views, use yield to render the view inside the layout.
230 235
  236 +=== Generating URL's in Action Mailer views
  237 +URLs can be generated in mailer views using url_for or named routes.
  238 +Unlike controllers from Action Pack, the mailer instance doesn't have any context about the incoming request, so you'll need to provide all of the details needed to generate a URL.
  239 +
  240 +When using url_for you'll need to provide the :host, :controller, and :action:
  241 +
  242 + <%= url_for(:host => "example.com", :controller => "welcome", :action => "greeting") %>
  243 +
  244 +When using named routes you only need to supply the :host:
  245 +
  246 + <%= users_url(:host => "example.com") %>
  247 +
  248 +You will want to avoid using the name_of_route_path form of named routes because it doesn't make sense to generate relative URLs in email messages. The reason that it doesn't make sense is because the email is opened on a mail client outside of your environment. Since the email is not being served by your server, a URL like "/users/show/1", will have no context. In order for the email client to properly link to a URL on your server it needs something like "http://yourserver.com/users/show/1".
  249 +
  250 +It is also possible to set a default host that will be used in all mailers by setting the :host option in
  251 +the ActionMailer::Base.default_url_options hash as follows:
  252 +
  253 + ActionMailer::Base.default_url_options[:host] = "example.com"
  254 +
  255 +This can also be set as a configuration option in config/environment.rb:
  256 +
  257 + config.action_mailer.default_url_options = { :host => "example.com" }
  258 +
  259 +If you do decide to set a default :host for your mailers you will want to use 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.
  260 +
231 261 === Sending multipart emails
232   -Coming soon!
  262 +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.txt.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.
  263 +
  264 +To explicitly specify multipart messages, you can do something like:
  265 +[source, ruby]
  266 +-------------------------------------------------------
  267 +class UserMailer < ActionMailer::Base
  268 +
  269 + def welcome_email(user)
  270 + recipients user.email_address
  271 + subject "New account information"
  272 + from "system@example.com"
  273 + content_type "multipart/alternative"
  274 +
  275 + part :content_type => "text/html",
  276 + :body => "<p>html content, can also be the name of an action that you call<p>"
  277 +
  278 + part "text/plain" do |p|
  279 + p.body = "text content, can also be the name of an action that you call"
  280 + end
  281 + end
  282 +
  283 +end
  284 +-------------------------------------------------------
  285 +
  286 +=== Sending emails with attachments
  287 +Attachments can be added by using the attachment method:
  288 +[source, ruby]
  289 +-------------------------------------------------------
  290 +class UserMailer < ActionMailer::Base
  291 +
  292 + def welcome_email(user)
  293 + recipients user.email_address
  294 + subject "New account information"
  295 + from "system@example.com"
  296 + content_type "multipart/alternative"
  297 +
  298 + attachment :content_type => "image/jpeg",
  299 + :body => File.read("an-image.jpg")
  300 +
  301 + attachment "application/pdf" do |a|
  302 + a.body = generate_your_pdf_here()
  303 + end
  304 + end
  305 +
  306 +end
  307 +-------------------------------------------------------
233 308
234 309 == Receiving Emails
  310 +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.
  311 +So, to receive emails in your Rails app you'll need:
  312 +
  313 +1. 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)'
  314 +
  315 +2. Implement a receive method in your mailer
  316 +
  317 +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 object‘s receive method. Here's an example:
  318 +
  319 +[source, ruby]
  320 +-------------------------------------------------------
  321 +class UserMailer < ActionMailer::Base
  322 +
  323 + def receive(email)
  324 + page = Page.find_by_address(email.to.first)
  325 + page.emails.create(
  326 + :subject => email.subject,
  327 + :body => email.body
  328 + )
  329 +
  330 + if email.has_attachments?
  331 + for attachment in email.attachments
  332 + page.attachments.create({
  333 + :file => attachment,
  334 + :description => email.subject
  335 + })
  336 + end
  337 + end
  338 + end
  339 +
  340 +
  341 +end
  342 +-------------------------------------------------------
  343 +
235 344
236 345 == Using Action Mailer Helpers
  346 +Action Mailer classes have 4 helper methods available to them:
  347 +[width="100%", cols="2,8"]
  348 +|======================================================
  349 +|add_template_helper(helper_module)|Makes all the (instance) methods in the helper module available to templates rendered through this controller.
  350 +
  351 +|helper(*args, &block)|
  352 +Declare a helper:
  353 + helper :foo
  354 +requires 'foo_helper' and includes FooHelper in the template class.
  355 + helper FooHelper
  356 +includes FooHelper in the template class.
  357 + helper { def foo() "#{bar} is the very best" end }
  358 +evaluates the block in the template class, adding method foo.
  359 + helper(:three, BlindHelper) { def mice() 'mice' end }
  360 +does all three.
  361 +
  362 +|helper_method|
  363 +Declare a controller method as a helper. For example,
  364 + helper_method :link_to
  365 + def link_to(name, options) ... end
  366 +makes the link_to controller method available in the view.
  367 +
  368 +|helper_attr|
  369 +Declare a controller attribute as a helper. For example,
  370 + helper_attr :name
  371 + attr_accessor :name
  372 +makes the name and name= controller methods available in the view.
  373 +The is a convenience wrapper for helper_method.
  374 +|======================================================
237 375
238 376 == Action Mailer Configuration
239 377 The following configuration options are best made in one of the environment files (environment.rb, production.rb, etc...)
@@ -342,8 +480,4 @@ class UserMailerTest < ActionMailer::TestCase
342 480 What have we done? Well, we sent the email and stored the returned object in the email variable. We then ensured that it was sent (the first assert), then, in the second batch of assertion, we ensure that the email does indeed contain the values that we expect.
343 481
344 482 == Epilogue
345   -This guide presented how to create a mailer and how to test it. In reality, you may find that writing your tests before you actually write your code to be a rewarding experience. It may take some time to get used to TDD (Test Driven Development), but coding this way achieves two major benefits. Firstly, you know that the code does indeed work, because the tests fail (because there's no code), then they pass, because the code that satisfies the tests was written. Secondly, when you start with the tests, you don't have to make time AFTER you write the code, to write the tests, then never get around to it. The tests are already there and testing has now become part of your coding regimen.
346   -
347   -== Changelog ==
348   -
349   -http://rails.lighthouseapp.com/projects/16213/tickets/25[Lighthouse ticket]
  483 +This guide presented how to create a mailer and how to test it. In reality, you may find that writing your tests before you actually write your code to be a rewarding experience. It may take some time to get used to TDD (Test Driven Development), but coding this way achieves two major benefits. Firstly, you know that the code does indeed work, because the tests fail (because there's no code), then they pass, because the code that satisfies the tests was written. Secondly, when you start with the tests, you don't have to make time AFTER you write the code, to write the tests, then never get around to it. The tests are already there and testing has now become part of your coding regimen.

0 comments on commit 9f097e3

Please sign in to comment.
Something went wrong with that request. Please try again.