1 require 'action_mailer/adv_attr_accessor'
2 require 'action_mailer/part'
3 require 'action_mailer/part_container'
4 require 'action_mailer/utils'
7 module ActionMailer
#:nodoc:
8 # Action Mailer allows you to send email from your application using a mailer model and views.
13 # To use Action Mailer, you need to create a mailer model.
15 # $ script/generate mailer Notifier
17 # The generated model inherits from ActionMailer::Base. Emails are defined by creating methods within the model which are then
18 # used to set variables to be used in the mail template, to change options on the mail, or
23 # class Notifier < ActionMailer::Base
24 # def signup_notification(recipient)
25 # recipients recipient.email_address_with_name
26 # from "system@example.com"
27 # subject "New account information"
28 # body :account => recipient
32 # Mailer methods have the following configuration methods available.
34 # * <tt>recipients</tt> - Takes one or more email addresses. These addresses are where your email will be delivered to. Sets the <tt>To:</tt> header.
35 # * <tt>subject</tt> - The subject of your email. Sets the <tt>Subject:</tt> header.
36 # * <tt>from</tt> - Who the email you are sending is from. Sets the <tt>From:</tt> header.
37 # * <tt>cc</tt> - Takes one or more email addresses. These addresses will receive a carbon copy of your email. Sets the <tt>Cc:</tt> header.
38 # * <tt>bcc</tt> - Takes one or more email addresses. These addresses will receive a blind carbon copy of your email. Sets the <tt>Bcc:</tt> header.
39 # * <tt>reply_to</tt> - Takes one or more email addresses. These addresses will be listed as the default recipients when replying to your email. Sets the <tt>Reply-To:</tt> header.
40 # * <tt>sent_on</tt> - The date on which the message was sent. If not set, the header wil be set by the delivery agent.
41 # * <tt>content_type</tt> - Specify the content type of the message. Defaults to <tt>text/plain</tt>.
42 # * <tt>headers</tt> - Specify additional headers to be set for the message, e.g. <tt>headers 'X-Mail-Count' => 107370</tt>.
44 # When a <tt>headers 'return-path'</tt> is specified, that value will be used as the 'envelope from'
45 # address. Setting this is useful when you want delivery notifications sent to a different address than
46 # the one in <tt>from</tt>.
48 # The <tt>body</tt> method has special behavior. It takes a hash which generates an instance variable
49 # named after each key in the hash containing the value that that key points to.
51 # So, for example, <tt>body :account => recipient</tt> would result
52 # in an instance variable <tt>@account</tt> with the value of <tt>recipient</tt> being accessible in the
58 # Like Action Controller, each mailer class has a corresponding view directory
59 # in which each method of the class looks for a template with its name.
60 # To define a template to be used with a mailing, create an <tt>.erb</tt> file with the same name as the method
61 # in your mailer model. For example, in the mailer defined above, the template at
62 # <tt>app/views/notifier/signup_notification.erb</tt> would be used to generate the email.
64 # Variables defined in the model are accessible as instance variables in the view.
66 # Emails by default are sent in plain text, so a sample view for our model example might look like this:
68 # Hi <%= @account.name %>,
69 # Thanks for joining our service! Please check back often.
71 # You can even use Action Pack helpers in these views. For example:
74 # <%= truncate(note.body, 25) %>
79 # URLs can be generated in mailer views using <tt>url_for</tt> or named routes.
80 # Unlike controllers from Action Pack, the mailer instance doesn't have any context about the incoming request,
81 # so you'll need to provide all of the details needed to generate a URL.
83 # When using <tt>url_for</tt> you'll need to provide the <tt>:host</tt>, <tt>:controller</tt>, and <tt>:action</tt>:
85 # <%= url_for(:host => "example.com", :controller => "welcome", :action => "greeting") %>
87 # When using named routes you only need to supply the <tt>:host</tt>:
89 # <%= users_url(:host => "example.com") %>
91 # You will want to avoid using the <tt>name_of_route_path</tt> form of named routes because it doesn't make sense to
92 # generate relative URLs in email messages.
94 # It is also possible to set a default host that will be used in all mailers by setting the <tt>:host</tt> option in
95 # the <tt>ActionMailer::Base.default_url_options</tt> hash as follows:
97 # ActionMailer::Base.default_url_options[:host] = "example.com"
99 # This can also be set as a configuration option in <tt>config/environment.rb</tt>:
101 # config.action_mailer.default_url_options = { :host => "example.com" }
103 # If you do decide to set a default <tt>:host</tt> for your mailers you will want to use the
104 # <tt>:only_path => false</tt> option when using <tt>url_for</tt>. This will ensure that absolute URLs are generated because
105 # the <tt>url_for</tt> view helper will, by default, generate relative URLs when a <tt>:host</tt> option isn't
106 # explicitly provided.
110 # Once a mailer action and template are defined, you can deliver your message or create it and save it
111 # for delivery later:
113 # Notifier.deliver_signup_notification(david) # sends the email
114 # mail = Notifier.create_signup_notification(david) # => a tmail object
115 # Notifier.deliver(mail)
117 # You never instantiate your mailer class. Rather, your delivery instance
118 # methods are automatically wrapped in class methods that start with the word
119 # <tt>deliver_</tt> followed by the name of the mailer method that you would
120 # like to deliver. The <tt>signup_notification</tt> method defined above is
121 # delivered by invoking <tt>Notifier.deliver_signup_notification</tt>.
126 # To send mail as HTML, make sure your view (the <tt>.erb</tt> file) generates HTML and
127 # set the content type to html.
129 # class MyMailer < ActionMailer::Base
130 # def signup_notification(recipient)
131 # recipients recipient.email_address_with_name
132 # subject "New account information"
133 # from "system@example.com"
134 # body :account => recipient
135 # content_type "text/html"
142 # You can explicitly specify multipart messages:
144 # class ApplicationMailer < ActionMailer::Base
145 # def signup_notification(recipient)
146 # recipients recipient.email_address_with_name
147 # subject "New account information"
148 # from "system@example.com"
149 # content_type "multipart/alternative"
151 # part :content_type => "text/html",
152 # :body => render_message("signup-as-html", :account => recipient)
154 # part "text/plain" do |p|
155 # p.body = render_message("signup-as-plain", :account => recipient)
156 # p.transfer_encoding = "base64"
161 # Multipart messages can also be used implicitly because Action Mailer will automatically
162 # detect and use multipart templates, where each template is named after the name of the action, followed
163 # by the content type. Each such detected template will be added as separate part to the message.
165 # For example, if the following templates existed:
166 # * signup_notification.text.plain.erb
167 # * signup_notification.text.html.erb
168 # * signup_notification.text.xml.builder
169 # * signup_notification.text.x-yaml.erb
171 # Each would be rendered and added as a separate part to the message,
172 # with the corresponding content type. The content type for the entire
173 # message is automatically set to <tt>multipart/alternative</tt>, which indicates
174 # that the email contains multiple different representations of the same email
175 # body. The same body hash is passed to each template.
177 # Implicit template rendering is not performed if any attachments or parts have been added to the email.
178 # This means that you'll have to manually add each part to the email and set the content type of the email
179 # to <tt>multipart/alternative</tt>.
183 # Attachments can be added by using the +attachment+ method.
187 # class ApplicationMailer < ActionMailer::Base
189 # def signup_notification(recipient)
190 # recipients recipient.email_address_with_name
191 # subject "New account information"
192 # from "system@example.com"
194 # attachment :content_type => "image/jpeg",
195 # :body => File.read("an-image.jpg")
197 # attachment "application/pdf" do |a|
198 # a.body = generate_your_pdf_here()
204 # = Configuration options
206 # These options are specified on the class level, like <tt>ActionMailer::Base.template_root = "/my/templates"</tt>
208 # * <tt>template_root</tt> - Determines the base from which template references will be made.
210 # * <tt>logger</tt> - the logger is used for generating information on the mailing run if available.
211 # Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
213 # * <tt>smtp_settings</tt> - Allows detailed configuration for <tt>:smtp</tt> delivery method:
214 # * <tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default "localhost" setting.
215 # * <tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.
216 # * <tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.
217 # * <tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.
218 # * <tt>:password</tt> - If your mail server requires authentication, set the password in this setting.
219 # * <tt>:authentication</tt> - If your mail server requires authentication, you need to specify the authentication type here.
220 # This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>.
222 # * <tt>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method.
223 # * <tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.
224 # * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt>.
226 # * <tt>raise_delivery_errors</tt> - Whether or not errors should be raised if the email fails to be delivered.
228 # * <tt>delivery_method</tt> - Defines a delivery method. Possible values are <tt>:smtp</tt> (default), <tt>:sendmail</tt>, and <tt>:test</tt>.
230 # * <tt>perform_deliveries</tt> - Determines whether <tt>deliver_*</tt> methods are actually carried out. By default they are,
231 # but this can be turned off to help functional testing.
233 # * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with <tt>delivery_method :test</tt>. Most useful
234 # for unit and functional testing.
236 # * <tt>default_charset</tt> - The default charset used for the body and to encode the subject. Defaults to UTF-8. You can also
237 # pick a different charset from inside a method with +charset+.
238 # * <tt>default_content_type</tt> - The default content type used for the main part of the message. Defaults to "text/plain". You
239 # can also pick a different content type from inside a method with +content_type+.
240 # * <tt>default_mime_version</tt> - The default mime version used for the message. Defaults to <tt>1.0</tt>. You
241 # can also pick a different value from inside a method with +mime_version+.
242 # * <tt>default_implicit_parts_order</tt> - When a message is built implicitly (i.e. multiple parts are assembled from templates
243 # which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to
244 # <tt>["text/html", "text/enriched", "text/plain"]</tt>. Items that appear first in the array have higher priority in the mail client
245 # and appear last in the mime encoded message. You can also pick a different order from inside a method with
246 # +implicit_parts_order+.
248 include AdvAttrAccessor
, PartContainer
249 if Object
.const_defined
?(:ActionController)
250 include ActionController
::UrlWriter
251 include ActionController
::Layout
254 private_class_method
:new #:nodoc:
256 class_inheritable_accessor
:view_paths
257 cattr_accessor
:logger
260 :address => "localhost",
262 :domain => 'localhost.localdomain',
265 :authentication => nil
267 cattr_accessor
:smtp_settings
269 @
@sendmail_settings = {
270 :location => '/usr/sbin/sendmail',
271 :arguments => '-i -t'
273 cattr_accessor
:sendmail_settings
275 @
@raise_delivery_errors = true
276 cattr_accessor
:raise_delivery_errors
278 superclass_delegating_accessor
:delivery_method
279 self.delivery_method
= :smtp
281 @
@perform_deliveries = true
282 cattr_accessor
:perform_deliveries
285 cattr_accessor
:deliveries
287 @
@default_charset = "utf-8"
288 cattr_accessor
:default_charset
290 @
@default_content_type = "text/plain"
291 cattr_accessor
:default_content_type
293 @
@default_mime_version = "1.0"
294 cattr_accessor
:default_mime_version
296 @
@default_implicit_parts_order = [ "text/html", "text/enriched", "text/plain" ]
297 cattr_accessor
:default_implicit_parts_order
299 cattr_reader
:protected_instance_variables
300 @
@protected_instance_variables = %w(@body)
302 # Specify the BCC addresses for the message
303 adv_attr_accessor
:bcc
305 # Define the body of the message. This is either a Hash (in which case it
306 # specifies the variables to pass to the template when it is rendered),
307 # or a string, in which case it specifies the actual text of the message.
308 adv_attr_accessor
:body
310 # Specify the CC addresses for the message.
311 adv_attr_accessor
:cc
313 # Specify the charset to use for the message. This defaults to the
314 # +default_charset+ specified for ActionMailer::Base.
315 adv_attr_accessor
:charset
317 # Specify the content type for the message. This defaults to <tt>text/plain</tt>
318 # in most cases, but can be automatically set in some situations.
319 adv_attr_accessor
:content_type
321 # Specify the from address for the message.
322 adv_attr_accessor
:from
324 # Specify the address (if different than the "from" address) to direct
325 # replies to this message.
326 adv_attr_accessor
:reply_to
328 # Specify additional headers to be added to the message.
329 adv_attr_accessor
:headers
331 # Specify the order in which parts should be sorted, based on content-type.
332 # This defaults to the value for the +default_implicit_parts_order+.
333 adv_attr_accessor
:implicit_parts_order
335 # Defaults to "1.0", but may be explicitly given if needed.
336 adv_attr_accessor
:mime_version
338 # The recipient addresses for the message, either as a string (for a single
339 # address) or an array (for multiple addresses).
340 adv_attr_accessor
:recipients
342 # The date on which the message was sent. If not set (the default), the
343 # header will be set by the delivery agent.
344 adv_attr_accessor
:sent_on
346 # Specify the subject of the message.
347 adv_attr_accessor
:subject
349 # Specify the template name to use for current message. This is the "base"
350 # template name, without the extension or directory, and may be used to
351 # have multiple mailer methods share the same template.
352 adv_attr_accessor
:template
354 # Override the mailer name, which defaults to an inflected version of the
355 # mailer's class name. If you want to use a template in a non-standard
356 # location, you can use this to specify that location.
357 def mailer_name(value
= nil)
359 self.mailer_name
= value
361 self.class.mailer_name
365 def mailer_name
=(value
)
366 self.class.mailer_name
= value
369 # The mail object instance referenced by this mailer.
371 attr_reader
:template_name, :default_template_name, :action_name
374 attr_writer
:mailer_name
377 @mailer_name ||= name
.underscore
380 # for ActionView compatibility
381 alias_method
:controller_name, :mailer_name
382 alias_method
:controller_path, :mailer_name
384 def respond_to
?(method_symbol
, include_private
= false) #:nodoc:
385 matches_dynamic_method
?(method_symbol
) || super
388 def method_missing(method_symbol
, *parameters
) #:nodoc:
389 if match
= matches_dynamic_method
?(method_symbol
)
391 when 'create' then new(match
[2], *parameters
).mail
392 when 'deliver' then new(match
[2], *parameters
).deliver
!
401 # Receives a raw email, parses it into an email object, decodes it,
402 # instantiates a new mailer, and passes the email object to the mailer
403 # object's +receive+ method. If you want your mailer to be able to
404 # process incoming messages, you'll need to implement a +receive+
405 # method that accepts the email object as a parameter:
407 # class MyMailer < ActionMailer::Base
412 def receive(raw_email
)
413 logger
.info
"Received mail:\n #{raw_email}" unless logger
.nil?
414 mail
= TMail
::Mail.parse(raw_email
)
419 # Deliver the given mail object directly. This can be used to deliver
420 # a preconstructed mail object, like:
422 # email = MyMailer.create_some_mail(parameters)
423 # email.set_some_obscure_header "frobnicate"
424 # MyMailer.deliver(email)
429 def register_template_extension(extension
)
430 ActiveSupport
::Deprecation.warn(
431 "ActionMailer::Base.register_template_extension has been deprecated." +
432 "Use ActionView::Base.register_template_extension instead", caller
)
436 self.view_paths
&& self.view_paths
.first
439 def template_root
=(root
)
440 self.view_paths
= ActionView
::Base.process_view_paths(root
)
444 def matches_dynamic_method
?(method_name
) #:nodoc:
445 method_name
= method_name
.to_s
446 /^(create|deliver)_([_a-z]\w*)/.match(method_name
) || /^(new)$/.match(method_name
)
450 # Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer
451 # will be initialized according to the named method. If not, the mailer will
452 # remain uninitialized (useful when you only need to invoke the "receive"
453 # method, for instance).
454 def initialize(method_name
=nil, *parameters
) #:nodoc:
455 create
!(method_name
, *parameters
) if method_name
458 # Initialize the mailer via the given +method_name+. The body will be
459 # rendered and a new TMail::Mail object created.
460 def create
!(method_name
, *parameters
) #:nodoc:
461 initialize_defaults(method_name
)
462 __send__(method_name
, *parameters
)
464 # If an explicit, textual body has not been set, we check assumptions.
465 unless String
=== @body
466 # First, we look to see if there are any likely templates that match,
467 # which include the content-type in their file name (i.e.,
468 # "the_template_file.text.html.erb", etc.). Only do this if parts
469 # have not already been specified manually.
471 Dir
.glob("#{template_path}/#{@template}.*").each
do |path
|
472 template
= template_root
["#{mailer_name}/#{File.basename(path)}"]
474 # Skip unless template has a multipart format
475 next unless template
&& template
.multipart
?
478 :content_type => template
.content_type
,
479 :disposition => "inline",
481 :body => render_message(template
, @body)
485 @content_type = "multipart/alternative"
486 @parts = sort_parts(@parts, @implicit_parts_order)
490 # Then, if there were such templates, we check to see if we ought to
491 # also render a "normal" template (without the content type). If a
492 # normal template exists (or if there were no implicit parts) we render
494 template_exists
= @parts.empty
?
495 template_exists
||= template_root
["#{mailer_name}/#{@template}"]
496 @body = render_message(@template, @body) if template_exists
498 # Finally, if there are other message parts and a textual body exists,
499 # we shift it onto the front of the parts and set the body to nil (so
500 # that create_mail doesn't try to render it in addition to the parts).
501 if !@parts.empty
? && String
=== @body
502 @parts.unshift Part
.new(:charset => charset
, :body => @body)
507 # If this is a multipart e-mail add the mime_version if it is not
509 @mime_version ||= "1.0" if !@parts.empty
?
511 # build the mail object itself
515 # Delivers a TMail::Mail object. By default, it delivers the cached mail
516 # object (from the <tt>create!</tt> method). If no cached mail object exists, and
517 # no alternate has been given as the parameter, this will fail.
518 def deliver
!(mail
= @mail)
519 raise "no mail object available for delivery!" unless mail
521 logger
.info
"Sent mail to #{Array(recipients).join(', ')}"
522 logger
.debug
"\n#{mail.encoded}"
526 __send__("perform_delivery_#{delivery_method}", mail
) if perform_deliveries
527 rescue Exception
=> e
# Net::SMTP errors or sendmail pipe errors
528 raise e
if raise_delivery_errors
535 # Set up the default values for the various instance variables of this
536 # mailer. Subclasses may override this method to provide different
538 def initialize_defaults(method_name
)
539 @charset ||= @
@default_charset.dup
540 @content_type ||= @
@default_content_type.dup
541 @implicit_parts_order ||= @
@default_implicit_parts_order.dup
542 @template ||= method_name
543 @default_template_name = @action_name = @template
544 @mailer_name ||= self.class.name
.underscore
548 @mime_version = @
@default_mime_version.dup
if @
@default_mime_version
551 def render_message(method_name
, body
)
552 render
:file => method_name
, :body => body
556 body
= opts
.delete(:body)
557 if opts
[:file] && (opts
[:file] !~
/\// && !opts
[:file].respond_to
?(:render))
558 opts
[:file] = "#{mailer_name}/#{opts[:file]}"
562 old_template
, @template = @template, initialize_template_class(body
)
563 layout
= respond_to
?(:pick_layout, true) ? pick_layout(opts
) : false
564 @template.render(opts
.merge(:layout => layout
))
566 @template = old_template
570 def default_template_format
574 def candidate_for_layout
?(options
)
575 !@template.send(:_exempt_from_layout?, default_template_name
)
579 self.class.template_root
582 def template_root
=(root
)
583 self.class.template_root
= root
587 "#{template_root}/#{mailer_name}"
590 def initialize_template_class(assigns
)
591 ActionView
::Base.new(view_paths
, assigns
, self)
594 def sort_parts(parts
, order
= [])
595 order
= order
.collect
{ |s
| s
.downcase
}
597 parts
= parts
.sort
do |a
, b
|
598 a_ct
= a
.content_type
.downcase
599 b_ct
= b
.content_type
.downcase
601 a_in
= order
.include? a_ct
602 b_in
= order
.include? b_ct
606 order
.index(a_ct
) <=> order
.index(b_ct
)
615 # reverse the ordering because parts that come last are displayed
616 # first in mail clients
626 m
.subject
, = quote_any_if_necessary(charset
, subject
)
627 m
.to
, m
.from
= quote_any_address_if_necessary(charset
, recipients
, from
)
628 m
.bcc
= quote_address_if_necessary(bcc
, charset
) unless bcc
.nil?
629 m
.cc
= quote_address_if_necessary(cc
, charset
) unless cc
.nil?
630 m
.reply_to
= quote_address_if_necessary(reply_to
, charset
) unless reply_to
.nil?
631 m
.mime_version
= mime_version
unless mime_version
.nil?
632 m
.date
= sent_on
.to_time
rescue sent_on
if sent_on
634 headers
.each
{ |k
, v
| m
[k
] = v
}
636 real_content_type
, ctype_attrs
= parse_content_type
639 m
.set_content_type(real_content_type
, nil, ctype_attrs
)
640 m
.body
= Utils
.normalize_new_lines(body
)
643 part
= TMail
::Mail.new
644 part
.body
= Utils
.normalize_new_lines(body
)
645 part
.set_content_type(real_content_type
, nil, ctype_attrs
)
646 part
.set_content_disposition
"inline"
651 part
= (TMail
::Mail === p
? p
: p
.to_mail(self))
655 if real_content_type
=~
/multipart/
656 ctype_attrs
.delete
"charset"
657 m
.set_content_type(real_content_type
, nil, ctype_attrs
)
664 def perform_delivery_smtp(mail
)
665 destinations
= mail
.destinations
667 sender
= mail
['return-path'] || mail
.from
669 smtp
= Net
::SMTP.new(smtp_settings
[:address], smtp_settings
[:port])
670 smtp
.enable_starttls_auto
if smtp
.respond_to
?(:enable_starttls_auto)
671 smtp
.start(smtp_settings
[:domain], smtp_settings
[:user_name], smtp_settings
[:password],
672 smtp_settings
[:authentication]) do |smtp
|
673 smtp
.sendmail(mail
.encoded
, sender
, destinations
)
677 def perform_delivery_sendmail(mail
)
678 sendmail_args
= sendmail_settings
[:arguments]
679 sendmail_args
+= " -f \"#{mail['return-path']}\"" if mail
['return-path']
680 IO
.popen("#{sendmail_settings[:location]} #{sendmail_args}","w+") do |sm
|
681 sm
.print(mail
.encoded
.gsub(/\r/, ''))
686 def perform_delivery_test(mail
)