actionmailer 3.0.4 → 7.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +219 -0
  3. data/MIT-LICENSE +1 -1
  4. data/README.rdoc +49 -55
  5. data/lib/action_mailer/base.rb +688 -387
  6. data/lib/action_mailer/callbacks.rb +31 -0
  7. data/lib/action_mailer/collector.rb +11 -9
  8. data/lib/action_mailer/delivery_methods.rb +35 -37
  9. data/lib/action_mailer/deprecator.rb +7 -0
  10. data/lib/action_mailer/form_builder.rb +37 -0
  11. data/lib/action_mailer/gem_version.rb +17 -0
  12. data/lib/action_mailer/inline_preview_interceptor.rb +59 -0
  13. data/lib/action_mailer/log_subscriber.rb +30 -8
  14. data/lib/action_mailer/mail_delivery_job.rb +48 -0
  15. data/lib/action_mailer/mail_helper.rb +59 -18
  16. data/lib/action_mailer/message_delivery.rb +156 -0
  17. data/lib/action_mailer/parameterized.rb +156 -0
  18. data/lib/action_mailer/preview.rb +166 -0
  19. data/lib/action_mailer/queued_delivery.rb +12 -0
  20. data/lib/action_mailer/railtie.rb +75 -7
  21. data/lib/action_mailer/rescuable.rb +33 -0
  22. data/lib/action_mailer/test_case.rb +75 -25
  23. data/lib/action_mailer/test_helper.rb +238 -15
  24. data/lib/action_mailer/version.rb +8 -7
  25. data/lib/action_mailer.rb +45 -18
  26. data/lib/rails/generators/mailer/USAGE +13 -8
  27. data/lib/rails/generators/mailer/mailer_generator.rb +26 -4
  28. data/lib/rails/generators/mailer/templates/application_mailer.rb.tt +6 -0
  29. data/lib/rails/generators/mailer/templates/mailer.rb.tt +17 -0
  30. metadata +175 -87
  31. data/CHANGELOG +0 -424
  32. data/lib/action_mailer/adv_attr_accessor.rb +0 -26
  33. data/lib/action_mailer/deprecated_api.rb +0 -147
  34. data/lib/action_mailer/old_api.rb +0 -259
  35. data/lib/action_mailer/tmail_compat.rb +0 -34
  36. data/lib/rails/generators/mailer/templates/mailer.rb +0 -16
@@ -1,36 +1,45 @@
1
- require 'mail'
2
- require 'action_mailer/tmail_compat'
3
- require 'action_mailer/collector'
4
- require 'active_support/core_ext/array/wrap'
5
- require 'active_support/core_ext/object/blank'
6
- require 'active_support/core_ext/proc'
7
- require 'action_mailer/log_subscriber'
8
-
9
- module ActionMailer #:nodoc:
1
+ # frozen_string_literal: true
2
+
3
+ require "mail"
4
+ require "action_mailer/collector"
5
+ require "active_support/core_ext/string/inflections"
6
+ require "active_support/core_ext/hash/except"
7
+ require "active_support/core_ext/module/anonymous"
8
+
9
+ require "action_mailer/log_subscriber"
10
+ require "action_mailer/rescuable"
11
+
12
+ module ActionMailer
13
+ # = Action Mailer \Base
14
+ #
10
15
  # Action Mailer allows you to send email from your application using a mailer model and views.
11
16
  #
12
- # = Mailer Models
17
+ # == Mailer Models
13
18
  #
14
19
  # To use Action Mailer, you need to create a mailer model.
15
20
  #
16
- # $ rails generate mailer Notifier
21
+ # $ bin/rails generate mailer Notifier
17
22
  #
18
- # The generated model inherits from <tt>ActionMailer::Base</tt>. Emails are defined by creating methods
19
- # within the model which are then used to set variables to be used in the mail template, to
20
- # change options on the mail, or to add attachments.
23
+ # The generated model inherits from <tt>ApplicationMailer</tt> which in turn
24
+ # inherits from +ActionMailer::Base+. A mailer model defines methods
25
+ # used to generate an email message. In these methods, you can set up variables to be used in
26
+ # the mailer views, options on the mail itself such as the <tt>:from</tt> address, and attachments.
21
27
  #
22
- # Examples:
28
+ # class ApplicationMailer < ActionMailer::Base
29
+ # default from: 'from@example.com'
30
+ # layout 'mailer'
31
+ # end
23
32
  #
24
- # class Notifier < ActionMailer::Base
25
- # default :from => 'no-reply@example.com',
26
- # :return_path => 'system@example.com'
33
+ # class NotifierMailer < ApplicationMailer
34
+ # default from: 'no-reply@example.com',
35
+ # return_path: 'system@example.com'
27
36
  #
28
- # def welcome(recipient)
29
- # @account = recipient
30
- # mail(:to => recipient.email_address_with_name,
31
- # :bcc => ["bcc@example.com", "Order Watcher <watcher@example.com>"])
32
- # end
33
- # end
37
+ # def welcome(recipient)
38
+ # @account = recipient
39
+ # mail(to: recipient.email_address_with_name,
40
+ # bcc: ["bcc@example.com", "Order Watcher <watcher@example.com>"])
41
+ # end
42
+ # end
34
43
  #
35
44
  # Within the mailer method, you have access to the following methods:
36
45
  #
@@ -41,73 +50,71 @@ module ActionMailer #:nodoc:
41
50
  # in the same manner as <tt>attachments[]=</tt>
42
51
  #
43
52
  # * <tt>headers[]=</tt> - Allows you to specify any header field in your email such
44
- # as <tt>headers['X-No-Spam'] = 'True'</tt>. Note, while most fields like <tt>To:</tt>
45
- # <tt>From:</tt> can only appear once in an email header, other fields like <tt>X-Anything</tt>
46
- # can appear multiple times. If you want to change a field that can appear multiple times,
47
- # you need to set it to nil first so that Mail knows you are replacing it and not adding
48
- # another field of the same name.
53
+ # as <tt>headers['X-No-Spam'] = 'True'</tt>. Note that declaring a header multiple times
54
+ # will add many fields of the same name. Read #headers doc for more information.
49
55
  #
50
56
  # * <tt>headers(hash)</tt> - Allows you to specify multiple headers in your email such
51
57
  # as <tt>headers({'X-No-Spam' => 'True', 'In-Reply-To' => '1234@message.id'})</tt>
52
58
  #
53
59
  # * <tt>mail</tt> - Allows you to specify email to be sent.
54
60
  #
55
- # The hash passed to the mail method allows you to specify any header that a Mail::Message
56
- # will accept (any valid Email header including optional fields).
61
+ # The hash passed to the mail method allows you to specify any header that a +Mail::Message+
62
+ # will accept (any valid email header including optional fields).
57
63
  #
58
- # The mail method, if not passed a block, will inspect your views and send all the views with
59
- # the same name as the method, so the above action would send the +welcome.text.plain.erb+ view
60
- # file as well as the +welcome.text.html.erb+ view file in a +multipart/alternative+ email.
64
+ # The +mail+ method, if not passed a block, will inspect your views and send all the views with
65
+ # the same name as the method, so the above action would send the +welcome.text.erb+ view
66
+ # file as well as the +welcome.html.erb+ view file in a +multipart/alternative+ email.
61
67
  #
62
68
  # If you want to explicitly render only certain templates, pass a block:
63
69
  #
64
- # mail(:to => user.email) do |format|
70
+ # mail(to: user.email) do |format|
65
71
  # format.text
66
72
  # format.html
67
73
  # end
68
74
  #
69
75
  # The block syntax is also useful in providing information specific to a part:
70
76
  #
71
- # mail(:to => user.email) do |format|
72
- # format.text(:content_transfer_encoding => "base64")
77
+ # mail(to: user.email) do |format|
78
+ # format.text(content_transfer_encoding: "base64")
73
79
  # format.html
74
80
  # end
75
81
  #
76
82
  # Or even to render a special view:
77
83
  #
78
- # mail(:to => user.email) do |format|
84
+ # mail(to: user.email) do |format|
79
85
  # format.text
80
86
  # format.html { render "some_other_template" }
81
87
  # end
82
88
  #
83
- # = Mailer views
89
+ # == Mailer views
84
90
  #
85
91
  # Like Action Controller, each mailer class has a corresponding view directory in which each
86
92
  # method of the class looks for a template with its name.
87
93
  #
88
- # To define a template to be used with a mailing, create an <tt>.erb</tt> file with the same
94
+ # To define a template to be used with a mailer, create an <tt>.erb</tt> file with the same
89
95
  # name as the method in your mailer model. For example, in the mailer defined above, the template at
