mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
get the Action Mailer guide ready. [ci skip]
This commit is contained in:
parent
0d8a76d8d4
commit
d4ae49b058
2 changed files with 239 additions and 119 deletions
|
@ -1,7 +1,9 @@
|
|||
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.
|
||||
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.
|
||||
|
||||
After reading this guide, you will know:
|
||||
|
||||
|
@ -9,17 +11,22 @@ After reading this guide, you will know:
|
|||
* How to generate and edit an Action Mailer class and mailer view.
|
||||
* How to configure Action Mailer for your environment.
|
||||
* How to test your Action Mailer classes.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
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`.
|
||||
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`.
|
||||
|
||||
Sending Emails
|
||||
--------------
|
||||
|
||||
This section will provide a step-by-step guide to creating a mailer and its views.
|
||||
This section will provide a step-by-step guide to creating a mailer and its
|
||||
views.
|
||||
|
||||
### Walkthrough to Generating a Mailer
|
||||
|
||||
|
@ -34,10 +41,25 @@ invoke test_unit
|
|||
create test/mailers/user_mailer_test.rb
|
||||
```
|
||||
|
||||
So we got the mailer, the views, and the tests.
|
||||
As you can see, you can generate mailers just like you use other generators with
|
||||
Rails. Mailers are conceptually similar to controllers, and so we get a mailer,
|
||||
a directory for views, and a test.
|
||||
|
||||
If you didn't want to use a generator, you could create your own file inside of
|
||||
app/mailers, just make sure that it inherits from `ActionMailer::Base`:
|
||||
|
||||
```ruby
|
||||
class MyMailer < ActionMailer::Base
|
||||
end
|
||||
```
|
||||
|
||||
#### Edit the Mailer
|
||||
|
||||
Mailers are very similar to Rails controllers. They also have methods called
|
||||
"actions" and use views to structure the content. Where a controller generates
|
||||
content like HTML to send back to the client, a Mailer creates a message to be
|
||||
delivered via email.
|
||||
|
||||
`app/mailers/user_mailer.rb` contains an empty mailer:
|
||||
|
||||
```ruby
|
||||
|
@ -46,7 +68,8 @@ class UserMailer < ActionMailer::Base
|
|||
end
|
||||
```
|
||||
|
||||
Let's 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
|
||||
|
@ -55,21 +78,28 @@ class UserMailer < ActionMailer::Base
|
|||
def welcome_email(user)
|
||||
@user = user
|
||||
@url = 'http://example.com/login'
|
||||
mail(to: user.email, subject: 'Welcome to My Awesome Site')
|
||||
mail(to: @user.email, subject: 'Welcome to My Awesome Site')
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
* `default Hash` - This is a hash of default values for any email you send, in this case we are setting the `:from` header to a value for all messages in this class, this can be overridden on a per email basis
|
||||
* `mail` - The actual email message, we are passing the `:to` and `:subject` headers in.
|
||||
* `default Hash` - This is a hash of default values for any email you send, in
|
||||
this case we are setting the `:from` header to a value for all messages in
|
||||
this class, this can be overridden on a per email basis
|
||||
* `mail` - The actual email message, we are passing the `:to` and `:subject`
|
||||
headers in.
|
||||
|
||||
Just like controllers, any instance variables we define in the method become available for use in the views.
|
||||
Just like controllers, any instance variables we define in the method become
|
||||
available for use in the views.
|
||||
|
||||
#### 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:
|
||||
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:
|
||||
|
||||
```html+erb
|
||||
<!DOCTYPE html>
|
||||
|
@ -91,7 +121,9 @@ Create a file called `welcome_email.html.erb` in `app/views/user_mailer/`. This
|
|||
</html>
|
||||
```
|
||||
|
||||
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/`:
|
||||
Let's also make a text part for this email. Not all clients prefer HTML emails,
|
||||
and so sending both is best practice. To do this, create a file called
|
||||
`welcome_email.text.erb` in `app/views/user_mailer/`:
|
||||
|
||||
```erb
|
||||
Welcome to example.com, <%= @user.name %>
|
||||
|
@ -105,11 +137,15 @@ To login to the site, just follow this link: <%= @url %>.
|
|||
Thanks for joining and have a great day!
|
||||
```
|
||||
|
||||
When you call the `mail` method now, Action Mailer will detect the two templates (text and HTML) and automatically generate a `multipart/alternative` email.
|
||||
When you call the `mail` method now, Action Mailer will detect the two templates
|
||||
(text and HTML) and automatically generate a `multipart/alternative` email.
|
||||
|
||||
#### Wire It Up So That the System Sends the Email When a User Signs Up
|
||||
#### Calling the Mailer
|
||||
|
||||
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, mailers are really just another way to render a view. Instead of rendering a view and sending out the HTTP protocol, they are just sending it out through the Email protocols instead. Due to this, it makes sense to just have your controller tell the mailer to send an email when a user is successfully created.
|
||||
Mailers are really just another way to render a view. Instead of rendering a
|
||||
view and sending out the HTTP protocol, they are just sending it out through the
|
||||
Email protocols instead. Due to this, it makes sense to just have your
|
||||
controller tell the Mailer to send an email when a user is successfully created.
|
||||
|
||||
Setting this up is painfully simple.
|
||||
|
||||
|
@ -120,7 +156,10 @@ $ rails generate scaffold user name email login
|
|||
$ rake db:migrate
|
||||
```
|
||||
|
||||
Now that we have a user model to play with, we will just edit the `app/controllers/users_controller.rb` make it instruct the UserMailer to deliver an email to the newly created user by editing the create action and inserting a call to `UserMailer.welcome_email` right after the user is successfully saved:
|
||||
Now that we have a user model to play with, we will just edit the
|
||||
`app/controllers/users_controller.rb` make it instruct the UserMailer to deliver
|
||||
an email to the newly created user by editing the create action and inserting a
|
||||
call to `UserMailer.welcome_email` right after the user is successfully saved:
|
||||
|
||||
```ruby
|
||||
class UsersController < ApplicationController
|
||||
|
@ -145,63 +184,50 @@ class UsersController < ApplicationController
|
|||
end
|
||||
```
|
||||
|
||||
This provides a much simpler implementation that does not require the registering of observers and the like.
|
||||
|
||||
The method `welcome_email` returns a `Mail::Message` object which can then just be told `deliver` to send itself out.
|
||||
The method `welcome_email` returns a `Mail::Message` object which can then just
|
||||
be told `deliver` to send itself out.
|
||||
|
||||
### Auto encoding header values
|
||||
|
||||
Action Mailer now handles the auto encoding of multibyte characters inside of headers and bodies.
|
||||
Action Mailer handles the auto encoding of multibyte characters inside of
|
||||
headers and bodies.
|
||||
|
||||
If you are using UTF-8 as your character set, you do not have to do anything special, just go ahead and send in UTF-8 data to the address fields, subject, keywords, filenames or body of the email and Action Mailer will auto encode it into quoted printable for you in the case of a header field or Base64 encode any body parts that are non US-ASCII.
|
||||
|
||||
For more complex examples such as defining alternate character sets or self-encoding text first, please refer to the Mail library.
|
||||
For more complex examples such as defining alternate character sets or
|
||||
self-encoding text first, please refer to the
|
||||
[Mail](https://github.com/mikel/mail) library.
|
||||
|
||||
### Complete List of Action Mailer Methods
|
||||
|
||||
There are just three methods that you need to send pretty much any email message:
|
||||
There are just three methods that you need to send pretty much any email
|
||||
message:
|
||||
|
||||
* `headers` - Specifies any header on the email you want. You can pass a hash of header field names and value pairs, or you can call `headers[:field_name] = 'value'`.
|
||||
* `attachments` - Allows you to add attachments to your email. For example, `attachments['file-name.jpg'] = File.read('file-name.jpg')`.
|
||||
* `mail` - Sends the actual email itself. You can pass in headers as a hash to the mail method as a parameter, mail will then create an email, either plain text, or multipart, depending on what email templates you have defined.
|
||||
|
||||
#### 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)
|
||||
```
|
||||
|
||||
* Passing in a key value assignment to the `headers` method:
|
||||
|
||||
```ruby
|
||||
headers['X-Spam'] = value
|
||||
```
|
||||
|
||||
* Passing a hash of key value pairs to the `headers` method:
|
||||
|
||||
```ruby
|
||||
headers {'X-Spam' => value, 'X-Special' => another_value}
|
||||
```
|
||||
|
||||
TIP: All `X-Value` headers per the RFC2822 can appear more than once. If you want to delete an `X-Value` header, you need to assign it a value of `nil`.
|
||||
* `headers` - Specifies any header on the email you want. You can pass a hash of
|
||||
header field names and value pairs, or you can call `headers[:field_name] =
|
||||
'value'`.
|
||||
* `attachments` - Allows you to add attachments to your email. For example,
|
||||
`attachments['file-name.jpg'] = File.read('file-name.jpg')`.
|
||||
* `mail` - Sends the actual email itself. You can pass in headers as a hash to
|
||||
the mail method as a parameter, mail will then create an email, either plain
|
||||
text, or multipart, depending on what email templates you have defined.
|
||||
|
||||
#### Adding Attachments
|
||||
|
||||
Adding attachments has been simplified in Action Mailer 3.0.
|
||||
Action Mailer makes it very easy to add attachments.
|
||||
|
||||
* 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.
|
||||
* Pass the file name and content and Action Mailer and the
|
||||
[Mail gem](https://github.com/mikel/mail) will automatically guess the
|
||||
mime_type, set the encoding and create the attachment.
|
||||
|
||||
```ruby
|
||||
attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
|
||||
```
|
||||
|
||||
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.
|
||||
NOTE: Mail will automatically Base64 encode an attachment. If you want something
|
||||
different, 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.
|
||||
* 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'))
|
||||
|
@ -210,13 +236,13 @@ NOTE: Mail will automatically Base64 encode an attachment. If you want something
|
|||
content: encoded_content }
|
||||
```
|
||||
|
||||
NOTE: If you specify an encoding, Mail will assume that your content is already encoded and not try to Base64 encode it.
|
||||
NOTE: If you specify an encoding, Mail will assume that your content is already
|
||||
encoded and not try to Base64 encode it.
|
||||
|
||||
#### Making Inline Attachments
|
||||
|
||||
Action Mailer 3.0 makes inline attachments, which involved a lot of hacking in pre 3.0 versions, much simpler and trivial as they should be.
|
||||
|
||||
* Firstly, to tell Mail to turn an attachment into an inline attachment, you just call `#inline` on the attachments method within your Mailer:
|
||||
* Firstly, to tell Mail to turn an attachment into an inline attachment, you
|
||||
just call `#inline` on the attachments method within your Mailer:
|
||||
|
||||
```ruby
|
||||
def welcome
|
||||
|
@ -224,7 +250,9 @@ Action Mailer 3.0 makes inline attachments, which involved a lot of hacking in p
|
|||
end
|
||||
```
|
||||
|
||||
* Then in your view, you can just reference `attachments[]` as a hash and specify which attachment you want to show, calling `url` on it and then passing the result into the `image_tag` method:
|
||||
* Then in your view, you can just reference `attachments` as a hash and specify
|
||||
which attachment you want to show, calling `url` on it and then passing the
|
||||
result into the `image_tag` method:
|
||||
|
||||
```html+erb
|
||||
<p>Hello there, this is our image</p>
|
||||
|
@ -232,7 +260,8 @@ Action Mailer 3.0 makes inline attachments, which involved a lot of hacking in p
|
|||
<%= image_tag attachments['image.jpg'].url %>
|
||||
```
|
||||
|
||||
* As this is a standard call to `image_tag` you can pass in an options hash after the attachment URL as you could for any other image:
|
||||
* As this is a standard call to `image_tag` you can pass in an options hash
|
||||
after the attachment URL as you could for any other image:
|
||||
|
||||
```html+erb
|
||||
<p>Hello there, this is our image</p>
|
||||
|
@ -243,7 +272,10 @@ Action Mailer 3.0 makes inline attachments, which involved a lot of hacking in p
|
|||
|
||||
#### Sending Email To Multiple Recipients
|
||||
|
||||
It is possible to send email to one or more recipients in one email (e.g., informing all admins of a new signup) by setting the list of emails to the `:to` key. The list of emails can be an array of email addresses or a single string with the addresses separated by commas.
|
||||
It is possible to send email to one or more recipients in one email (e.g.,
|
||||
informing all admins of a new signup) by setting the list of emails to the `:to`
|
||||
key. The list of emails can be an array of email addresses or a single string
|
||||
with the addresses separated by commas.
|
||||
|
||||
```ruby
|
||||
class AdminMailer < ActionMailer::Base
|
||||
|
@ -257,12 +289,14 @@ class AdminMailer < ActionMailer::Base
|
|||
end
|
||||
```
|
||||
|
||||
The same format can be used to set carbon copy (Cc:) and blind carbon copy (Bcc:) recipients, by using the `:cc` and `:bcc` keys respectively.
|
||||
The same format can be used to set carbon copy (Cc:) and blind carbon copy
|
||||
(Bcc:) recipients, by using the `:cc` and `:bcc` keys respectively.
|
||||
|
||||
#### Sending Email With Name
|
||||
|
||||
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 `"Name <email>"`.
|
||||
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 `"Name <email>"`.
|
||||
|
||||
```ruby
|
||||
def welcome_email(user)
|
||||
|
@ -274,7 +308,11 @@ end
|
|||
|
||||
### 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 its name is the same as the mailer method. In our example from above, our mailer view for the `welcome_email` method will be in `app/views/user_mailer/welcome_email.html.erb` for the HTML version and `welcome_email.text.erb` for the plain text version.
|
||||
Mailer views are located in the `app/views/name_of_mailer_class` directory. The
|
||||
specific mailer view is known to the class because its name is the same as the
|
||||
mailer method. In our example from above, our mailer view for the
|
||||
`welcome_email` method will be in `app/views/user_mailer/welcome_email.html.erb`
|
||||
for the HTML version and `welcome_email.text.erb` for the plain text version.
|
||||
|
||||
To change the default mailer view for your action you do something like:
|
||||
|
||||
|
@ -285,7 +323,7 @@ class UserMailer < ActionMailer::Base
|
|||
def welcome_email(user)
|
||||
@user = user
|
||||
@url = 'http://example.com/login'
|
||||
mail(to: user.email,
|
||||
mail(to: @user.email,
|
||||
subject: 'Welcome to My Awesome Site',
|
||||
template_path: 'notifications',
|
||||
template_name: 'another')
|
||||
|
@ -293,9 +331,12 @@ class UserMailer < ActionMailer::Base
|
|||
end
|
||||
```
|
||||
|
||||
In this case it will look for templates at `app/views/notifications` with name `another`. You can also specify an array of paths for `template_path`, and they will be searched in order.
|
||||
In this case it will look for templates at `app/views/notifications` with name
|
||||
`another`. You can also specify an array of paths for `template_path`, and they
|
||||
will be searched in order.
|
||||
|
||||
If you want more flexibility you can also pass a block and render specific templates or even render inline or text without using a template file:
|
||||
If you want more flexibility you can also pass a block and render specific
|
||||
templates or even render inline or text without using a template file:
|
||||
|
||||
```ruby
|
||||
class UserMailer < ActionMailer::Base
|
||||
|
@ -304,21 +345,26 @@ class UserMailer < ActionMailer::Base
|
|||
def welcome_email(user)
|
||||
@user = user
|
||||
@url = 'http://example.com/login'
|
||||
mail(to: user.email,
|
||||
mail(to: @user.email,
|
||||
subject: 'Welcome to My Awesome Site') do |format|
|
||||
format.html { render 'another_template' }
|
||||
format.text { render text: 'Render text' }
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
```
|
||||
|
||||
This will render the template 'another_template.html.erb' for the HTML part and use the rendered text for the text part. The render command is the same one used inside of Action Controller, so you can use all the same options, such as `:text`, `:inline` etc.
|
||||
This will render the template 'another_template.html.erb' for the HTML part and
|
||||
use the rendered text for the text part. The render command is the same one used
|
||||
inside of Action Controller, so you can use all the same options, such as
|
||||
`:text`, `:inline` etc.
|
||||
|
||||
### 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.
|
||||
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:
|
||||
|
||||
|
@ -328,9 +374,11 @@ class UserMailer < ActionMailer::Base
|
|||
end
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
You can also pass in a `layout: 'layout_name'` option to the render call inside the format block to specify different layouts for different actions:
|
||||
You can also pass in a `layout: 'layout_name'` option to the render call inside
|
||||
the format block to specify different layouts for different actions:
|
||||
|
||||
```ruby
|
||||
class UserMailer < ActionMailer::Base
|
||||
|
@ -343,13 +391,37 @@ class UserMailer < ActionMailer::Base
|
|||
end
|
||||
```
|
||||
|
||||
Will render the HTML part using the `my_layout.html.erb` file and the text part with the usual `user_mailer.text.erb` file if it exists.
|
||||
Will render the HTML part using the `my_layout.html.erb` file and the text part
|
||||
with the usual `user_mailer.text.erb` file if it exists.
|
||||
|
||||
### 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` parameter yourself.
|
||||
|
||||
As the `:host` usually is consistent across the application you can configure it
|
||||
globally in `config/application.rb`:
|
||||
|
||||
```ruby
|
||||
config.action_mailer.default_url_options = { host: 'example.com' }
|
||||
```
|
||||
|
||||
#### generating URLs with `url_for`
|
||||
|
||||
You need to pass the `only_path: false` option when using `url_for`. This will
|
||||
ensure that absolute URLs are generated because the `url_for` view helper will,
|
||||
by default, generate relative URLs when a `:host` option isn't explicitly
|
||||
provided.
|
||||
|
||||
```erb
|
||||
<%= url_for(controller: 'welcome',
|
||||
action: 'greeting',
|
||||
only_path: false) %>
|
||||
```
|
||||
|
||||
If you did not configure the `:host` option globally make sure to pass it to
|
||||
`url_for`.
|
||||
|
||||
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',
|
||||
|
@ -357,27 +429,32 @@ Unlike controllers, the mailer instance doesn't have any context about the incom
|
|||
action: 'greeting') %>
|
||||
```
|
||||
|
||||
When using named routes you only need to supply the `:host`:
|
||||
NOTE: When you explicitly pass the `:host` Rails will always generate absolute
|
||||
URLs, so there is no need to pass `only_path: false`.
|
||||
|
||||
#### generating URLs with named routes
|
||||
|
||||
Email clients have no web context and so paths have no base URL to form complete
|
||||
web addresses. Thus, you should always use the "_url" variant of named route
|
||||
helpers.
|
||||
|
||||
If you did not configure the `:host` option globally make sure to pass it to the
|
||||
url helper.
|
||||
|
||||
```erb
|
||||
<%= user_url(@user, host: 'example.com') %>
|
||||
```
|
||||
|
||||
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 as a configuration option in `config/application.rb`:
|
||||
|
||||
```ruby
|
||||
config.action_mailer.default_url_options = { host: 'example.com' }
|
||||
```
|
||||
|
||||
If you use this setting, you should pass the `only_path: false` option when using `url_for`. This will ensure that absolute URLs are generated because the `url_for` view helper will, by default, generate relative URLs when a `:host` option isn't explicitly provided.
|
||||
|
||||
### 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.
|
||||
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 `:parts_order` inside of the `ActionMailer::Base.default` method.
|
||||
The order of the parts getting inserted is determined by the `:parts_order`
|
||||
inside of the `ActionMailer::Base.default` method.
|
||||
|
||||
### Sending Emails with Attachments
|
||||
|
||||
|
@ -389,38 +466,51 @@ class UserMailer < ActionMailer::Base
|
|||
@user = user
|
||||
@url = user_url(@user)
|
||||
attachments['terms.pdf'] = File.read('/path/terms.pdf')
|
||||
mail(to: user.email,
|
||||
mail(to: @user.email,
|
||||
subject: 'Please see the Terms and Conditions attached')
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
The above will send a multipart email with an attachment, properly nested with the top level being `multipart/mixed` and the first part being a `multipart/alternative` containing the plain text and HTML email messages.
|
||||
The above will send a multipart email with an attachment, properly nested with
|
||||
the top level being `multipart/mixed` and the first part being a
|
||||
`multipart/alternative` containing the plain text and HTML email messages.
|
||||
|
||||
### Sending Emails with Dynamic Delivery Options
|
||||
|
||||
If you wish to override the default delivery options (e.g. SMTP credentials) while delivering emails, you can do this using `delivery_method_options` in the mailer action.
|
||||
If you wish to override the default delivery options (e.g. SMTP credentials)
|
||||
while delivering emails, you can do this using `delivery_method_options` in the
|
||||
mailer action.
|
||||
|
||||
```ruby
|
||||
class UserMailer < ActionMailer::Base
|
||||
def welcome_email(user, company)
|
||||
@user = user
|
||||
@url = user_url(@user)
|
||||
delivery_options = { user_name: company.smtp_user, password: company.smtp_password, address: company.smtp_host }
|
||||
mail(to: user.email, subject: "Please see the Terms and Conditions attached", delivery_method_options: delivery_options)
|
||||
delivery_options = { user_name: company.smtp_user,
|
||||
password: company.smtp_password,
|
||||
address: company.smtp_host }
|
||||
mail(to: @user.email,
|
||||
subject: "Please see the Terms and Conditions attached",
|
||||
delivery_method_options: delivery_options)
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
### Sending Emails without Template Rendering
|
||||
|
||||
There may be cases in which you want to skip the template rendering step and supply the email body as a string. You can achieve this using the `:body` option.
|
||||
In such cases don't forget to add the `:content_type` option. Rails will default to `text/plain` otherwise.
|
||||
There may be cases in which you want to skip the template rendering step and
|
||||
supply the email body as a string. You can achieve this using the `:body`
|
||||
option. In such cases don't forget to add the `:content_type` option. Rails
|
||||
will default to `text/plain` otherwise.
|
||||
|
||||
```ruby
|
||||
class UserMailer < ActionMailer::Base
|
||||
def welcome_email(user, email_body)
|
||||
mail(to: user.email, body: email_body, content_type: "text/html", subject: "Already rendered!")
|
||||
mail(to: user.email,
|
||||
body: email_body,
|
||||
content_type: "text/html",
|
||||
subject: "Already rendered!")
|
||||
end
|
||||
end
|
||||
```
|
||||
|
@ -428,13 +518,21 @@ end
|
|||
Receiving Emails
|
||||
----------------
|
||||
|
||||
Receiving and parsing emails with Action Mailer can be a rather complex endeavor. Before your email reaches your Rails app, you would have had to configure your system to somehow forward emails to your app, which needs to be listening for that. So, to receive emails in your Rails app you'll need to:
|
||||
Receiving and parsing emails with Action Mailer can be a rather complex
|
||||
endeavor. Before your email reaches your Rails app, you would have had to
|
||||
configure your system to somehow forward emails to your app, which needs to be
|
||||
listening for that. So, to receive emails in your Rails app you'll need to:
|
||||
|
||||
* 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/bin/rails runner 'UserMailer.receive(STDIN.read)'`.
|
||||
* Configure your email server to forward emails from the address(es) you would
|
||||
like your app to receive to `/path/to/app/bin/rails 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:
|
||||
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
|
||||
|
@ -460,17 +558,23 @@ end
|
|||
Action Mailer Callbacks
|
||||
---------------------------
|
||||
|
||||
Action Mailer allows for you to specify a `before_action`, `after_action` and `around_action`.
|
||||
Action Mailer allows for you to specify a `before_action`, `after_action` and
|
||||
`around_action`.
|
||||
|
||||
* Filters can be specified with a block or a symbol to a method in the mailer class similar to controllers.
|
||||
* Filters can be specified with a block or a symbol to a method in the mailer
|
||||
class similar to controllers.
|
||||
|
||||
* You could use a `before_action` to prepopulate the mail object with defaults, delivery_method_options or insert default headers and attachments.
|
||||
* You could use a `before_action` to populate the mail object with defaults,
|
||||
delivery_method_options or insert default headers and attachments.
|
||||
|
||||
* You could use an `after_action` to do similar setup as a `before_action` but using instance variables set in your mailer action.
|
||||
* You could use an `after_action` to do similar setup as a `before_action` but
|
||||
using instance variables set in your mailer action.
|
||||
|
||||
```ruby
|
||||
class UserMailer < ActionMailer::Base
|
||||
after_action :set_delivery_options, :prevent_delivery_to_guests, :set_business_headers
|
||||
after_action :set_delivery_options,
|
||||
:prevent_delivery_to_guests,
|
||||
:set_business_headers
|
||||
|
||||
def feedback_message(business, user)
|
||||
@business = business
|
||||
|
@ -486,7 +590,8 @@ class UserMailer < ActionMailer::Base
|
|||
private
|
||||
|
||||
def set_delivery_options
|
||||
# You have access to the mail instance and @business and @user instance variables here
|
||||
# You have access to the mail instance,
|
||||
# @business and @user instance variables here
|
||||
if @business && @business.has_smtp_settings?
|
||||
mail.delivery_method.settings.merge!(@business.smtp_settings)
|
||||
end
|
||||
|
@ -511,12 +616,14 @@ end
|
|||
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.
|
||||
Action Mailer now just inherits from `AbstractController`, so you have access to
|
||||
the same generic helpers as you do in Action Controller.
|
||||
|
||||
Action Mailer Configuration
|
||||
---------------------------
|
||||
|
||||
The following configuration options are best made in one of the environment files (environment.rb, production.rb, etc...)
|
||||
The following configuration options are best made in one of the environment
|
||||
files (environment.rb, production.rb, etc...)
|
||||
|
||||
| Configuration | Description |
|
||||
|---------------|-------------|
|
||||
|
@ -529,9 +636,14 @@ The following configuration options are best made in one of the environment file
|
|||
|`deliveries`|Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.|
|
||||
|`default_options`|Allows you to set default values for the `mail` method options (`:from`, `:reply_to`, etc.).|
|
||||
|
||||
For a complete writeup of possible configurations see the
|
||||
[Action Mailer section](configuring.html#configuring-action-mailer) in
|
||||
our Configuring Rails Applications guide.
|
||||
|
||||
### Example Action Mailer Configuration
|
||||
|
||||
An example would be adding the following to your appropriate `config/environments/$RAILS_ENV.rb` file:
|
||||
An example would be adding the following to your appropriate
|
||||
`config/environments/$RAILS_ENV.rb` file:
|
||||
|
||||
```ruby
|
||||
config.action_mailer.delivery_method = :sendmail
|
||||
|
@ -542,19 +654,20 @@ config.action_mailer.delivery_method = :sendmail
|
|||
# }
|
||||
config.action_mailer.perform_deliveries = true
|
||||
config.action_mailer.raise_delivery_errors = true
|
||||
config.action_mailer.default_options = {from: 'no-replay@example.org'}
|
||||
config.action_mailer.default_options = {from: 'no-replay@example.com'}
|
||||
```
|
||||
|
||||
### Action Mailer Configuration for GMail
|
||||
### Action Mailer Configuration for Gmail
|
||||
|
||||
As Action Mailer now uses the Mail gem, this becomes as simple as adding to your `config/environments/$RAILS_ENV.rb` file:
|
||||
As Action Mailer now uses the Mail gem, this becomes as simple as adding to your
|
||||
`config/environments/$RAILS_ENV.rb` file:
|
||||
|
||||
```ruby
|
||||
config.action_mailer.delivery_method = :smtp
|
||||
config.action_mailer.smtp_settings = {
|
||||
address: 'smtp.gmail.com',
|
||||
port: 587,
|
||||
domain: 'baci.lindsaar.net',
|
||||
domain: 'example.com',
|
||||
user_name: '<username>',
|
||||
password: '<password>',
|
||||
authentication: 'plain',
|
||||
|
@ -569,7 +682,10 @@ You can find detailed instructions on how to test your mailers in our
|
|||
|
||||
Intercepting Emails
|
||||
-------------------
|
||||
There are situations where you need to edit an email before it's delivered. Fortunately Action Mailer provides hooks to intercept every email. You can register an interceptor to make modifications to mail messages right before they are handed to the delivery agents.
|
||||
There are situations where you need to edit an email before it's
|
||||
delivered. Fortunately Action Mailer provides hooks to intercept every
|
||||
email. You can register an interceptor to make modifications to mail messages
|
||||
right before they are handed to the delivery agents.
|
||||
|
||||
```ruby
|
||||
class SandboxEmailInterceptor
|
||||
|
@ -579,10 +695,15 @@ class SandboxEmailInterceptor
|
|||
end
|
||||
```
|
||||
|
||||
Before the interceptor can do its job you need to register it with the Action Mailer framework. You can do this in an initializer file `config/initializers/sandbox_email_interceptor.rb`
|
||||
Before the interceptor can do its job you need to register it with the Action
|
||||
Mailer framework. You can do this in an initializer file
|
||||
`config/initializers/sandbox_email_interceptor.rb`
|
||||
|
||||
```ruby
|
||||
ActionMailer::Base.register_interceptor(SandboxEmailInterceptor) if Rails.env.staging?
|
||||
```
|
||||
|
||||
NOTE: The example above uses a custom environment called "staging" for a production like server but for testing purposes. You can read [Creating Rails environments](./configuring.html#creating-rails-environments) for more information about custom Rails environments.
|
||||
NOTE: The example above uses a custom environment called "staging" for a
|
||||
production like server but for testing purposes. You can read
|
||||
[Creating Rails environments](./configuring.html#creating-rails-environments)
|
||||
for more information about custom Rails environments.
|
||||
|
|
|
@ -68,7 +68,6 @@
|
|||
-
|
||||
name: Action Mailer Basics
|
||||
url: action_mailer_basics.html
|
||||
work_in_progress: true
|
||||
description: This guide describes how to use Action Mailer to send and receive emails.
|
||||
-
|
||||
name: Testing Rails Applications
|
||||
|
|
Loading…
Reference in a new issue