mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
made a complete pass over the Action Mailer guide, it probably needs another one
This commit is contained in:
parent
b96ce7f946
commit
d50457c710
1 changed files with 71 additions and 104 deletions
|
@ -1,6 +1,6 @@
|
|||
h2. Action Mailer Basics
|
||||
|
||||
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 Action Mailer. It will also cover how to test your mailers.
|
||||
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 Action Mailer. It also covers how to test your mailers.
|
||||
|
||||
endprologue.
|
||||
|
||||
|
@ -27,49 +27,43 @@ create app/models/user_mailer.rb
|
|||
create test/unit/user_mailer_test.rb
|
||||
</shell>
|
||||
|
||||
So we got the model, the fixtures, and the tests all created for us
|
||||
So we got the model, the fixtures, and the tests.
|
||||
|
||||
h5. Edit the model:
|
||||
|
||||
Opening +app/models/user_mailer.rb+, you should see the empty mailer:
|
||||
+app/models/user_mailer.rb+ contains an empty mailer:
|
||||
|
||||
<ruby>
|
||||
class UserMailer < ActionMailer::Base
|
||||
end
|
||||
</ruby>
|
||||
|
||||
Lets add a method called +welcome_email+, that will send an email to the user's registered email address:
|
||||
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
|
||||
|
||||
def welcome_email(user)
|
||||
recipients user.email
|
||||
from "My Awesome Site Notifications <notifications@example.com>"
|
||||
subject "Welcome to My Awesome Site"
|
||||
sent_on Time.now
|
||||
body {:user => user, :url => "http://example.com/login"}
|
||||
content_type "text/html"
|
||||
end
|
||||
|
||||
end
|
||||
</ruby>
|
||||
|
||||
Here is a quick explanation of the options 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.
|
||||
|
||||
|recipients| The recipients of the email. It can be a string or, if there are multiple recipients, an array of strings|
|
||||
|from| Who the email will appear to come from in the recipients' mailbox|
|
||||
|from| The from address of the email|
|
||||
|subject| The subject of the email|
|
||||
|sent_on| Timestamp for the email|
|
||||
|content_type| The content type, by default is text/plain|
|
||||
|sent_on| The timestamp for the email|
|
||||
|
||||
The keys of the hash passed to `body` become instance variables in the view. Thus, in our example the mailer view will have a @user and a @url instance variables available.
|
||||
The keys of the hash passed to +body+ become instance variables in the view. Thus, in our example the mailer view will have a +@user+ and a +@url+ instance variables available.
|
||||
|
||||
h5. Create the mailer view
|
||||
h5. Create a mailer view
|
||||
|
||||
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.
|
||||
|
||||
The file can look like:
|
||||
Create a file called +welcome_email.text.html.erb+ in +app/views/user_mailer/+. This will be the template used for the email, formatted in HTML:
|
||||
|
||||
<erb>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
|
@ -88,6 +82,8 @@ The file can look like:
|
|||
</html>
|
||||
</erb>
|
||||
|
||||
Had we wanted to send text-only emails, the file would have been called +welcome_email.text.plain.erb+. Rails sets the content type of the email to be the one in the filename.
|
||||
|
||||
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.
|
||||
|
@ -97,25 +93,15 @@ Let's see how we would go about wiring it up using an observer:
|
|||
In +config/environment.rb+:
|
||||
|
||||
<ruby>
|
||||
# Code that already exists
|
||||
Rails::Initializer.run do |config|
|
||||
# Code that already exists
|
||||
# ...
|
||||
config.active_record.observers = :user_observer
|
||||
end
|
||||
</ruby>
|
||||
|
||||
You can place the observer in +app/models+ where it will be loaded automatically by Rails. Another option is to create an +app/observers+ folder to store all your observers, and add that to your load path. Open +config/environment.rb+ and make it look like:
|
||||
You can place the observer in +app/models+ where it will be loaded automatically by Rails.
|
||||
|
||||
<ruby>
|
||||
# Code that already exists
|
||||
Rails::Initializer.run do |config|
|
||||
# Code that already exists
|
||||
config.load_paths += %W(#{RAILS_ROOT}/app/observers)
|
||||
config.active_record.observers = :user_observer
|
||||
end
|
||||
</ruby>
|
||||
|
||||
Now create a file called user_observer in +app/models+ or +app/observers+ depending on where you stored it, and make it look like:
|
||||
Now create a file called +user_observer.rb+ in +app/models+ depending on where you stored it, and make it look like:
|
||||
|
||||
<ruby>
|
||||
class UserObserver < ActiveRecord::Observer
|
||||
|
@ -125,11 +111,11 @@ class UserObserver < ActiveRecord::Observer
|
|||
end
|
||||
</ruby>
|
||||
|
||||
Notice how we call +deliver_welcome_email+? In Action Mailer we send emails by calling deliver_name_of_method. In UserMailer, we defined a method called welcome_email, and so we deliver the email by calling deliver_welcome_email. The next section will go through how Action Mailer achieves this.
|
||||
Notice how we call +deliver_welcome_email+? In Action Mailer we send emails by calling +deliver_<method_name>+. In UserMailer, we defined a method called +welcome_email+, and so we deliver the email by calling +deliver_welcome_email+. The next section will go through how Action Mailer achieves this.
|
||||
|
||||
h4. Action Mailer and dynamic deliver_<method> methods
|
||||
h4. Action Mailer and dynamic deliver_<method_name> methods
|
||||
|
||||
So how does Action Mailer understand this deliver_welcome_email call? If you read the documentation (http://api.rubyonrails.org/files/vendor/rails/actionmailer/README.html), you will find this in the "Sending Emails" section:
|
||||
So how does Action Mailer understand this +deliver_welcome_email+ call? If you read the documentation (http://api.rubyonrails.org/files/vendor/rails/actionmailer/README.html), you will find this in the "Sending Emails" section:
|
||||
|
||||
You never instantiate your mailer class. Rather, your delivery instance methods are automatically wrapped in class methods that start with the word +deliver_+ followed by the name of the mailer method that you would like to deliver.
|
||||
|
||||
|
@ -150,32 +136,31 @@ end
|
|||
|
||||
Hence, 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 parameters. The resulting object is then sent the +deliver!+ method, which well... delivers it.
|
||||
|
||||
h4. Complete List of ActionMailer user-settable attributes
|
||||
h4. Complete list of Action Mailer user-settable attributes
|
||||
|
||||
|bcc| Specify the BCC addresses for the message|
|
||||
|body| Define the body of the message. This is either a Hash (in which case it specifies the variables to pass to the template when it is rendered), or a string, in which case it specifies the actual text of the message.|
|
||||
|cc| Specify the CC addresses for the message.|
|
||||
|charset| Specify the charset to use for the message. This defaults to the default_charset specified for ActionMailer::Base.|
|
||||
|content_type| Specify the content type for the message. This defaults to <text/plain in most cases, but can be automatically set in some situations.|
|
||||
|from| Specify the from address for the message.|
|
||||
|reply_to| Specify the address (if different than the "from" address) to direct replies to this message.|
|
||||
|headers| Specify additional headers to be added to the message.|
|
||||
|implicit_parts_order| Specify the order in which parts should be sorted, based on content-type. This defaults to the value for the default_implicit_parts_order.|
|
||||
|mime_version| Defaults to "1.0", but may be explicitly given if needed.|
|
||||
|recipient| The recipient addresses for the message, either as a string (for a single address) or an array (for multiple addresses).|
|
||||
|sent_on| The date on which the message was sent. If not set (the default), the header will be set by the delivery agent.|
|
||||
|subject| Specify the subject of the message.|
|
||||
|template| Specify the template name to use for current message. This is the "base" template name, without the extension or directory, and may be used to have multiple mailer methods share the same template.|
|
||||
|bcc| The BCC addresses of the email|
|
||||
|body| The body of the email. This is either a hash (in which case it specifies the variables to pass to the template when it is rendered), or a string, in which case it specifies the actual body of the message|
|
||||
|cc| The CC addresses for the email|
|
||||
|charset| The charset to use for the email. This defaults to the +default_charset+ specified for ActionMailer::Base.|
|
||||
|content_type| The content type for the email. This defaults to "text/plain" but the filename may specify it|
|
||||
|from| The from address of the email|
|
||||
|reply_to| The address (if different than the "from" address) to direct replies to this email|
|
||||
|headers| Additional headers to be added to the email|
|
||||
|implicit_parts_order| The order in which parts should be sorted, based on the content type. This defaults to the value of +default_implicit_parts_order+|
|
||||
|mime_version| Defaults to "1.0", but may be explicitly given if needed|
|
||||
|recipient| The recipient addresses of the email, either as a string (for a single address) or an array of strings (for multiple addresses)|
|
||||
|sent_on| The timestamp on which the message was sent. If unset, the header will be set by the delivery agent|
|
||||
|subject| The subject of the email|
|
||||
|template| The template to use. This is the "base" template name, without the extension or directory, and may be used to have multiple mailer methods share the same template|
|
||||
|
||||
h4. Mailer Views
|
||||
|
||||
Mailer views are located in /app/views/name_of_mailer_class. 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.txt.erb for the plain text version.
|
||||
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.text.html.erb+ for the HTML version and +welcome_email.text.plain.erb+ for the plain text version.
|
||||
|
||||
To change the default mailer view for your action you do something like:
|
||||
|
||||
<ruby>
|
||||
class UserMailer < ActionMailer::Base
|
||||
|
||||
def welcome_email(user)
|
||||
recipients user.email
|
||||
from "My Awesome Site Notifications<notifications@example.com>"
|
||||
|
@ -183,71 +168,63 @@ class UserMailer < ActionMailer::Base
|
|||
sent_on Time.now
|
||||
body {:user => user, :url => "http://example.com/login"}
|
||||
content_type "text/html"
|
||||
|
||||
# change the default from welcome_email.[html, txt].erb
|
||||
template "some_other_template" # this will be in app/views/user_mailer/some_other_template.[html, txt].erb
|
||||
end
|
||||
|
||||
# use some_other_template.text.(html|plain).erb instead
|
||||
template "some_other_template"
|
||||
end
|
||||
</ruby>
|
||||
|
||||
h4. Action Mailer Layouts
|
||||
|
||||
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:
|
||||
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.text.(html|plain).erb+. In order to use a different file just use:
|
||||
|
||||
<ruby>
|
||||
class UserMailer < ActionMailer::Base
|
||||
|
||||
layout 'awesome' # will use awesome.html.erb as the layout
|
||||
|
||||
layout 'awesome' # use awesome.text.(html|plain).erb as the layout
|
||||
end
|
||||
</ruby>
|
||||
|
||||
Just like with controller views, use yield to render the view inside the layout.
|
||||
Just like with controller views, use +yield+ to render the view inside the layout.
|
||||
|
||||
h4. Generating URL's in Action Mailer views
|
||||
h4. Generating URLs in Action Mailer views
|
||||
|
||||
URLs can be generated in mailer views using url_for or named routes.
|
||||
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.
|
||||
|
||||
When using url_for you'll need to provide the :host, :controller, and :action:
|
||||
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:
|
||||
When using named routes you only need to supply the +:host+:
|
||||
|
||||
<erb>
|
||||
<%= users_url(:host => "example.com") %>
|
||||
</erb>
|
||||
|
||||
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".
|
||||
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:
|
||||
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:
|
||||
|
||||
<erb>
|
||||
ActionMailer::Base.default_url_options[:host] = "example.com"
|
||||
</erb>
|
||||
|
||||
This can also be set as a configuration option in config/environment.rb:
|
||||
This can also be set as a configuration option in +config/environment.rb+:
|
||||
|
||||
<erb>
|
||||
config.action_mailer.default_url_options = { :host => "example.com" }
|
||||
</erb>
|
||||
|
||||
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.
|
||||
If you set a default +:host+ for your mailers you need to pass +:only_path => false+ to +url_for+. Otherwise it doesn't get included.
|
||||
|
||||
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.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.
|
||||
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.plain.erb+ and +welcome_email.text.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.
|
||||
|
||||
To explicitly specify multipart messages, you can do something like:
|
||||
|
||||
<ruby>
|
||||
class UserMailer < ActionMailer::Base
|
||||
|
||||
def welcome_email(user)
|
||||
recipients user.email_address
|
||||
subject "New account information"
|
||||
|
@ -261,17 +238,15 @@ class UserMailer < ActionMailer::Base
|
|||
p.body = "text content, can also be the name of an action that you call"
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
</ruby>
|
||||
|
||||
h4. Sending emails with attachments
|
||||
|
||||
Attachments can be added by using the attachment method:
|
||||
Attachments can be added by using the +attachment+ method:
|
||||
|
||||
<ruby>
|
||||
class UserMailer < ActionMailer::Base
|
||||
|
||||
def welcome_email(user)
|
||||
recipients user.email_address
|
||||
subject "New account information"
|
||||
|
@ -285,24 +260,21 @@ class UserMailer < ActionMailer::Base
|
|||
a.body = generate_your_pdf_here()
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
</ruby>
|
||||
|
||||
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:
|
||||
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:
|
||||
|
||||
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)'
|
||||
1. Implement a +receive+ method in your mailer.
|
||||
|
||||
2. Implement a receive method in your mailer
|
||||
2. 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 object‘s receive method. Here's an example:
|
||||
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(
|
||||
|
@ -319,12 +291,9 @@ class UserMailer < ActionMailer::Base
|
|||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
end
|
||||
</ruby>
|
||||
|
||||
|
||||
h3. Using Action Mailer Helpers
|
||||
|
||||
Action Mailer classes have 4 helper methods available to them:
|
||||
|
@ -352,7 +321,7 @@ The following configuration options are best made in one of the environment file
|
|||
|default_implicit_parts_order|When a message is built implicitly (i.e. multiple parts are assembled from templates which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to ["text/html", "text/enriched", "text/plain"]. Items that appear first in the array have higher priority in the mail client and appear last in the mime encoded message. You can also pick a different order from inside a method with implicit_parts_order.|
|
||||
|
||||
|
||||
h4. Example Action Mailer Configuration
|
||||
h4. Example Action Mailer configuration
|
||||
|
||||
An example would be:
|
||||
|
||||
|
@ -371,7 +340,7 @@ h4. Action Mailer Configuration for GMail
|
|||
|
||||
Instructions copied from http://http://www.fromjavatoruby.com/2008/11/actionmailer-with-gmail-must-issue.html
|
||||
|
||||
First you must install the action_mailer_tls plugin from http://code.openrain.com/rails/action_mailer_tls/, then all you have to do is configure action mailer.
|
||||
First you must install the +action_mailer_tls+ plugin from http://code.openrain.com/rails/action_mailer_tls/, then all you have to do is configure action mailer.
|
||||
|
||||
<ruby>
|
||||
ActionMailer::Base.smtp_settings = {
|
||||
|
@ -386,7 +355,7 @@ ActionMailer::Base.smtp_settings = {
|
|||
|
||||
h4. Configure Action Mailer to recognize HAML templates
|
||||
|
||||
In environment.rb, add the following line:
|
||||
In +config/environment.rb+, add the following line:
|
||||
|
||||
<ruby>
|
||||
ActionMailer::Base.register_template_extension('haml')
|
||||
|
@ -394,29 +363,27 @@ ActionMailer::Base.register_template_extension('haml')
|
|||
|
||||
h3. Mailer Testing
|
||||
|
||||
Testing mailers involves 2 things. One is that the mail was queued and the other that the body contains what we expect it to contain. With that in mind, we could test our example mailer from above like so:
|
||||
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
|
||||
tests UserMailer
|
||||
tests UserMailer
|
||||
|
||||
def test_welcome_email
|
||||
user = users(:some_user_in_your_fixtures)
|
||||
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?
|
||||
# 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 email.body =~ /Welcome to example.com, #{user.first_name}/
|
||||
end
|
||||
# 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 /Welcome to example.com, #{user.first_name}/, email.body
|
||||
end
|
||||
end
|
||||
</ruby>
|
||||
|
||||
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.
|
||||
|
||||
h3. Epilogue
|
||||
|
||||
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.
|
||||
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.
|
||||
|
|
Loading…
Reference in a new issue