90
- # <tt>app/views/notifier/signup_notification.text.plain.erb</tt> would be used to generate the email.
96
+ # <tt>app/views/notifier_mailer/welcome.text.erb</tt> would be used to generate the email.
91
97
  #
92
- # Variables defined in the model are accessible as instance variables in the view.
98
+ # Variables defined in the methods of your mailer model are accessible as instance variables in their
99
+ # corresponding view.
93
100
  #
94
101
  # Emails by default are sent in plain text, so a sample view for our model example might look like this:
95
102
  #
96
103
  # Hi <%= @account.name %>,
97
104
  # Thanks for joining our service! Please check back often.
98
105
  #
99
- # You can even use Action Pack helpers in these views. For example:
106
+ # You can even use Action View helpers in these views. For example:
100
107
  #
101
108
  # You got a new note!
102
- # <%= truncate(@note.body, 25) %>
109
+ # <%= truncate(@note.body, length: 25) %>
103
110
  #
104
- # If you need to access the subject, from or the recipients in the view, you can do that through message object:
111
+ # If you need to access the subject, from, or the recipients in the view, you can do that through message object:
105
112
  #
106
113
  # You got a new note from <%= message.from %>!
107
- # <%= truncate(@note.body, 25) %>
114
+ # <%= truncate(@note.body, length: 25) %>
108
115
  #
109
116
  #
110
- # = Generating URLs
117
+ # == Generating URLs
111
118
  #
112
119
  # URLs can be generated in mailer views using <tt>url_for</tt> or named routes. Unlike controllers from
113
120
  # Action Pack, the mailer instance doesn't have any context about the incoming request, so you'll need
@@ -115,50 +122,62 @@ module ActionMailer #:nodoc:
115
122
  #
116
123
  # When using <tt>url_for</tt> you'll need to provide the <tt>:host</tt>, <tt>:controller</tt>, and <tt>:action</tt>:
117
124
  #
118
- # <%= url_for(:host => "example.com", :controller => "welcome", :action => "greeting") %>
125
+ # <%= url_for(host: "example.com", controller: "welcome", action: "greeting") %>
119
126
  #
120
127
  # When using named routes you only need to supply the <tt>:host</tt>:
121
128
  #
122
- # <%= users_url(:host => "example.com") %>
129
+ # <%= users_url(host: "example.com") %>
123
130
  #
124
- # You want to avoid using the <tt>name_of_route_path</tt> form of named routes because it doesn't
125
- # make sense to generate relative URLs in email messages.
131
+ # You should use the <tt>named_route_url</tt> style (which generates absolute URLs) and avoid using the
132
+ # <tt>named_route_path</tt> style (which generates relative URLs), since clients reading the mail will
133
+ # have no concept of a current URL from which to determine a relative path.
126
134
  #
127
135
  # It is also possible to set a default host that will be used in all mailers by setting the <tt>:host</tt>
128
136
  # option as a configuration option in <tt>config/application.rb</tt>:
129
137
  #
130
- # config.action_mailer.default_url_options = { :host => "example.com" }
138
+ # config.action_mailer.default_url_options = { host: "example.com" }
139
+ #
140
+ # You can also define a <tt>default_url_options</tt> method on individual mailers to override these
141
+ # default settings per-mailer.
142
+ #
143
+ # By default when <tt>config.force_ssl</tt> is +true+, URLs generated for hosts will use the HTTPS protocol.
131
144
  #
132
- # Setting <tt>ActionMailer::Base.default_url_options</tt> directly is now deprecated, use the configuration
133
- # option mentioned above to set the default host.
145
+ # == Sending mail
134
146
  #
135
- # If you do decide to set a default <tt>:host</tt> for your mailers you want to use the
136
- # <tt>:only_path => false</tt> option when using <tt>url_for</tt>. This will ensure that absolute URLs are
137
- # generated because the <tt>url_for</tt> view helper will, by default, generate relative URLs when a
138
- # <tt>:host</tt> option isn't explicitly provided.
147
+ # Once a mailer action and template are defined, you can deliver your message or defer its creation and
148
+ # delivery for later:
139
149
  #
140
- # = Sending mail
150
+ # NotifierMailer.welcome(User.first).deliver_now # sends the email
151
+ # mail = NotifierMailer.welcome(User.first) # => an ActionMailer::MessageDelivery object
152
+ # mail.deliver_now # generates and sends the email now
141
153
  #
142
- # Once a mailer action and template are defined, you can deliver your message or create it and save it
143
- # for delivery later:
154
+ # The ActionMailer::MessageDelivery class is a wrapper around a delegate that will call
155
+ # your method to generate the mail. If you want direct access to the delegator, or +Mail::Message+,
156
+ # you can call the <tt>message</tt> method on the ActionMailer::MessageDelivery object.
144
157
  #
145
- # Notifier.welcome(david).deliver # sends the email
146
- # mail = Notifier.welcome(david) # => a Mail::Message object
147
- # mail.deliver # sends the email
158
+ # NotifierMailer.welcome(User.first).message # => a Mail::Message object
159
+ #
160
+ # Action Mailer is nicely integrated with Active Job so you can generate and send emails in the background
161
+ # (example: outside of the request-response cycle, so the user doesn't have to wait on it):
162
+ #
163
+ # NotifierMailer.welcome(User.first).deliver_later # enqueue the email sending to Active Job
164
+ #
165
+ # Note that <tt>deliver_later</tt> will execute your method from the background job.
148
166
  #
149
167
  # You never instantiate your mailer class. Rather, you just call the method you defined on the class itself.
168
+ # All instance methods are expected to return a message object to be sent.
150
169
  #
151
- # = Multipart Emails
170
+ # == Multipart Emails
152
171
  #
153
- # Multipart messages can also be used implicitly because Action Mailer will automatically
154
- # detect and use multipart templates, where each template is named after the name of the action, followed
155
- # by the content type. Each such detected template will be added as separate part to the message.
172
+ # Multipart messages can also be used implicitly because Action Mailer will automatically detect and use
173
+ # multipart templates, where each template is named after the name of the action, followed by the content
174
+ # type. Each such detected template will be added to the message, as a separate part.
156
175
  #
157
176
  # For example, if the following templates exist:
158
- # * signup_notification.text.plain.erb
159
- # * signup_notification.text.html.erb
160
- # * signup_notification.text.xml.builder
161
- # * signup_notification.text.yaml.erb
177
+ # * signup_notification.text.erb
178
+ # * signup_notification.html.erb
179
+ # * signup_notification.xml.builder
180
+ # * signup_notification.yml.erb
162
181
  #
163
182
  # Each would be rendered and added as a separate part to the message, with the corresponding content
164
183
  # type. The content type for the entire message is automatically set to <tt>multipart/alternative</tt>,
@@ -169,32 +188,55 @@ module ActionMailer #:nodoc:
169
188
  # This means that you'll have to manually add each part to the email and set the content type of the email
170
189
  # to <tt>multipart/alternative</tt>.
171
190
  #
172
- # = Attachments
191
+ # == Attachments
173
192
  #
174
193
  # Sending attachment in emails is easy:
175
194
  #
176
- # class ApplicationMailer < ActionMailer::Base
195
+ # class NotifierMailer < ApplicationMailer
177
196
  # def welcome(recipient)
178
197
  # attachments['free_book.pdf'] = File.read('path/to/file.pdf')
179
- # mail(:to => recipient, :subject => "New account information")
198
+ # mail(to: recipient, subject: "New account information")
180
199
  # end
181
200
  # end
182
201
  #
183
- # Which will (if it had both a <tt>welcome.text.plain.erb</tt> and <tt>welcome.text.html.erb</tt>
202
+ # Which will (if it had both a <tt>welcome.text.erb</tt> and <tt>welcome.html.erb</tt>
184
203
  # template in the view directory), send a complete <tt>multipart/mixed</tt> email with two parts,
185
204
  # the first part being a <tt>multipart/alternative</tt> with the text and HTML email parts inside,
186
205
  # and the second being a <tt>application/pdf</tt> with a Base64 encoded copy of the file.pdf book
187
206
  # with the filename +free_book.pdf+.
188
207
  #
189
- # = Inline Attachments
208
+ # If you need to send attachments with no content, you need to create an empty view for it,
209
+ # or add an empty body parameter like this:
210
+ #
211
+ # class NotifierMailer < ApplicationMailer
212
+ # def welcome(recipient)
213
+ # attachments['free_book.pdf'] = File.read('path/to/file.pdf')
214
+ # mail(to: recipient, subject: "New account information", body: "")
215
+ # end
216
+ # end
217
+ #
218
+ # You can also send attachments with HTML template, in this case you need to add body, attachments,
219
+ # and custom content type like this:
220
+ #
221
+ # class NotifierMailer < ApplicationMailer
222
+ # def welcome(recipient)
223
+ # attachments["free_book.pdf"] = File.read("path/to/file.pdf")
224
+ # mail(to: recipient,
225
+ # subject: "New account information",
226
+ # content_type: "text/html",
227
+ # body: "<html><body>Hello there</body></html>")
228
+ # end
229
+ # end
230
+ #
231
+ # == Inline Attachments
190
232
  #
191
233
  # You can also specify that a file should be displayed inline with other HTML. This is useful
192
234
  # if you want to display a corporate logo or a photo.
193
235
  #
194
- # class ApplicationMailer < ActionMailer::Base
236
+ # class NotifierMailer < ApplicationMailer
195
237
  # def welcome(recipient)
196
238
  # attachments.inline['photo.png'] = File.read('path/to/photo.png')
197
- # mail(:to => recipient, :subject => "Here is what we look like")
239
+ # mail(to: recipient, subject: "Here is what we look like")
198
240
  # end
199
241
  # end
200
242
  #
@@ -210,76 +252,174 @@ module ActionMailer #:nodoc:
210
252
  #
211
253
  # <h1>Please Don't Cringe</h1>
212
254
  #
213
- # <%= image_tag attachments['photo.png'].url, :alt => 'Our Photo', :class => 'photo' -%>
255
+ # <%= image_tag attachments['photo.png'].url, alt: 'Our Photo', class: 'photo' -%>
214
256
  #
215
- # = Observing and Intercepting Mails
257
+ # == Observing and Intercepting Mails
216
258
  #
217
- # Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to
218
- # register objects that are called during the mail delivery life cycle.
259
+ # Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to
260
+ # register classes that are called during the mail delivery life cycle.
219
261
  #
220
- # An observer object must implement the <tt>:delivered_email(message)</tt> method which will be
262
+ # An observer class must implement the <tt>:delivered_email(message)</tt> method which will be
221
263
  # called once for every email sent after the email has been sent.
222
264
  #
223
- # An interceptor object must implement the <tt>:delivering_email(message)</tt> method which will be
265
+ # An interceptor class must implement the <tt>:delivering_email(message)</tt> method which will be
224
266
  # called before the email is sent, allowing you to make modifications to the email before it hits
225
- # the delivery agents. Your object should make and needed modifications directly to the passed
226
- # in Mail::Message instance.
267
+ # the delivery agents. Your class should make any needed modifications directly to the passed
268
+ # in +Mail::Message+ instance.
227
269
  #
228
- # = Default Hash
270
+ # == Default \Hash
229
271
  #
230
272
  # Action Mailer provides some intelligent defaults for your emails, these are usually specified in a
231
273
  # default method inside the class definition:
232
274
  #
233
- # class Notifier < ActionMailer::Base
234
- # default :sender => 'system@example.com'
275
+ # class NotifierMailer < ApplicationMailer
276
+ # default sender: 'system@example.com'
235
277
  # end
236
278
  #
237
- # You can pass in any header value that a <tt>Mail::Message</tt> accepts. Out of the box,
238
- # <tt>ActionMailer::Base</tt> sets the following:
279
+ # You can pass in any header value that a +Mail::Message+ accepts. Out of the box,
280
+ # +ActionMailer::Base+ sets the following:
239
281
  #
240
- # * <tt>:mime_version => "1.0"</tt>
241
- # * <tt>:charset => "UTF-8",</tt>
242
- # * <tt>:content_type => "text/plain",</tt>
243
- # * <tt>:parts_order => [ "text/plain", "text/enriched", "text/html" ]</tt>
282
+ # * <tt>mime_version: "1.0"</tt>
283
+ # * <tt>charset: "UTF-8"</tt>
284
+ # * <tt>content_type: "text/plain"</tt>
285
+ # * <tt>parts_order: [ "text/plain", "text/enriched", "text/html" ]</tt>
244
286
  #
245
- # <tt>parts_order</tt> and <tt>charset</tt> are not actually valid <tt>Mail::Message</tt> header fields,
287
+ # <tt>parts_order</tt> and <tt>charset</tt> are not actually valid +Mail::Message+ header fields,
246
288
  # but Action Mailer translates them appropriately and sets the correct values.
247
289
  #
248
290
  # As you can pass in any header, you need to either quote the header as a string, or pass it in as
249
- # an underscorised symbol, so the following will work:
291
+ # an underscored symbol, so the following will work:
250
292
  #
251
- # class Notifier < ActionMailer::Base
293
+ # class NotifierMailer < ApplicationMailer
252
294
  # default 'Content-Transfer-Encoding' => '7bit',
253
- # :content_description => 'This is a description'
295
+ # content_description: 'This is a description'
254
296
  # end
255
297
  #
256
- # Finally, Action Mailer also supports passing <tt>Proc</tt> objects into the default hash, so you
257
- # can define methods that evaluate as the message is being generated:
298
+ # Finally, Action Mailer also supports passing <tt>Proc</tt> and <tt>Lambda</tt> objects into the default hash,
299
+ # so you can define methods that evaluate as the message is being generated:
258
300
  #
259
- # class Notifier < ActionMailer::Base
260
- # default 'X-Special-Header' => Proc.new { my_method }
301
+ # class NotifierMailer < ApplicationMailer
302
+ # default 'X-Special-Header' => Proc.new { my_method }, to: -> { @inviter.email_address }
261
303
  #
262
304
  # private
263
- #
264
305
  # def my_method
265
306
  # 'some complex call'
266
307
  # end
267
308
  # end
268
309
  #
269
- # Note that the proc is evaluated right at the start of the mail message generation, so if you
270
- # set something in the defaults using a proc, and then set the same thing inside of your
271
- # mailer method, it will get over written by the mailer method.
310
+ # Note that the proc/lambda is evaluated right at the start of the mail message generation, so if you
311
+ # set something in the default hash using a proc, and then set the same thing inside of your
312
+ # mailer method, it will get overwritten by the mailer method.
313
+ #
314
+ # It is also possible to set these default options that will be used in all mailers through
315
+ # the <tt>default_options=</tt> configuration in <tt>config/application.rb</tt>:
316
+ #
317
+ # config.action_mailer.default_options = { from: "no-reply@example.org" }
318
+ #
319
+ # == \Callbacks
320
+ #
321
+ # You can specify callbacks using <tt>before_action</tt> and <tt>after_action</tt> for configuring your messages,
322
+ # and using <tt>before_deliver</tt> and <tt>after_deliver</tt> for wrapping the delivery process.
323
+ # For example, when you want to add default inline attachments and log delivery for all messages
324
+ # sent out by a certain mailer class:
325
+ #
326
+ # class NotifierMailer < ApplicationMailer
327
+ # before_action :add_inline_attachment!
328
+ # after_deliver :log_delivery
329
+ #
330
+ # def welcome
331
+ # mail
332
+ # end
333
+ #
334
+ # private
335
+ # def add_inline_attachment!
336
+ # attachments.inline["footer.jpg"] = File.read('/path/to/filename.jpg')
337
+ # end
338
+ #
339
+ # def log_delivery
340
+ # Rails.logger.info "Sent email with message id '#{message.message_id}' at #{Time.current}."
341
+ # end
342
+ # end
343
+ #
344
+ # Action callbacks in Action Mailer are implemented using
345
+ # AbstractController::Callbacks, so you can define and configure
346
+ # callbacks in the same manner that you would use callbacks in classes that
347
+ # inherit from ActionController::Base.
348
+ #
349
+ # Note that unless you have a specific reason to do so, you should prefer
350
+ # using <tt>before_action</tt> rather than <tt>after_action</tt> in your
351
+ # Action Mailer classes so that headers are parsed properly.
352
+ #
353
+ # == Rescuing Errors
354
+ #
355
+ # +rescue+ blocks inside of a mailer method cannot rescue errors that occur
356
+ # outside of rendering -- for example, record deserialization errors in a
357
+ # background job, or errors from a third-party mail delivery service.
358
+ #
359
+ # To rescue errors that occur during any part of the mailing process, use
360
+ # {rescue_from}[rdoc-ref:ActiveSupport::Rescuable::ClassMethods#rescue_from]:
361
+ #
362
+ # class NotifierMailer < ApplicationMailer
363
+ # rescue_from ActiveJob::DeserializationError do
364
+ # # ...
365
+ # end
366
+ #
367
+ # rescue_from "SomeThirdPartyService::ApiError" do
368
+ # # ...
369
+ # end
370
+ #
371
+ # def notify(recipient)
372
+ # mail(to: recipient, subject: "Notification")
373
+ # end
374
+ # end
375
+ #
376
+ # == Previewing emails
377
+ #
378
+ # You can preview your email templates visually by adding a mailer preview file to the
379
+ # <tt>ActionMailer::Base.preview_paths</tt>. Since most emails do something interesting
380
+ # with database data, you'll need to write some scenarios to load messages with fake data:
381
+ #
382
+ # class NotifierMailerPreview < ActionMailer::Preview
383
+ # def welcome
384
+ # NotifierMailer.welcome(User.first)
385
+ # end
386
+ # end
387
+ #
388
+ # Methods must return a +Mail::Message+ object which can be generated by calling the mailer
389
+ # method without the additional <tt>deliver_now</tt> / <tt>deliver_later</tt>. The location of the
390
+ # mailer preview directories can be configured using the <tt>preview_paths</tt> option which has a default
391
+ # of <tt>test/mailers/previews</tt>:
392
+ #
393
+ # config.action_mailer.preview_paths << "#{Rails.root}/lib/mailer_previews"
394
+ #
395
+ # An overview of all previews is accessible at <tt>http://localhost:3000/rails/mailers</tt>
396
+ # on a running development server instance.
397
+ #
398
+ # Previews can also be intercepted in a similar manner as deliveries can be by registering
399
+ # a preview interceptor that has a <tt>previewing_email</tt> method:
400
+ #
401
+ # class CssInlineStyler
402
+ # def self.previewing_email(message)
403
+ # # inline CSS styles
404
+ # end
405
+ # end
406
+ #
407
+ # config.action_mailer.preview_interceptors :css_inline_styler
272
408
  #
273
- # = Configuration options
409
+ # Note that interceptors need to be registered both with <tt>register_interceptor</tt>
410
+ # and <tt>register_preview_interceptor</tt> if they should operate on both sending and
411
+ # previewing emails.
412
+ #
413
+ # == Configuration options
274
414
  #
275
415
  # These options are specified on the class level, like
276
416
  # <tt>ActionMailer::Base.raise_delivery_errors = true</tt>
277
417
  #
278
- # * <tt>default</tt> - You can pass this in at a class level as well as within the class itself as
418
+ # * <tt>default_options</tt> - You can pass this in at a class level as well as within the class itself as
279
419
  # per the above section.
280
420
  #
281
421
  # * <tt>logger</tt> - the logger is used for generating information on the mailing run if available.
282
- # Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
422
+ # Can be set to +nil+ for no logging. Compatible with both Ruby's own +Logger+ and Log4r loggers.
283
423
  #
284
424
  # * <tt>smtp_settings</tt> - Allows detailed configuration for <tt>:smtp</tt> delivery method:
285
425
  # * <tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default
@@ -290,15 +430,24 @@ module ActionMailer #:nodoc:
290
430
  # * <tt>:password</tt> - If your mail server requires authentication, set the password in this setting.
291
431
  # * <tt>:authentication</tt> - If your mail server requires authentication, you need to specify the
292
432
  # authentication type here.
293
- # This is a symbol and one of <tt>:plain</tt> (will send the password in the clear), <tt>:login</tt> (will
294
- # send password BASE64 encoded) or <tt>:cram_md5</tt> (combines a Challenge/Response mechanism to exchange
433
+ # This is a symbol and one of <tt>:plain</tt> (will send the password Base64 encoded), <tt>:login</tt> (will
434
+ # send the password Base64 encoded) or <tt>:cram_md5</tt> (combines a Challenge/Response mechanism to exchange
295
435
  # information and a cryptographic Message Digest 5 algorithm to hash important information)
296
- # * <tt>:enable_starttls_auto</tt> - When set to true, detects if STARTTLS is enabled in your SMTP server
297
- # and starts to use it.
436
+ # * <tt>:enable_starttls</tt> - Use STARTTLS when connecting to your SMTP server and fail if unsupported. Defaults
437
+ # to <tt>false</tt>. Requires at least version 2.7 of the Mail gem.
438
+ # * <tt>:enable_starttls_auto</tt> - Detects if STARTTLS is enabled in your SMTP server and starts
439
+ # to use it. Defaults to <tt>true</tt>.
440
+ # * <tt>:openssl_verify_mode</tt> - When using TLS, you can set how OpenSSL checks the certificate. This is
441
+ # really useful if you need to validate a self-signed and/or a wildcard certificate. You can use the name
442
+ # of an OpenSSL verify constant (<tt>'none'</tt> or <tt>'peer'</tt>) or directly the constant
443
+ # (+OpenSSL::SSL::VERIFY_NONE+ or +OpenSSL::SSL::VERIFY_PEER+).
444
+ # * <tt>:ssl/:tls</tt> Enables the SMTP connection to use SMTP/TLS (SMTPS: SMTP over direct TLS connection)
445
+ # * <tt>:open_timeout</tt> Number of seconds to wait while attempting to open a connection.
446
+ # * <tt>:read_timeout</tt> Number of seconds to wait until timing-out a read(2) call.
298
447
  #
299
448
  # * <tt>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method.
300
449
  # * <tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.
301
- # * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt> with <tt>-f sender@addres</tt>
450
+ # * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>%w[ -i ]</tt> with <tt>-f sender@address</tt>
302
451
  # added automatically before the message is sent.
303
452
  #
304
453
  # * <tt>file_settings</tt> - Allows you to override options for the <tt>:file</tt> delivery method.
@@ -309,191 +458,273 @@ module ActionMailer #:nodoc:
309
458
  #
310
459
  # * <tt>delivery_method</tt> - Defines a delivery method. Possible values are <tt>:smtp</tt> (default),
311
460
  # <tt>:sendmail</tt>, <tt>:test</tt>, and <tt>:file</tt>. Or you may provide a custom delivery method
312
- # object eg. MyOwnDeliveryMethodClass.new. See the Mail gem documentation on the interface you need to
461
+ # object e.g. +MyOwnDeliveryMethodClass+. See the Mail gem documentation on the interface you need to
313
462
  # implement for a custom delivery agent.
314
463
  #
315
464
  # * <tt>perform_deliveries</tt> - Determines whether emails are actually sent from Action Mailer when you
316
- # call <tt>.deliver</tt> on an mail message or on an Action Mailer method. This is on by default but can
465
+ # call <tt>.deliver</tt> on an email message or on an Action Mailer method. This is on by default but can
317
466
  # be turned off to aid in functional testing.
318
467
  #
319
468
  # * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with
320
469
  # <tt>delivery_method :test</tt>. Most useful for unit and functional testing.
321
470
  #
322
- # * <tt>default_charset</tt> - This is now deprecated, use the +default+ method above to
323
- # set the default +:charset+.
324
- #
325
- # * <tt>default_content_type</tt> - This is now deprecated, use the +default+ method above
326
- # to set the default +:content_type+.
327
- #
328
- # * <tt>default_mime_version</tt> - This is now deprecated, use the +default+ method above
329
- # to set the default +:mime_version+.
471
+ # * <tt>delivery_job</tt> - The job class used with <tt>deliver_later</tt>. Mailers can set this to use a
472
+ # custom delivery job. Defaults to +ActionMailer::MailDeliveryJob+.
330
473
  #
331
- # * <tt>default_implicit_parts_order</tt> - This is now deprecated, use the +default+ method above
332
- # to set the default +:parts_order+. Parts Order is used when a message is built implicitly
333
- # (i.e. multiple parts are assembled from templates which specify the content type in their
334
- # filenames) this variable controls how the parts are ordered.
474
+ # * <tt>deliver_later_queue_name</tt> - The queue name used by <tt>deliver_later</tt> with the default
475
+ # <tt>delivery_job</tt>. Mailers can set this to use a custom queue name.
335
476
  class Base < AbstractController::Base
477
+ include Callbacks
336
478
  include DeliveryMethods
479
+ include QueuedDelivery
480
+ include Rescuable
481
+ include Parameterized
482
+ include Previews
483
+ include FormBuilder
484
+
337
485
  abstract!
338
486
 
339
- include AbstractController::Logger
340
487
  include AbstractController::Rendering
341
- include AbstractController::Layouts
488
+
489
+ include AbstractController::Logger
342
490
  include AbstractController::Helpers
343
491
  include AbstractController::Translation
344
492
  include AbstractController::AssetPaths
493
+ include AbstractController::Callbacks
494
+ include AbstractController::Caching
345
495
 
346
- helper ActionMailer::MailHelper
347
-
348
- include ActionMailer::OldApi
349
- include ActionMailer::DeprecatedApi
496
+ include ActionView::Layouts
350
497
 
351
- delegate :register_observer, :to => Mail
352
- delegate :register_interceptor, :to => Mail
498
+ PROTECTED_IVARS = AbstractController::Rendering::DEFAULT_PROTECTED_INSTANCE_VARIABLES + [:@_action_has_layout]
353
499
 
354
- private_class_method :new #:nodoc:
500
+ helper ActionMailer::MailHelper
355
501
 
356
- class_attribute :default_params
357
- self.default_params = {
358
- :mime_version => "1.0",
359
- :charset => "UTF-8",
360
- :content_type => "text/plain",
361
- :parts_order => [ "text/plain", "text/enriched", "text/html" ]
502
+ class_attribute :default_params, default: {
503
+ mime_version: "1.0",
504
+ charset: "UTF-8",
505
+ content_type: "text/plain",
506
+ parts_order: [ "text/plain", "text/enriched", "text/html" ]
362
507
  }.freeze
363
508
 
364
509
  class << self
510
+ # Register one or more Observers which will be notified when mail is delivered.
511
+ def register_observers(*observers)
512
+ observers.flatten.compact.each { |observer| register_observer(observer) }
513
+ end
514
+
515
+ # Unregister one or more previously registered Observers.
516
+ def unregister_observers(*observers)
517
+ observers.flatten.compact.each { |observer| unregister_observer(observer) }
518
+ end
519
+
520
+ # Register one or more Interceptors which will be called before mail is sent.
521
+ def register_interceptors(*interceptors)
522
+ interceptors.flatten.compact.each { |interceptor| register_interceptor(interceptor) }
523
+ end
524
+
525
+ # Unregister one or more previously registered Interceptors.
526
+ def unregister_interceptors(*interceptors)
527
+ interceptors.flatten.compact.each { |interceptor| unregister_interceptor(interceptor) }
528
+ end
529
+
530
+ # Register an Observer which will be notified when mail is delivered.
531
+ # Either a class, string, or symbol can be passed in as the Observer.
532
+ # If a string or symbol is passed in it will be camelized and constantized.
533
+ def register_observer(observer)
534
+ Mail.register_observer(observer_class_for(observer))
535
+ end
536
+
537
+ # Unregister a previously registered Observer.
538
+ # Either a class, string, or symbol can be passed in as the Observer.
539
+ # If a string or symbol is passed in it will be camelized and constantized.
540
+ def unregister_observer(observer)
541
+ Mail.unregister_observer(observer_class_for(observer))
542
+ end
543
+
544
+ # Register an Interceptor which will be called before mail is sent.
545
+ # Either a class, string, or symbol can be passed in as the Interceptor.
546
+ # If a string or symbol is passed in it will be camelized and constantized.
547
+ def register_interceptor(interceptor)
548
+ Mail.register_interceptor(observer_class_for(interceptor))
549
+ end
365
550
 
551
+ # Unregister a previously registered Interceptor.
552
+ # Either a class, string, or symbol can be passed in as the Interceptor.
553
+ # If a string or symbol is passed in it will be camelized and constantized.
554
+ def unregister_interceptor(interceptor)
555
+ Mail.unregister_interceptor(observer_class_for(interceptor))
556
+ end
557
+
558
+ def observer_class_for(value) # :nodoc:
559
+ case value
560
+ when String, Symbol
561
+ value.to_s.camelize.constantize
562
+ else
563
+ value
564
+ end
565
+ end
566
+ private :observer_class_for
567
+
568
+ # Returns the name of the current mailer. This method is also being used as a path for a view lookup.
569
+ # If this is an anonymous mailer, this method will return +anonymous+ instead.
366
570
  def mailer_name
367
- @mailer_name ||= name.underscore
571
+ @mailer_name ||= anonymous? ? "anonymous" : name.underscore
368
572
  end
573
+ # Allows to set the name of current mailer.
369
574
  attr_writer :mailer_name
370
575
  alias :controller_path :mailer_name
371
576
 
577
+ # Sets the defaults through app configuration:
578
+ #
579
+ # config.action_mailer.default(from: "no-reply@example.org")
580
+ #
581
+ # Aliased by ::default_options=
372
582
  def default(value = nil)
373
583
  self.default_params = default_params.merge(value).freeze if value
374
584
  default_params
375
585
  end
376
-
377
- # Receives a raw email, parses it into an email object, decodes it,
378
- # instantiates a new mailer, and passes the email object to the mailer
379
- # object's +receive+ method. If you want your mailer to be able to
380
- # process incoming messages, you'll need to implement a +receive+
381
- # method that accepts the raw email string as a parameter:
586
+ # Allows to set defaults through app configuration:
382
587
  #
383
- # class MyMailer < ActionMailer::Base
384
- # def receive(mail)
385
- # ...
386
- # end
387
- # end
388
- def receive(raw_mail)
389
- ActiveSupport::Notifications.instrument("receive.action_mailer") do |payload|
390
- mail = Mail.new(raw_mail)
391
- set_payload_for_mail(payload, mail)
392
- new.receive(mail)
393
- end
394
- end
588
+ # config.action_mailer.default_options = { from: "no-reply@example.org" }
589
+ alias :default_options= :default
395
590
 
396
- # Wraps an email delivery inside of Active Support Notifications instrumentation. This
397
- # method is actually called by the <tt>Mail::Message</tt> object itself through a callback
398
- # when you call <tt>:deliver</tt> on the Mail::Message, calling +deliver_mail+ directly
399
- # and passing a Mail::Message will do nothing except tell the logger you sent the email.
400
- def deliver_mail(mail) #:nodoc:
591
+ # Wraps an email delivery inside of ActiveSupport::Notifications instrumentation.
592
+ #
593
+ # This method is actually called by the +Mail::Message+ object itself
594
+ # through a callback when you call <tt>:deliver</tt> on the +Mail::Message+,
595
+ # calling +deliver_mail+ directly and passing a +Mail::Message+ will do
596
+ # nothing except tell the logger you sent the email.
597
+ def deliver_mail(mail) # :nodoc:
401
598
  ActiveSupport::Notifications.instrument("deliver.action_mailer") do |payload|
402
- self.set_payload_for_mail(payload, mail)
599
+ set_payload_for_mail(payload, mail)
403
600
  yield # Let Mail do the delivery actions
404
601
  end
405
602
  end
406
603
 
407
- def respond_to?(method, *args) #:nodoc:
408
- super || action_methods.include?(method.to_s)
604
+ # Returns an email in the format "Name <email@example.com>".
605
+ #
606
+ # If the name is a blank string, it returns just the address.
607
+ def email_address_with_name(address, name)
608
+ Mail::Address.new.tap do |builder|
609
+ builder.address = address
610
+ builder.display_name = name.presence
611
+ end.to_s
409
612
  end
410
613
 
411
- protected
412
-
413
- def set_payload_for_mail(payload, mail) #:nodoc:
414
- payload[:mailer] = self.name
415
- payload[:message_id] = mail.message_id
416
- payload[:subject] = mail.subject
417
- payload[:to] = mail.to
418
- payload[:from] = mail.from
419
- payload[:bcc] = mail.bcc if mail.bcc.present?
420
- payload[:cc] = mail.cc if mail.cc.present?
421
- payload[:date] = mail.date
422
- payload[:mail] = mail.encoded
614
+ private
615
+ def set_payload_for_mail(payload, mail)
616
+ payload[:mail] = mail.encoded
617
+ payload[:mailer] = name
618
+ payload[:message_id] = mail.message_id
619
+ payload[:subject] = mail.subject
620
+ payload[:to] = mail.to
621
+ payload[:from] = mail.from
622
+ payload[:bcc] = mail.bcc if mail.bcc.present?
623
+ payload[:cc] = mail.cc if mail.cc.present?
624
+ payload[:date] = mail.date
625
+ payload[:perform_deliveries] = mail.perform_deliveries
423
626
  end
424
627
 
425
- def method_missing(method, *args) #:nodoc:
426
- if action_methods.include?(method.to_s)
427
- new(method, *args).message
628
+ def method_missing(method_name, *args)
629
+ if action_methods.include?(method_name.to_s)
630
+ MessageDelivery.new(self, method_name, *args)
428
631
  else
429
632
  super
430
633
  end
431
634
  end
635
+ ruby2_keywords(:method_missing)
636
+
637
+ def respond_to_missing?(method, include_all = false)
638
+ action_methods.include?(method.to_s) || super
639
+ end
432
640
  end
433
641
 
434
642
  attr_internal :message
435
643
 
436
- # Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer
437
- # will be initialized according to the named method. If not, the mailer will
438
- # remain uninitialized (useful when you only need to invoke the "receive"
439
- # method, for instance).
440
- def initialize(method_name=nil, *args)
644
+ def initialize
441
645
  super()
646
+ @_mail_was_called = false
442
647
  @_message = Mail.new
443
- process(method_name, *args) if method_name
444
648
  end
445
649
 
446
- def process(*args) #:nodoc:
447
- lookup_context.skip_default_locale!
448
- super
449
- end
650
+ def process(method_name, *args) # :nodoc:
651
+ payload = {
652
+ mailer: self.class.name,
653
+ action: method_name,
654
+ args: args
655
+ }
450
656
 
451
- class DeprecatedHeaderProxy < ActiveSupport::BasicObject
452
- def initialize(message)
453
- @message = message
657
+ ActiveSupport::Notifications.instrument("process.action_mailer", payload) do
658
+ super
659
+ @_message = NullMail.new unless @_mail_was_called
454
660
  end
661
+ end
662
+ ruby2_keywords(:process)
455
663
 
456
- def []=(key, value)
457
- unless value.is_a?(::String)
458
- ::ActiveSupport::Deprecation.warn("Using a non-String object for a header's value is deprecated. " \
459
- "You specified #{value.inspect} (a #{value.class}) for #{key}", caller)
460
-
461
- value = value.to_s
462
- end
664
+ class NullMail # :nodoc:
665
+ def body; "" end
666
+ def header; {} end
463
667
 
464
- @message[key] = value
668
+ def respond_to?(string, include_all = false)
669
+ true
465
670
  end
466
671
 
467
- def headers(hash = {})
468
- hash.each_pair do |k,v|
469
- self[k] = v
470
- end
672
+ def method_missing(*args)
673
+ nil
471
674
  end
675
+ end
472
676
 
473
- def method_missing(meth, *args, &block)
474
- @message.send(meth, *args, &block)
475
- end
677
+ # Returns the name of the mailer object.
678
+ def mailer_name
679
+ self.class.mailer_name
476
680
  end
477
681
 
478
- # Allows you to pass random and unusual headers to the new +Mail::Message+ object
479
- # which will add them to itself.
682
+ # Returns an email in the format "Name <email@example.com>".
683
+ #
684
+ # If the name is a blank string, it returns just the address.
685
+ def email_address_with_name(address, name)
686
+ self.class.email_address_with_name(address, name)
687
+ end
688
+
689
+ # Allows you to pass random and unusual headers to the new +Mail::Message+
690
+ # object which will add them to itself.
480
691
  #
481
692
  # headers['X-Special-Domain-Specific-Header'] = "SecretValue"
482
693
  #
483
- # You can also pass a hash into headers of header field names and values, which
484
- # will then be set on the Mail::Message object:
694
+ # You can also pass a hash into headers of header field names and values,
695
+ # which will then be set on the +Mail::Message+ object:
485
696
  #
486
697
  # headers 'X-Special-Domain-Specific-Header' => "SecretValue",
487
698
  # 'In-Reply-To' => incoming.message_id
488
699
  #
489
- # The resulting Mail::Message will have the following in it's header:
700
+ # The resulting +Mail::Message+ will have the following in its header:
490
701
  #
491
702
  # X-Special-Domain-Specific-Header: SecretValue
492
- def headers(args=nil)
703
+ #
704
+ # Note about replacing already defined headers:
705
+ #
706
+ # * +subject+
707
+ # * +sender+
708
+ # * +from+
709
+ # * +to+
710
+ # * +cc+
711
+ # * +bcc+
712
+ # * +reply-to+
713
+ # * +orig-date+
714
+ # * +message-id+
715
+ # * +references+
716
+ #
717
+ # Fields can only appear once in email headers while other fields such as
718
+ # <tt>X-Anything</tt> can appear multiple times.
719
+ #
720
+ # If you want to replace any header which already exists, first set it to
721
+ # +nil+ in order to reset the value otherwise another field will be added
722
+ # for the same header.
723
+ def headers(args = nil)
493
724
  if args
494
- DeprecatedHeaderProxy.new(@_message).headers(args)
725
+ @_message.headers(args)
495
726
  else
496
- DeprecatedHeaderProxy.new(@_message)
727
+ @_message
497
728
  end
498
729
  end
499
730
 
@@ -501,23 +732,23 @@ module ActionMailer #:nodoc:
501
732
  #
502
733
  # mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
503
734
  #
504
- # If you do this, then Mail will take the file name and work out the mime type
505
- # set the Content-Type, Content-Disposition, Content-Transfer-Encoding and
506
- # base64 encode the contents of the attachment all for you.
735
+ # If you do this, then Mail will take the file name and work out the mime type.
736
+ # It will also set the +Content-Type+, +Content-Disposition+, and +Content-Transfer-Encoding+,
737
+ # and encode the contents of the attachment in Base64.
507
738
  #
508
739
  # You can also specify overrides if you want by passing a hash instead of a string:
509
740
  #
510
- # mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
511
- # :content => File.read('/path/to/filename.jpg')}
741
+ # mail.attachments['filename.jpg'] = {mime_type: 'application/gzip',
742
+ # content: File.read('/path/to/filename.jpg')}
512
743
  #
513
- # If you want to use a different encoding than Base64, you can pass an encoding in,
514
- # but then it is up to you to pass in the content pre-encoded, and don't expect
515
- # Mail to know how to decode this data:
744
+ # If you want to use encoding other than Base64 then you will need to pass encoding
745
+ # type along with the pre-encoded content as Mail doesn't know how to decode the
746
+ # data:
516
747
  #
517
748
  # file_content = SpecialEncode(File.read('/path/to/filename.jpg'))
518
- # mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
519
- # :encoding => 'SpecialEncoding',
520
- # :content => file_content }
749
+ # mail.attachments['filename.jpg'] = {mime_type: 'application/gzip',
750
+ # encoding: 'SpecialEncoding',
751
+ # content: file_content }
521
752
  #
522
753
  # You can also search for specific attachments:
523
754
  #
@@ -528,249 +759,319 @@ module ActionMailer #:nodoc:
528
759
  # mail.attachments[0] # => Mail::Part (first attachment)
529
760
  #
530
761
  def attachments
531
- @_message.attachments
762
+ if @_mail_was_called
763
+ LateAttachmentsProxy.new(@_message.attachments)
764
+ else
765
+ @_message.attachments
766
+ end
767
+ end
768
+
769
+ class LateAttachmentsProxy < SimpleDelegator
770
+ def inline; self end
771
+ def []=(_name, _content); _raise_error end
772
+
773
+ private
774
+ def _raise_error
775
+ raise RuntimeError, "Can't add attachments after `mail` was called.\n" \
776
+ "Make sure to use `attachments[]=` before calling `mail`."
777
+ end
532
778
  end
533
779
 
534
780
  # The main method that creates the message and renders the email templates. There are
535
781
  # two ways to call this method, with a block, or without a block.
536
782
  #
537
- # Both methods accept a headers hash. This hash allows you to specify the most used headers
538
- # in an email message, these are:
783
+ # It accepts a headers hash. This hash allows you to specify
784
+ # the most used headers in an email message, these are:
539
785
  #
540
- # * <tt>:subject</tt> - The subject of the message, if this is omitted, Action Mailer will
541
- # ask the Rails I18n class for a translated <tt>:subject</tt> in the scope of
542
- # <tt>[:actionmailer, mailer_scope, action_name]</tt> or if this is missing, will translate the
543
- # humanized version of the <tt>action_name</tt>
544
- # * <tt>:to</tt> - Who the message is destined for, can be a string of addresses, or an array
786
+ # * +:subject+ - The subject of the message, if this is omitted, Action Mailer will
787
+ # ask the \Rails I18n class for a translated +:subject+ in the scope of
788
+ # <tt>[mailer_scope, action_name]</tt> or if this is missing, will translate the
789
+ # humanized version of the +action_name+
790
+ # * +:to+ - Who the message is destined for, can be a string of addresses, or an array
545
791
  # of addresses.
546
- # * <tt>:from</tt> - Who the message is from
547
- # * <tt>:cc</tt> - Who you would like to Carbon-Copy on this email, can be a string of addresses,
792
+ # * +:from+ - Who the message is from
793
+ # * +:cc+ - Who you would like to Carbon-Copy on this email, can be a string of addresses,
548
794
  # or an array of addresses.
549
- # * <tt>:bcc</tt> - Who you would like to Blind-Carbon-Copy on this email, can be a string of
795
+ # * +:bcc+ - Who you would like to Blind-Carbon-Copy on this email, can be a string of
550
796
  # addresses, or an array of addresses.
551
- # * <tt>:reply_to</tt> - Who to set the Reply-To header of the email to.
552
- # * <tt>:date</tt> - The date to say the email was sent on.
797
+ # * +:reply_to+ - Who to set the +Reply-To+ header of the email to.
798
+ # * +:date+ - The date to say the email was sent on.
553
799
  #
554
- # You can set default values for any of the above headers (except :date) by using the <tt>default</tt>
555
- # class method:
800
+ # You can set default values for any of the above headers (except +:date+)
801
+ # by using the ::default class method:
556
802
  #
557
803
  # class Notifier < ActionMailer::Base
558
- # self.default :from => 'no-reply@test.lindsaar.net',
559
- # :bcc => 'email_logger@test.lindsaar.net',
560
- # :reply_to => 'bounces@test.lindsaar.net'
804
+ # default from: 'no-reply@test.lindsaar.net',
805
+ # bcc: 'email_logger@test.lindsaar.net',
806
+ # reply_to: 'bounces@test.lindsaar.net'
561
807
  # end
562
808
  #
563
809
  # If you need other headers not listed above, you can either pass them in
564
810
  # as part of the headers hash or use the <tt>headers['name'] = value</tt>
565
811
  # method.
566
812
  #
567
- # When a <tt>:return_path</tt> is specified as header, that value will be used as the 'envelope from'
568
- # address for the Mail message. Setting this is useful when you want delivery notifications
569
- # sent to a different address than the one in <tt>:from</tt>. Mail will actually use the
570
- # <tt>:return_path</tt> in preference to the <tt>:sender</tt> in preference to the <tt>:from</tt>
571
- # field for the 'envelope from' value.
813
+ # When a +:return_path+ is specified as header, that value will be used as
814
+ # the 'envelope from' address for the Mail message. Setting this is useful
815
+ # when you want delivery notifications sent to a different address than the
816
+ # one in +:from+. Mail will actually use the +:return_path+ in preference
817
+ # to the +:sender+ in preference to the +:from+ field for the 'envelope
818
+ # from' value.
572
819
  #
573
- # If you do not pass a block to the +mail+ method, it will find all templates in the
574
- # view paths using by default the mailer name and the method name that it is being
575
- # called from, it will then create parts for each of these templates intelligently,
576
- # making educated guesses on correct content type and sequence, and return a fully
577
- # prepared Mail::Message ready to call <tt>:deliver</tt> on to send.
820
+ # If you do not pass a block to the +mail+ method, it will find all
821
+ # templates in the view paths using by default the mailer name and the
822
+ # method name that it is being called from, it will then create parts for
823
+ # each of these templates intelligently, making educated guesses on correct
824
+ # content type and sequence, and return a fully prepared +Mail::Message+
825
+ # ready to call <tt>:deliver</tt> on to send.
578
826
  #
579
827
  # For example:
580
828
  #
581
829
  # class Notifier < ActionMailer::Base
582
- # default :from => 'no-reply@test.lindsaar.net',
830
+ # default from: 'no-reply@test.lindsaar.net'
583
831
  #
584
832
  # def welcome
585
- # mail(:to => 'mikel@test.lindsaar.net')
833
+ # mail(to: 'mikel@test.lindsaar.net')
586
834
  # end
587
835
  # end
588
836
  #
589
- # Will look for all templates at "app/views/notifier" with name "welcome". However, those
590
- # can be customized:
837
+ # Will look for all templates at "app/views/notifier" with name "welcome".
838
+ # If no welcome template exists, it will raise an ActionView::MissingTemplate error.
839
+ #
840
+ # However, those can be customized:
591
841
  #
592
- # mail(:template_path => 'notifications', :template_name => 'another')
842
+ # mail(template_path: 'notifications', template_name: 'another')
593
843
  #
594
844
  # And now it will look for all templates at "app/views/notifications" with name "another".
595
845
  #
596
846
  # If you do pass a block, you can render specific templates of your choice:
597
847
  #
598
- # mail(:to => 'mikel@test.lindsaar.net') do |format|
848
+ # mail(to: 'mikel@test.lindsaar.net') do |format|
599
849
  # format.text
600
850
  # format.html
601
851
  # end
602
852
  #
603
- # You can even render text directly without using a template:
853
+ # You can even render plain text directly without using a template:
604
854
  #
605
- # mail(:to => 'mikel@test.lindsaar.net') do |format|
606
- # format.text { render :text => "Hello Mikel!" }
607
- # format.html { render :text => "<h1>Hello Mikel!</h1>" }
855
+ # mail(to: 'mikel@test.lindsaar.net') do |format|
856
+ # format.text { render plain: "Hello Mikel!" }
857
+ # format.html { render html: "<h1>Hello Mikel!</h1>".html_safe }
608
858
  # end
609
859
  #
610
- # Which will render a <tt>multipart/alternative</tt> email with <tt>text/plain</tt> and
611
- # <tt>text/html</tt> parts.
860
+ # Which will render a +multipart/alternative+ email with +text/plain+ and
861
+ # +text/html+ parts.
612
862
  #
613
863
  # The block syntax also allows you to customize the part headers if desired:
614
864
  #
615
- # mail(:to => 'mikel@test.lindsaar.net') do |format|
616
- # format.text(:content_transfer_encoding => "base64")
865
+ # mail(to: 'mikel@test.lindsaar.net') do |format|
866
+ # format.text(content_transfer_encoding: "base64")
617
867
  # format.html
618
868
  # end
619
869
  #
620
- def mail(headers={}, &block)
621
- # Guard flag to prevent both the old and the new API from firing
622
- # Should be removed when old API is removed
623
- @mail_was_called = true
624
- m = @_message
870
+ def mail(headers = {}, &block)
871
+ return message if @_mail_was_called && headers.blank? && !block
625
872
 
626
- # At the beginning, do not consider class default for parts order neither content_type
873
+ # At the beginning, do not consider class default for content_type
627
874
  content_type = headers[:content_type]
628
- parts_order = headers[:parts_order]
629
875
 
630
- # Call all the procs (if any)
631
- default_values = self.class.default.merge(self.class.default) do |k,v|
632
- v.respond_to?(:call) ? v.bind(self).call : v
633
- end
634
-
635
- # Handle defaults
636
- headers = headers.reverse_merge(default_values)
637
- headers[:subject] ||= default_i18n_subject
876
+ headers = apply_defaults(headers)
638
877
 
639
878
  # Apply charset at the beginning so all fields are properly quoted
640
- m.charset = charset = headers[:charset]
879
+ message.charset = charset = headers[:charset]
641
880
 
642
881
  # Set configure delivery behavior
643
- wrap_delivery_behavior!(headers.delete(:delivery_method))
882
+ wrap_delivery_behavior!(headers[:delivery_method], headers[:delivery_method_options])
644
883
 
645
- # Assign all headers except parts_order, content_type and body
646
- assignable = headers.except(:parts_order, :content_type, :body, :template_name, :template_path)
647
- assignable.each { |k, v| m[k] = v }
884
+ assign_headers_to_message(message, headers)
648
885
 
649
886
  # Render the templates and blocks
650
- responses, explicit_order = collect_responses_and_parts_order(headers, &block)
651
- create_parts_from_responses(m, responses)
887
+ responses = collect_responses(headers, &block)
888
+ @_mail_was_called = true
889
+
890
+ create_parts_from_responses(message, responses)
891
+ wrap_inline_attachments(message)
652
892
 
653
- # Setup content type, reapply charset and handle parts order
654
- m.content_type = set_content_type(m, content_type, headers[:content_type])
655
- m.charset = charset
893
+ # Set up content type, reapply charset and handle parts order
894
+ message.content_type = set_content_type(message, content_type, headers[:content_type])
895
+ message.charset = charset
656
896
 
657
- if m.multipart?
658
- parts_order ||= explicit_order || headers[:parts_order]
659
- m.body.set_sort_order(parts_order)
660
- m.body.sort_parts!
897
+ if message.multipart?
898
+ message.body.set_sort_order(headers[:parts_order])
899
+ message.body.sort_parts!
661
900
  end
662
901
 
663
- m
902
+ message
664
903
  end
665
904
 
666
- protected
905
+ private
906
+ # Used by #mail to set the content type of the message.
907
+ #
908
+ # It will use the given +user_content_type+, or multipart if the mail
909
+ # message has any attachments. If the attachments are inline, the content
910
+ # type will be "multipart/related", otherwise "multipart/mixed".
911
+ #
912
+ # If there is no content type passed in via headers, and there are no
913
+ # attachments, or the message is multipart, then the default content type is
914
+ # used.
915
+ def set_content_type(m, user_content_type, class_default) # :doc:
916
+ params = m.content_type_parameters || {}
917
+ case
918
+ when user_content_type.present?
919
+ user_content_type
920
+ when m.has_attachments?
921
+ if m.attachments.all?(&:inline?)
922
+ ["multipart", "related", params]
923
+ else
924
+ ["multipart", "mixed", params]
925
+ end
926
+ when m.multipart?
927
+ ["multipart", "alternative", params]
928
+ else
929
+ m.content_type || class_default
930
+ end
931
+ end
932
+
933
+ # Translates the +subject+ using \Rails I18n class under <tt>[mailer_scope, action_name]</tt> scope.
934
+ # If it does not find a translation for the +subject+ under the specified scope it will default to a
935
+ # humanized version of the <tt>action_name</tt>.
936
+ # If the subject has interpolations, you can pass them through the +interpolations+ parameter.
937
+ def default_i18n_subject(interpolations = {}) # :doc:
938
+ mailer_scope = self.class.mailer_name.tr("/", ".")
939
+ I18n.t(:subject, **interpolations.merge(scope: [mailer_scope, action_name], default: action_name.humanize))
940
+ end
941
+
942
+ # Emails do not support relative path links.
943
+ def self.supports_path? # :doc:
944
+ false
945
+ end
946
+
947
+ def apply_defaults(headers)
948
+ default_values = self.class.default.except(*headers.keys).transform_values do |value|
949
+ compute_default(value)
950
+ end
667
951
 
668
- def set_content_type(m, user_content_type, class_default)
669
- params = m.content_type_parameters || {}
670
- case
671
- when user_content_type.present?
672
- user_content_type
673
- when m.has_attachments?
674
- if m.attachments.detect { |a| a.inline? }
675
- ["multipart", "related", params]
952
+ headers_with_defaults = headers.reverse_merge(default_values)
953
+ headers_with_defaults[:subject] ||= default_i18n_subject
954
+ headers_with_defaults
955
+ end
956
+
957
+ def compute_default(value)
958
+ return value unless value.is_a?(Proc)
959
+
960
+ if value.arity == 1
961
+ instance_exec(self, &value)
676
962
  else
677
- ["multipart", "mixed", params]
963
+ instance_exec(&value)
678
964
  end
679
- when m.multipart?
680
- ["multipart", "alternative", params]
681
- else
682
- m.content_type || class_default
683
965
  end
684
- end
685
966
 
686
- def default_i18n_subject #:nodoc:
687
- mailer_scope = self.class.mailer_name.gsub('/', '.')
688
- I18n.t(:subject, :scope => [mailer_scope, action_name], :default => action_name.humanize)
689
- end
967
+ def assign_headers_to_message(message, headers)
968
+ assignable = headers.except(:parts_order, :content_type, :body, :template_name,
969
+ :template_path, :delivery_method, :delivery_method_options)
970
+ assignable.each { |k, v| message[k] = v }
971
+ end
690
972
 
691
- def collect_responses_and_parts_order(headers) #:nodoc:
692
- responses, parts_order = [], nil
973
+ def collect_responses(headers, &block)
974
+ if block_given?
975
+ collect_responses_from_block(headers, &block)
976
+ elsif headers[:body]
977
+ collect_responses_from_text(headers)
978
+ else
979
+ collect_responses_from_templates(headers)
980
+ end
981
+ end
693
982
 
694
- if block_given?
695
- collector = ActionMailer::Collector.new(lookup_context) { render(action_name) }
983
+ def collect_responses_from_block(headers)
984
+ templates_name = headers[:template_name] || action_name
985
+ collector = ActionMailer::Collector.new(lookup_context) { render(templates_name) }
696
986
  yield(collector)
697
- parts_order = collector.responses.map { |r| r[:content_type] }
698
- responses = collector.responses
699
- elsif headers[:body]
700
- responses << {
701
- :body => headers.delete(:body),
702
- :content_type => self.class.default[:content_type] || "text/plain"
703
- }
704
- else
705
- templates_path = headers.delete(:template_path) || self.class.mailer_name
706
- templates_name = headers.delete(:template_name) || action_name
987
+ collector.responses
988
+ end
989
+
990
+ def collect_responses_from_text(headers)
991
+ [{
992
+ body: headers.delete(:body),
993
+ content_type: headers[:content_type] || "text/plain"
994
+ }]
995
+ end
707
996
 
708
- each_template(templates_path, templates_name) do |template|
709
- self.formats = template.formats
997
+ def collect_responses_from_templates(headers)
998
+ templates_path = headers[:template_path] || self.class.mailer_name
999
+ templates_name = headers[:template_name] || action_name
710
1000
 
711
- responses << {
712
- :body => render(:template => template),
713
- :content_type => template.mime_type.to_s
1001
+ each_template(Array(templates_path), templates_name).map do |template|
1002
+ format = template.format || self.formats.first
1003
+ {
1004
+ body: render(template: template, formats: [format]),
1005
+ content_type: Mime[format].to_s
714
1006
  }
715
1007
  end
716
1008
  end
717
1009
 
718
- [responses, parts_order]
719
- end
1010
+ def each_template(paths, name, &block)
1011
+ templates = lookup_context.find_all(name, paths)
1012
+ if templates.empty?
1013
+ raise ActionView::MissingTemplate.new(paths, name, paths, false, "mailer")
1014
+ else
1015
+ templates.uniq(&:format).each(&block)
1016
+ end
1017
+ end
1018
+
1019
+ def wrap_inline_attachments(message)
1020
+ # If we have both types of attachment, wrap all the inline attachments
1021
+ # in multipart/related, but not the actual attachments
1022
+ if message.attachments.detect(&:inline?) && message.attachments.detect { |a| !a.inline? }
1023
+ related = Mail::Part.new
1024
+ related.content_type = "multipart/related"
1025
+ mixed = [ related ]
720
1026
 
721
- def each_template(paths, name, &block) #:nodoc:
722
- Array.wrap(paths).each do |path|
723
- templates = lookup_context.find_all(name, path)
724
- templates = templates.uniq_by { |t| t.formats }
1027
+ message.parts.each do |p|
1028
+ if p.attachment? && !p.inline?
1029
+ mixed << p
1030
+ else
1031
+ related.add_part(p)
1032
+ end
1033
+ end
725
1034
 
726
- unless templates.empty?
727
- templates.each(&block)
728
- return
1035
+ message.parts.clear
1036
+ mixed.each { |c| message.add_part(c) }
729
1037
  end
730
1038
  end
731
- end
732
1039
 
733
- def create_parts_from_responses(m, responses) #:nodoc:
734
- if responses.size == 1 && !m.has_attachments?
735
- responses[0].each { |k,v| m[k] = v }
736
- elsif responses.size > 1 && m.has_attachments?
737
- container = Mail::Part.new
738
- container.content_type = "multipart/alternative"
739
- responses.each { |r| insert_part(container, r, m.charset) }
740
- m.add_part(container)
741
- else
742
- responses.each { |r| insert_part(m, r, m.charset) }
1040
+ def create_parts_from_responses(m, responses)
1041
+ if responses.size == 1 && !m.has_attachments?
1042
+ responses[0].each { |k, v| m[k] = v }
1043
+ elsif responses.size > 1 && m.has_attachments?
1044
+ container = Mail::Part.new
1045
+ container.content_type = "multipart/alternative"
1046
+ responses.each { |r| insert_part(container, r, m.charset) }
1047
+ m.add_part(container)
1048
+ else
1049
+ responses.each { |r| insert_part(m, r, m.charset) }
1050
+ end
743
1051
  end
744
- end
745
1052
 
746
- def insert_part(container, response, charset) #:nodoc:
747
- response[:charset] ||= charset
748
- part = Mail::Part.new(response)
749
- container.add_part(part)
750
- end
751
-
752
- module DeprecatedUrlOptions
753
- def default_url_options
754
- deprecated_url_options
1053
+ def insert_part(container, response, charset)
1054
+ response[:charset] ||= charset
1055
+ part = Mail::Part.new(response)
1056
+ container.add_part(part)
755
1057
  end
756
1058
 
757
- def default_url_options=(val)
758
- deprecated_url_options
1059
+ # This and #instrument_name is for caching instrument
1060
+ def instrument_payload(key)
1061
+ {
1062
+ mailer: mailer_name,
1063
+ key: key
1064
+ }
759
1065
  end
760
1066
 
761
- def deprecated_url_options
762
- raise "You can no longer call ActionMailer::Base.default_url_options " \
763
- "directly. You need to set config.action_mailer.default_url_options. " \
764
- "If you are using ActionMailer standalone, you need to include the " \
765
- "routing url_helpers directly."
1067
+ def instrument_name
1068
+ "action_mailer"
766
1069
  end
767
- end
768
1070
 
769
- # This module will complain if the user tries to set default_url_options
770
- # directly instead of through the config object. In Action Mailer's Railtie,
771
- # we include the router's url_helpers, which will override this module.
772
- extend DeprecatedUrlOptions
1071
+ def _protected_ivars
1072
+ PROTECTED_IVARS
1073
+ end
773
1074
 
774
- ActiveSupport.run_load_hooks(:action_mailer, self)
1075
+ ActiveSupport.run_load_hooks(:action_mailer, self)
775
1076
  end
776
1077
  end