All Files ( 83.05% covered at 28.24 hits/line )
19 files in total.
767 relevant lines,
637 lines covered and
130 lines missed.
(
83.05%
)
# frozen_string_literal: true
#--
# Copyright (c) 2004-2020 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
- 1
require "abstract_controller"
- 1
require "action_mailer/version"
# Common Active Support usage in Action Mailer
- 1
require "active_support"
- 1
require "active_support/rails"
- 1
require "active_support/core_ext/class"
- 1
require "active_support/core_ext/module/attr_internal"
- 1
require "active_support/core_ext/string/inflections"
- 1
require "active_support/lazy_load_hooks"
- 1
module ActionMailer
- 1
extend ::ActiveSupport::Autoload
- 1
eager_autoload do
- 1
autoload :Collector
end
- 1
autoload :Base
- 1
autoload :DeliveryMethods
- 1
autoload :InlinePreviewInterceptor
- 1
autoload :MailHelper
- 1
autoload :Parameterized
- 1
autoload :Preview
- 1
autoload :Previews, "action_mailer/preview"
- 1
autoload :TestCase
- 1
autoload :TestHelper
- 1
autoload :MessageDelivery
- 1
autoload :DeliveryJob
- 1
autoload :MailDeliveryJob
- 1
def self.eager_load!
super
require "mail"
Mail.eager_autoload!
end
end
- 1
autoload :Mime, "action_dispatch/http/mime_type"
- 1
ActiveSupport.on_load(:action_view) do
- 1
ActionView::Base.default_formats ||= Mime::SET.symbols
- 1
ActionView::Template::Types.delegate_to Mime
- 1
ActionView::LookupContext::DetailsKey.clear
end
# frozen_string_literal: true
- 1
require "mail"
- 1
require "action_mailer/collector"
- 1
require "active_support/core_ext/string/inflections"
- 1
require "active_support/core_ext/hash/except"
- 1
require "active_support/core_ext/module/anonymous"
- 1
require "action_mailer/log_subscriber"
- 1
require "action_mailer/rescuable"
- 1
module ActionMailer
# Action Mailer allows you to send email from your application using a mailer model and views.
#
# = Mailer Models
#
# To use Action Mailer, you need to create a mailer model.
#
# $ bin/rails generate mailer Notifier
#
# The generated model inherits from <tt>ApplicationMailer</tt> which in turn
# inherits from <tt>ActionMailer::Base</tt>. A mailer model defines methods
# used to generate an email message. In these methods, you can set up variables to be used in
# the mailer views, options on the mail itself such as the <tt>:from</tt> address, and attachments.
#
# class ApplicationMailer < ActionMailer::Base
# default from: 'from@example.com'
# layout 'mailer'
# end
#
# class NotifierMailer < ApplicationMailer
# default from: 'no-reply@example.com',
# return_path: 'system@example.com'
#
# def welcome(recipient)
# @account = recipient
# mail(to: recipient.email_address_with_name,
# bcc: ["bcc@example.com", "Order Watcher <watcher@example.com>"])
# end
# end
#
# Within the mailer method, you have access to the following methods:
#
# * <tt>attachments[]=</tt> - Allows you to add attachments to your email in an intuitive
# manner; <tt>attachments['filename.png'] = File.read('path/to/filename.png')</tt>
#
# * <tt>attachments.inline[]=</tt> - Allows you to add an inline attachment to your email
# in the same manner as <tt>attachments[]=</tt>
#
# * <tt>headers[]=</tt> - Allows you to specify any header field in your email such
# as <tt>headers['X-No-Spam'] = 'True'</tt>. Note that declaring a header multiple times
# will add many fields of the same name. Read #headers doc for more information.
#
# * <tt>headers(hash)</tt> - Allows you to specify multiple headers in your email such
# as <tt>headers({'X-No-Spam' => 'True', 'In-Reply-To' => '1234@message.id'})</tt>
#
# * <tt>mail</tt> - Allows you to specify email to be sent.
#
# The hash passed to the mail method allows you to specify any header that a <tt>Mail::Message</tt>
# will accept (any valid email header including optional fields).
#
# The +mail+ method, if not passed a block, will inspect your views and send all the views with
# the same name as the method, so the above action would send the +welcome.text.erb+ view
# file as well as the +welcome.html.erb+ view file in a +multipart/alternative+ email.
#
# If you want to explicitly render only certain templates, pass a block:
#
# mail(to: user.email) do |format|
# format.text
# format.html
# end
#
# The block syntax is also useful in providing information specific to a part:
#
# mail(to: user.email) do |format|
# format.text(content_transfer_encoding: "base64")
# format.html
# end
#
# Or even to render a special view:
#
# mail(to: user.email) do |format|
# format.text
# format.html { render "some_other_template" }
# end
#
# = Mailer views
#
# Like Action Controller, each mailer class has a corresponding view directory in which each
# method of the class looks for a template with its name.
#
# To define a template to be used with a mailer, create an <tt>.erb</tt> file with the same
# name as the method in your mailer model. For example, in the mailer defined above, the template at
# <tt>app/views/notifier_mailer/welcome.text.erb</tt> would be used to generate the email.
#
# Variables defined in the methods of your mailer model are accessible as instance variables in their
# corresponding view.
#
# Emails by default are sent in plain text, so a sample view for our model example might look like this:
#
# Hi <%= @account.name %>,
# Thanks for joining our service! Please check back often.
#
# You can even use Action View helpers in these views. For example:
#
# You got a new note!
# <%= truncate(@note.body, length: 25) %>
#
# If you need to access the subject, from or the recipients in the view, you can do that through message object:
#
# You got a new note from <%= message.from %>!
# <%= truncate(@note.body, length: 25) %>
#
#
# = Generating URLs
#
# URLs can be generated in mailer views using <tt>url_for</tt> or named routes. Unlike controllers from
# Action Pack, the mailer instance doesn't have any context about the incoming request, so you'll need
# to provide all of the details needed to generate a URL.
#
# When using <tt>url_for</tt> you'll need to provide the <tt>:host</tt>, <tt>:controller</tt>, and <tt>:action</tt>:
#
# <%= url_for(host: "example.com", controller: "welcome", action: "greeting") %>
#
# When using named routes you only need to supply the <tt>:host</tt>:
#
# <%= users_url(host: "example.com") %>
#
# You should use the <tt>named_route_url</tt> style (which generates absolute URLs) and avoid using the
# <tt>named_route_path</tt> style (which generates relative URLs), since clients reading the mail will
# have no concept of a current URL from which to determine a relative path.
#
# It is also possible to set a default host that will be used in all mailers by setting the <tt>:host</tt>
# option as a configuration option in <tt>config/application.rb</tt>:
#
# config.action_mailer.default_url_options = { host: "example.com" }
#
# You can also define a <tt>default_url_options</tt> method on individual mailers to override these
# default settings per-mailer.
#
# By default when <tt>config.force_ssl</tt> is +true+, URLs generated for hosts will use the HTTPS protocol.
#
# = Sending mail
#
# Once a mailer action and template are defined, you can deliver your message or defer its creation and
# delivery for later:
#
# NotifierMailer.welcome(User.first).deliver_now # sends the email
# mail = NotifierMailer.welcome(User.first) # => an ActionMailer::MessageDelivery object
# mail.deliver_now # generates and sends the email now
#
# The <tt>ActionMailer::MessageDelivery</tt> class is a wrapper around a delegate that will call
# your method to generate the mail. If you want direct access to the delegator, or <tt>Mail::Message</tt>,
# you can call the <tt>message</tt> method on the <tt>ActionMailer::MessageDelivery</tt> object.
#
# NotifierMailer.welcome(User.first).message # => a Mail::Message object
#
# Action Mailer is nicely integrated with Active Job so you can generate and send emails in the background
# (example: outside of the request-response cycle, so the user doesn't have to wait on it):
#
# NotifierMailer.welcome(User.first).deliver_later # enqueue the email sending to Active Job
#
# Note that <tt>deliver_later</tt> will execute your method from the background job.
#
# You never instantiate your mailer class. Rather, you just call the method you defined on the class itself.
# All instance methods are expected to return a message object to be sent.
#
# = Multipart Emails
#
# Multipart messages can also be used implicitly because Action Mailer will automatically detect and use
# multipart templates, where each template is named after the name of the action, followed by the content
# type. Each such detected template will be added to the message, as a separate part.
#
# For example, if the following templates exist:
# * signup_notification.text.erb
# * signup_notification.html.erb
# * signup_notification.xml.builder
# * signup_notification.yml.erb
#
# Each would be rendered and added as a separate part to the message, with the corresponding content
# type. The content type for the entire message is automatically set to <tt>multipart/alternative</tt>,
# which indicates that the email contains multiple different representations of the same email
# body. The same instance variables defined in the action are passed to all email templates.
#
# Implicit template rendering is not performed if any attachments or parts have been added to the email.
# This means that you'll have to manually add each part to the email and set the content type of the email
# to <tt>multipart/alternative</tt>.
#
# = Attachments
#
# Sending attachment in emails is easy:
#
# class NotifierMailer < ApplicationMailer
# def welcome(recipient)
# attachments['free_book.pdf'] = File.read('path/to/file.pdf')
# mail(to: recipient, subject: "New account information")
# end
# end
#
# Which will (if it had both a <tt>welcome.text.erb</tt> and <tt>welcome.html.erb</tt>
# template in the view directory), send a complete <tt>multipart/mixed</tt> email with two parts,
# the first part being a <tt>multipart/alternative</tt> with the text and HTML email parts inside,
# and the second being a <tt>application/pdf</tt> with a Base64 encoded copy of the file.pdf book
# with the filename +free_book.pdf+.
#
# If you need to send attachments with no content, you need to create an empty view for it,
# or add an empty body parameter like this:
#
# class NotifierMailer < ApplicationMailer
# def welcome(recipient)
# attachments['free_book.pdf'] = File.read('path/to/file.pdf')
# mail(to: recipient, subject: "New account information", body: "")
# end
# end
#
# You can also send attachments with html template, in this case you need to add body, attachments,
# and custom content type like this:
#
# class NotifierMailer < ApplicationMailer
# def welcome(recipient)
# attachments["free_book.pdf"] = File.read("path/to/file.pdf")
# mail(to: recipient,
# subject: "New account information",
# content_type: "text/html",
# body: "<html><body>Hello there</body></html>")
# end
# end
#
# = Inline Attachments
#
# You can also specify that a file should be displayed inline with other HTML. This is useful
# if you want to display a corporate logo or a photo.
#
# class NotifierMailer < ApplicationMailer
# def welcome(recipient)
# attachments.inline['photo.png'] = File.read('path/to/photo.png')
# mail(to: recipient, subject: "Here is what we look like")
# end
# end
#
# And then to reference the image in the view, you create a <tt>welcome.html.erb</tt> file and
# make a call to +image_tag+ passing in the attachment you want to display and then call
# +url+ on the attachment to get the relative content id path for the image source:
#
# <h1>Please Don't Cringe</h1>
#
# <%= image_tag attachments['photo.png'].url -%>
#
# As we are using Action View's +image_tag+ method, you can pass in any other options you want:
#
# <h1>Please Don't Cringe</h1>
#
# <%= image_tag attachments['photo.png'].url, alt: 'Our Photo', class: 'photo' -%>
#
# = Observing and Intercepting Mails
#
# Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to
# register classes that are called during the mail delivery life cycle.
#
# An observer class must implement the <tt>:delivered_email(message)</tt> method which will be
# called once for every email sent after the email has been sent.
#
# An interceptor class must implement the <tt>:delivering_email(message)</tt> method which will be
# called before the email is sent, allowing you to make modifications to the email before it hits
# the delivery agents. Your class should make any needed modifications directly to the passed
# in <tt>Mail::Message</tt> instance.
#
# = Default Hash
#
# Action Mailer provides some intelligent defaults for your emails, these are usually specified in a
# default method inside the class definition:
#
# class NotifierMailer < ApplicationMailer
# default sender: 'system@example.com'
# end
#
# You can pass in any header value that a <tt>Mail::Message</tt> accepts. Out of the box,
# <tt>ActionMailer::Base</tt> sets the following:
#
# * <tt>mime_version: "1.0"</tt>
# * <tt>charset: "UTF-8"</tt>
# * <tt>content_type: "text/plain"</tt>
# * <tt>parts_order: [ "text/plain", "text/enriched", "text/html" ]</tt>
#
# <tt>parts_order</tt> and <tt>charset</tt> are not actually valid <tt>Mail::Message</tt> header fields,
# but Action Mailer translates them appropriately and sets the correct values.
#
# As you can pass in any header, you need to either quote the header as a string, or pass it in as
# an underscored symbol, so the following will work:
#
# class NotifierMailer < ApplicationMailer
# default 'Content-Transfer-Encoding' => '7bit',
# content_description: 'This is a description'
# end
#
# Finally, Action Mailer also supports passing <tt>Proc</tt> and <tt>Lambda</tt> objects into the default hash,
# so you can define methods that evaluate as the message is being generated:
#
# class NotifierMailer < ApplicationMailer
# default 'X-Special-Header' => Proc.new { my_method }, to: -> { @inviter.email_address }
#
# private
# def my_method
# 'some complex call'
# end
# end
#
# Note that the proc/lambda is evaluated right at the start of the mail message generation, so if you
# set something in the default hash using a proc, and then set the same thing inside of your
# mailer method, it will get overwritten by the mailer method.
#
# It is also possible to set these default options that will be used in all mailers through
# the <tt>default_options=</tt> configuration in <tt>config/application.rb</tt>:
#
# config.action_mailer.default_options = { from: "no-reply@example.org" }
#
# = Callbacks
#
# You can specify callbacks using <tt>before_action</tt> and <tt>after_action</tt> for configuring your messages.
# This may be useful, for example, when you want to add default inline attachments for all
# messages sent out by a certain mailer class:
#
# class NotifierMailer < ApplicationMailer
# before_action :add_inline_attachment!
#
# def welcome
# end
#
# private
# def add_inline_attachment!
# attachments.inline["footer.jpg"] = File.read('/path/to/filename.jpg')
# end
# end
#
# Callbacks in Action Mailer are implemented using
# <tt>AbstractController::Callbacks</tt>, so you can define and configure
# callbacks in the same manner that you would use callbacks in classes that
# inherit from <tt>ActionController::Base</tt>.
#
# Note that unless you have a specific reason to do so, you should prefer
# using <tt>before_action</tt> rather than <tt>after_action</tt> in your
# Action Mailer classes so that headers are parsed properly.
#
# = Previewing emails
#
# You can preview your email templates visually by adding a mailer preview file to the
# <tt>ActionMailer::Base.preview_path</tt>. Since most emails do something interesting
# with database data, you'll need to write some scenarios to load messages with fake data:
#
# class NotifierMailerPreview < ActionMailer::Preview
# def welcome
# NotifierMailer.welcome(User.first)
# end
# end
#
# Methods must return a <tt>Mail::Message</tt> object which can be generated by calling the mailer
# method without the additional <tt>deliver_now</tt> / <tt>deliver_later</tt>. The location of the
# mailer previews directory can be configured using the <tt>preview_path</tt> option which has a default
# of <tt>test/mailers/previews</tt>:
#
# config.action_mailer.preview_path = "#{Rails.root}/lib/mailer_previews"
#
# An overview of all previews is accessible at <tt>http://localhost:3000/rails/mailers</tt>
# on a running development server instance.
#
# Previews can also be intercepted in a similar manner as deliveries can be by registering
# a preview interceptor that has a <tt>previewing_email</tt> method:
#
# class CssInlineStyler
# def self.previewing_email(message)
# # inline CSS styles
# end
# end
#
# config.action_mailer.preview_interceptors :css_inline_styler
#
# Note that interceptors need to be registered both with <tt>register_interceptor</tt>
# and <tt>register_preview_interceptor</tt> if they should operate on both sending and
# previewing emails.
#
# = Configuration options
#
# These options are specified on the class level, like
# <tt>ActionMailer::Base.raise_delivery_errors = true</tt>
#
# * <tt>default_options</tt> - You can pass this in at a class level as well as within the class itself as
# per the above section.
#
# * <tt>logger</tt> - the logger is used for generating information on the mailing run if available.
# Can be set to +nil+ for no logging. Compatible with both Ruby's own +Logger+ and Log4r loggers.
#
# * <tt>smtp_settings</tt> - Allows detailed configuration for <tt>:smtp</tt> delivery method:
# * <tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default
# "localhost" setting.
# * <tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.
# * <tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.
# * <tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.
# * <tt>:password</tt> - If your mail server requires authentication, set the password in this setting.
# * <tt>:authentication</tt> - If your mail server requires authentication, you need to specify the
# authentication type here.
# This is a symbol and one of <tt>:plain</tt> (will send the password Base64 encoded), <tt>:login</tt> (will
# send the password Base64 encoded) or <tt>:cram_md5</tt> (combines a Challenge/Response mechanism to exchange
# information and a cryptographic Message Digest 5 algorithm to hash important information)
# * <tt>:enable_starttls_auto</tt> - Detects if STARTTLS is enabled in your SMTP server and starts
# to use it. Defaults to <tt>true</tt>.
# * <tt>:openssl_verify_mode</tt> - When using TLS, you can set how OpenSSL checks the certificate. This is
# really useful if you need to validate a self-signed and/or a wildcard certificate. You can use the name
# of an OpenSSL verify constant (<tt>'none'</tt> or <tt>'peer'</tt>) or directly the constant
# (<tt>OpenSSL::SSL::VERIFY_NONE</tt> or <tt>OpenSSL::SSL::VERIFY_PEER</tt>).
# * <tt>:ssl/:tls</tt> Enables the SMTP connection to use SMTP/TLS (SMTPS: SMTP over direct TLS connection)
#
# * <tt>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method.
# * <tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.
# * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i</tt> with <tt>-f sender@address</tt>
# added automatically before the message is sent.
#
# * <tt>file_settings</tt> - Allows you to override options for the <tt>:file</tt> delivery method.
# * <tt>:location</tt> - The directory into which emails will be written. Defaults to the application
# <tt>tmp/mails</tt>.
#
# * <tt>raise_delivery_errors</tt> - Whether or not errors should be raised if the email fails to be delivered.
#
# * <tt>delivery_method</tt> - Defines a delivery method. Possible values are <tt>:smtp</tt> (default),
# <tt>:sendmail</tt>, <tt>:test</tt>, and <tt>:file</tt>. Or you may provide a custom delivery method
# object e.g. +MyOwnDeliveryMethodClass+. See the Mail gem documentation on the interface you need to
# implement for a custom delivery agent.
#
# * <tt>perform_deliveries</tt> - Determines whether emails are actually sent from Action Mailer when you
# call <tt>.deliver</tt> on an email message or on an Action Mailer method. This is on by default but can
# be turned off to aid in functional testing.
#
# * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with
# <tt>delivery_method :test</tt>. Most useful for unit and functional testing.
#
# * <tt>deliver_later_queue_name</tt> - The name of the queue used with <tt>deliver_later</tt>. Defaults to +mailers+.
- 1
class Base < AbstractController::Base
- 1
include DeliveryMethods
- 1
include Rescuable
- 1
include Parameterized
- 1
include Previews
- 1
abstract!
- 1
include AbstractController::Rendering
- 1
include AbstractController::Logger
- 1
include AbstractController::Helpers
- 1
include AbstractController::Translation
- 1
include AbstractController::AssetPaths
- 1
include AbstractController::Callbacks
- 1
include AbstractController::Caching
- 1
include ActionView::Layouts
- 1
PROTECTED_IVARS = AbstractController::Rendering::DEFAULT_PROTECTED_INSTANCE_VARIABLES + [:@_action_has_layout]
- 1
helper ActionMailer::MailHelper
- 1
class_attribute :delivery_job, default: ::ActionMailer::DeliveryJob
- 1
class_attribute :default_params, default: {
mime_version: "1.0",
charset: "UTF-8",
content_type: "text/plain",
parts_order: [ "text/plain", "text/enriched", "text/html" ]
}.freeze
- 1
class << self
# Register one or more Observers which will be notified when mail is delivered.
- 1
def register_observers(*observers)
- 3
observers.flatten.compact.each { |observer| register_observer(observer) }
end
# Unregister one or more previously registered Observers.
- 1
def unregister_observers(*observers)
- 3
observers.flatten.compact.each { |observer| unregister_observer(observer) }
end
# Register one or more Interceptors which will be called before mail is sent.
- 1
def register_interceptors(*interceptors)
- 3
interceptors.flatten.compact.each { |interceptor| register_interceptor(interceptor) }
end
# Unregister one or more previously registered Interceptors.
- 1
def unregister_interceptors(*interceptors)
- 3
interceptors.flatten.compact.each { |interceptor| unregister_interceptor(interceptor) }
end
# Register an Observer which will be notified when mail is delivered.
# Either a class, string or symbol can be passed in as the Observer.
# If a string or symbol is passed in it will be camelized and constantized.
- 1
def register_observer(observer)
- 5
Mail.register_observer(observer_class_for(observer))
end
# Unregister a previously registered Observer.
# Either a class, string or symbol can be passed in as the Observer.
# If a string or symbol is passed in it will be camelized and constantized.
- 1
def unregister_observer(observer)
- 5
Mail.unregister_observer(observer_class_for(observer))
end
# Register an Interceptor which will be called before mail is sent.
# Either a class, string or symbol can be passed in as the Interceptor.
# If a string or symbol is passed in it will be camelized and constantized.
- 1
def register_interceptor(interceptor)
- 5
Mail.register_interceptor(observer_class_for(interceptor))
end
# Unregister a previously registered Interceptor.
# Either a class, string or symbol can be passed in as the Interceptor.
# If a string or symbol is passed in it will be camelized and constantized.
- 1
def unregister_interceptor(interceptor)
- 5
Mail.unregister_interceptor(observer_class_for(interceptor))
end
- 1
def observer_class_for(value) # :nodoc:
- 20
case value
when String, Symbol
- 12
value.to_s.camelize.constantize
else
- 8
value
end
end
- 1
private :observer_class_for
# Returns the name of the current mailer. This method is also being used as a path for a view lookup.
# If this is an anonymous mailer, this method will return +anonymous+ instead.
- 1
def mailer_name
- 555
@mailer_name ||= anonymous? ? "anonymous" : name.underscore
end
# Allows to set the name of current mailer.
- 1
attr_writer :mailer_name
- 1
alias :controller_path :mailer_name
# Sets the defaults through app configuration:
#
# config.action_mailer.default(from: "no-reply@example.org")
#
# Aliased by ::default_options=
- 1
def default(value = nil)
- 206
self.default_params = default_params.merge(value).freeze if value
- 206
default_params
end
# Allows to set defaults through app configuration:
#
# config.action_mailer.default_options = { from: "no-reply@example.org" }
- 1
alias :default_options= :default
# Wraps an email delivery inside of <tt>ActiveSupport::Notifications</tt> instrumentation.
#
# This method is actually called by the <tt>Mail::Message</tt> object itself
# through a callback when you call <tt>:deliver</tt> on the <tt>Mail::Message</tt>,
# calling +deliver_mail+ directly and passing a <tt>Mail::Message</tt> will do
# nothing except tell the logger you sent the email.
- 1
def deliver_mail(mail) #:nodoc:
- 74
ActiveSupport::Notifications.instrument("deliver.action_mailer") do |payload|
- 74
set_payload_for_mail(payload, mail)
- 74
yield # Let Mail do the delivery actions
end
end
# Returns an email in the format "Name <email@example.com>".
- 1
def email_address_with_name(address, name)
Mail::Address.new.tap do |builder|
- 3
builder.address = address
- 3
builder.display_name = name
- 3
end.to_s
end
- 1
private
- 1
def set_payload_for_mail(payload, mail)
- 74
payload[:mail] = mail.encoded
- 74
payload[:mailer] = name
- 74
payload[:message_id] = mail.message_id
- 74
payload[:subject] = mail.subject
- 74
payload[:to] = mail.to
- 74
payload[:from] = mail.from
- 74
payload[:bcc] = mail.bcc if mail.bcc.present?
- 74
payload[:cc] = mail.cc if mail.cc.present?
- 74
payload[:date] = mail.date
- 74
payload[:perform_deliveries] = mail.perform_deliveries
end
- 1
def method_missing(method_name, *args)
- 224
if action_methods.include?(method_name.to_s)
- 223
MessageDelivery.new(self, method_name, *args)
else
- 1
super
end
end
- 1
ruby2_keywords(:method_missing) if respond_to?(:ruby2_keywords, true)
- 1
def respond_to_missing?(method, include_all = false)
- 12
action_methods.include?(method.to_s) || super
end
end
- 1
attr_internal :message
- 1
def initialize
- 216
super()
- 216
@_mail_was_called = false
- 216
@_message = Mail.new
end
- 1
def process(method_name, *args) #:nodoc:
- 188
payload = {
mailer: self.class.name,
action: method_name,
args: args
}
- 188
ActiveSupport::Notifications.instrument("process.action_mailer", payload) do
- 188
super
- 181
@_message = NullMail.new unless @_mail_was_called
end
end
- 1
class NullMail #:nodoc:
- 2
def body; "" end
- 1
def header; {} end
- 1
def respond_to?(string, include_all = false)
- 1
true
end
- 1
def method_missing(*args)
nil
end
end
# Returns the name of the mailer object.
- 1
def mailer_name
- 25
self.class.mailer_name
end
# Returns an email in the format "Name <email@example.com>".
- 1
def email_address_with_name(address, name)
- 1
self.class.email_address_with_name(address, name)
end
# Allows you to pass random and unusual headers to the new <tt>Mail::Message</tt>
# object which will add them to itself.
#
# headers['X-Special-Domain-Specific-Header'] = "SecretValue"
#
# You can also pass a hash into headers of header field names and values,
# which will then be set on the <tt>Mail::Message</tt> object:
#
# headers 'X-Special-Domain-Specific-Header' => "SecretValue",
# 'In-Reply-To' => incoming.message_id
#
# The resulting <tt>Mail::Message</tt> will have the following in its header:
#
# X-Special-Domain-Specific-Header: SecretValue
#
# Note about replacing already defined headers:
#
# * +subject+
# * +sender+
# * +from+
# * +to+
# * +cc+
# * +bcc+
# * +reply-to+
# * +orig-date+
# * +message-id+
# * +references+
#
# Fields can only appear once in email headers while other fields such as
# <tt>X-Anything</tt> can appear multiple times.
#
# If you want to replace any header which already exists, first set it to
# +nil+ in order to reset the value otherwise another field will be added
# for the same header.
- 1
def headers(args = nil)
- 43
if args
- 4
@_message.headers(args)
else
- 39
@_message
end
end
# Allows you to add attachments to an email, like so:
#
# mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
#
# If you do this, then Mail will take the file name and work out the mime type.
# It will also set the Content-Type, Content-Disposition, Content-Transfer-Encoding
# and encode the contents of the attachment in Base64.
#
# You can also specify overrides if you want by passing a hash instead of a string:
#
# mail.attachments['filename.jpg'] = {mime_type: 'application/gzip',
# content: File.read('/path/to/filename.jpg')}
#
# If you want to use encoding other than Base64 then you will need to pass encoding
# type along with the pre-encoded content as Mail doesn't know how to decode the
# data:
#
# file_content = SpecialEncode(File.read('/path/to/filename.jpg'))
# mail.attachments['filename.jpg'] = {mime_type: 'application/gzip',
# encoding: 'SpecialEncoding',
# content: file_content }
#
# You can also search for specific attachments:
#
# # By Filename
# mail.attachments['filename.jpg'] # => Mail::Part object or nil
#
# # or by index
# mail.attachments[0] # => Mail::Part (first attachment)
#
- 1
def attachments
- 26
if @_mail_was_called
- 4
LateAttachmentsProxy.new(@_message.attachments)
else
- 22
@_message.attachments
end
end
- 1
class LateAttachmentsProxy < SimpleDelegator
- 3
def inline; self end
- 3
def []=(_name, _content); _raise_error end
- 1
private
- 1
def _raise_error
- 2
raise RuntimeError, "Can't add attachments after `mail` was called.\n" \
"Make sure to use `attachments[]=` before calling `mail`."
end
end
# The main method that creates the message and renders the email templates. There are
# two ways to call this method, with a block, or without a block.
#
# It accepts a headers hash. This hash allows you to specify
# the most used headers in an email message, these are:
#
# * +:subject+ - The subject of the message, if this is omitted, Action Mailer will
# ask the Rails I18n class for a translated +:subject+ in the scope of
# <tt>[mailer_scope, action_name]</tt> or if this is missing, will translate the
# humanized version of the +action_name+
# * +:to+ - Who the message is destined for, can be a string of addresses, or an array
# of addresses.
# * +:from+ - Who the message is from
# * +:cc+ - Who you would like to Carbon-Copy on this email, can be a string of addresses,
# or an array of addresses.
# * +:bcc+ - Who you would like to Blind-Carbon-Copy on this email, can be a string of
# addresses, or an array of addresses.
# * +:reply_to+ - Who to set the Reply-To header of the email to.
# * +:date+ - The date to say the email was sent on.
#
# You can set default values for any of the above headers (except +:date+)
# by using the ::default class method:
#
# class Notifier < ActionMailer::Base
# default from: 'no-reply@test.lindsaar.net',
# bcc: 'email_logger@test.lindsaar.net',
# reply_to: 'bounces@test.lindsaar.net'
# end
#
# If you need other headers not listed above, you can either pass them in
# as part of the headers hash or use the <tt>headers['name'] = value</tt>
# method.
#
# When a +:return_path+ is specified as header, that value will be used as
# the 'envelope from' address for the Mail message. Setting this is useful
# when you want delivery notifications sent to a different address than the
# one in +:from+. Mail will actually use the +:return_path+ in preference
# to the +:sender+ in preference to the +:from+ field for the 'envelope
# from' value.
#
# If you do not pass a block to the +mail+ method, it will find all
# templates in the view paths using by default the mailer name and the
# method name that it is being called from, it will then create parts for
# each of these templates intelligently, making educated guesses on correct
# content type and sequence, and return a fully prepared <tt>Mail::Message</tt>
# ready to call <tt>:deliver</tt> on to send.
#
# For example:
#
# class Notifier < ActionMailer::Base
# default from: 'no-reply@test.lindsaar.net'
#
# def welcome
# mail(to: 'mikel@test.lindsaar.net')
# end
# end
#
# Will look for all templates at "app/views/notifier" with name "welcome".
# If no welcome template exists, it will raise an ActionView::MissingTemplate error.
#
# However, those can be customized:
#
# mail(template_path: 'notifications', template_name: 'another')
#
# And now it will look for all templates at "app/views/notifications" with name "another".
#
# If you do pass a block, you can render specific templates of your choice:
#
# mail(to: 'mikel@test.lindsaar.net') do |format|
# format.text
# format.html
# end
#
# You can even render plain text directly without using a template:
#
# mail(to: 'mikel@test.lindsaar.net') do |format|
# format.text { render plain: "Hello Mikel!" }
# format.html { render html: "<h1>Hello Mikel!</h1>".html_safe }
# end
#
# Which will render a +multipart/alternative+ email with +text/plain+ and
# +text/html+ parts.
#
# The block syntax also allows you to customize the part headers if desired:
#
# mail(to: 'mikel@test.lindsaar.net') do |format|
# format.text(content_transfer_encoding: "base64")
# format.html
# end
#
- 1
def mail(headers = {}, &block)
- 193
return message if @_mail_was_called && headers.blank? && !block
# At the beginning, do not consider class default for content_type
- 191
content_type = headers[:content_type]
- 191
headers = apply_defaults(headers)
# Apply charset at the beginning so all fields are properly quoted
- 191
message.charset = charset = headers[:charset]
# Set configure delivery behavior
- 191
wrap_delivery_behavior!(headers[:delivery_method], headers[:delivery_method_options])
- 189
assign_headers_to_message(message, headers)
# Render the templates and blocks
- 189
responses = collect_responses(headers, &block)
- 187
@_mail_was_called = true
- 187
create_parts_from_responses(message, responses)
- 187
wrap_inline_attachments(message)
# Set up content type, reapply charset and handle parts order
- 187
message.content_type = set_content_type(message, content_type, headers[:content_type])
- 187
message.charset = charset
- 187
if message.multipart?
- 39
message.body.set_sort_order(headers[:parts_order])
- 39
message.body.sort_parts!
end
- 187
message
end
- 1
private
# Used by #mail to set the content type of the message.
#
# It will use the given +user_content_type+, or multipart if the mail
# message has any attachments. If the attachments are inline, the content
# type will be "multipart/related", otherwise "multipart/mixed".
#
# If there is no content type passed in via headers, and there are no
# attachments, or the message is multipart, then the default content type is
# used.
- 1
def set_content_type(m, user_content_type, class_default) # :doc:
- 187
params = m.content_type_parameters || {}
case
when user_content_type.present?
- 5
user_content_type
when m.has_attachments?
- 15
if m.attachments.all?(&:inline?)
- 3
["multipart", "related", params]
else
- 12
["multipart", "mixed", params]
end
when m.multipart?
- 22
["multipart", "alternative", params]
else
- 145
m.content_type || class_default
- 187
end
end
# Translates the +subject+ using Rails I18n class under <tt>[mailer_scope, action_name]</tt> scope.
# If it does not find a translation for the +subject+ under the specified scope it will default to a
# humanized version of the <tt>action_name</tt>.
# If the subject has interpolations, you can pass them through the +interpolations+ parameter.
- 1
def default_i18n_subject(interpolations = {}) # :doc:
- 93
mailer_scope = self.class.mailer_name.tr("/", ".")
- 93
I18n.t(:subject, **interpolations.merge(scope: [mailer_scope, action_name], default: action_name.humanize))
end
# Emails do not support relative path links.
- 1
def self.supports_path? # :doc:
- 22
false
end
- 1
def apply_defaults(headers)
- 191
default_values = self.class.default.transform_values do |value|
- 1099
compute_default(value)
end
- 191
headers_with_defaults = headers.reverse_merge(default_values)
- 191
headers_with_defaults[:subject] ||= default_i18n_subject
- 191
headers_with_defaults
end
- 1
def compute_default(value)
- 1099
return value unless value.is_a?(Proc)
- 43
if value.arity == 1
- 14
instance_exec(self, &value)
else
- 29
instance_exec(&value)
end
end
- 1
def assign_headers_to_message(message, headers)
- 189
assignable = headers.except(:parts_order, :content_type, :body, :template_name,
:template_path, :delivery_method, :delivery_method_options)
- 1231
assignable.each { |k, v| message[k] = v }
end
- 1
def collect_responses(headers, &block)
- 189
if block_given?
- 28
collect_responses_from_block(headers, &block)
- 161
elsif headers[:body]
- 49
collect_responses_from_text(headers)
else
- 112
collect_responses_from_templates(headers)
end
end
- 1
def collect_responses_from_block(headers)
- 28
templates_name = headers[:template_name] || action_name
- 34
collector = ActionMailer::Collector.new(lookup_context) { render(templates_name) }
- 28
yield(collector)
- 27
collector.responses
end
- 1
def collect_responses_from_text(headers)
- 49
[{
body: headers.delete(:body),
content_type: headers[:content_type] || "text/plain"
}]
end
- 1
def collect_responses_from_templates(headers)
- 112
templates_path = headers[:template_path] || self.class.mailer_name
- 112
templates_name = headers[:template_name] || action_name
- 112
each_template(Array(templates_path), templates_name).map do |template|
- 124
format = template.format || self.formats.first
- 124
{
body: render(template: template, formats: [format]),
content_type: Mime[format].to_s
}
end
end
- 1
def each_template(paths, name, &block)
- 112
templates = lookup_context.find_all(name, paths)
- 112
if templates.empty?
- 1
raise ActionView::MissingTemplate.new(paths, name, paths, false, "mailer")
else
- 111
templates.uniq(&:format).each(&block)
end
end
- 1
def wrap_inline_attachments(message)
# If we have both types of attachment, wrap all the inline attachments
# in multipart/related, but not the actual attachments
- 193
if message.attachments.detect(&:inline?) && message.attachments.detect { |a| !a.inline? }
- 1
related = Mail::Part.new
- 1
related.content_type = "multipart/related"
- 1
mixed = [ related ]
- 1
message.parts.each do |p|
- 3
if p.attachment? && !p.inline?
- 1
mixed << p
else
- 2
related.add_part(p)
end
end
- 1
message.parts.clear
- 3
mixed.each { |c| message.add_part(c) }
end
end
- 1
def create_parts_from_responses(m, responses)
- 187
if responses.size == 1 && !m.has_attachments?
- 445
responses[0].each { |k, v| m[k] = v }
- 39
elsif responses.size > 1 && m.has_attachments?
- 5
container = Mail::Part.new
- 5
container.content_type = "multipart/alternative"
- 15
responses.each { |r| insert_part(container, r, m.charset) }
- 5
m.add_part(container)
else
- 91
responses.each { |r| insert_part(m, r, m.charset) }
end
end
- 1
def insert_part(container, response, charset)
- 67
response[:charset] ||= charset
- 67
part = Mail::Part.new(response)
- 67
container.add_part(part)
end
# This and #instrument_name is for caching instrument
- 1
def instrument_payload(key)
- 23
{
mailer: mailer_name,
key: key
}
end
- 1
def instrument_name
- 23
"action_mailer"
end
- 1
def _protected_ivars
- 189
PROTECTED_IVARS
end
- 1
ActiveSupport.run_load_hooks(:action_mailer, self)
end
end
# frozen_string_literal: true
- 1
require "abstract_controller/collector"
- 1
require "active_support/core_ext/hash/reverse_merge"
- 1
require "active_support/core_ext/array/extract_options"
- 1
module ActionMailer
- 1
class Collector
- 1
include AbstractController::Collector
- 1
attr_reader :responses
- 1
def initialize(context, &block)
- 28
@context = context
- 28
@responses = []
- 28
@default_render = block
end
- 1
def any(*args, &block)
- 2
options = args.extract_options!
- 2
raise ArgumentError, "You have to supply at least one format" if args.empty?
- 3
args.each { |type| send(type, options.dup, &block) }
end
- 1
alias :all :any
- 1
def custom(mime, options = {})
- 42
options.reverse_merge!(content_type: mime.to_s)
- 42
@context.formats = [mime.to_sym]
- 42
options[:body] = block_given? ? yield : @default_render.call
- 42
@responses << options
end
end
end
# frozen_string_literal: true
- 1
require "active_job"
- 1
module ActionMailer
# The <tt>ActionMailer::DeliveryJob</tt> class is used when you
# want to send emails outside of the request-response cycle.
#
# Exceptions are rescued and handled by the mailer class.
- 1
class DeliveryJob < ActiveJob::Base # :nodoc:
- 5
queue_as { ActionMailer::Base.deliver_later_queue_name }
- 1
rescue_from StandardError, with: :handle_exception_with_mailer_class
- 1
before_perform do
- 2
ActiveSupport::Deprecation.warn <<~MSG.squish
Sending mail with DeliveryJob and Parameterized::DeliveryJob
is deprecated and will be removed in Rails 6.1.
Please use MailDeliveryJob instead.
MSG
end
- 1
def perform(mailer, mail_method, delivery_method, *args) #:nodoc:
- 1
mailer.constantize.public_send(mail_method, *args).send(delivery_method)
end
- 1
ruby2_keywords(:perform) if respond_to?(:ruby2_keywords, true)
- 1
private
# "Deserialize" the mailer class name by hand in case another argument
# (like a Global ID reference) raised DeserializationError.
- 1
def mailer_class
if mailer = Array(@serialized_arguments).first || Array(arguments).first
mailer.constantize
end
end
- 1
def handle_exception_with_mailer_class(exception)
if klass = mailer_class
klass.handle_exception exception
else
raise exception
end
end
end
end
# frozen_string_literal: true
- 1
require "tmpdir"
- 1
module ActionMailer
# This module handles everything related to mail delivery, from registering
# new delivery methods to configuring the mail object to be sent.
- 1
module DeliveryMethods
- 1
extend ActiveSupport::Concern
- 1
included do
# Do not make this inheritable, because we always want it to propagate
- 1
cattr_accessor :raise_delivery_errors, default: true
- 1
cattr_accessor :perform_deliveries, default: true
- 1
cattr_accessor :deliver_later_queue_name, default: :mailers
- 1
class_attribute :delivery_methods, default: {}.freeze
- 1
class_attribute :delivery_method, default: :smtp
- 1
add_delivery_method :smtp, Mail::SMTP,
address: "localhost",
port: 25,
domain: "localhost.localdomain",
user_name: nil,
password: nil,
authentication: nil,
enable_starttls_auto: true
- 1
add_delivery_method :file, Mail::FileDelivery,
- 1
location: defined?(Rails.root) ? "#{Rails.root}/tmp/mails" : "#{Dir.tmpdir}/mails"
- 1
add_delivery_method :sendmail, Mail::Sendmail,
location: "/usr/sbin/sendmail",
arguments: "-i"
- 1
add_delivery_method :test, Mail::TestMailer
end
# Helpers for creating and wrapping delivery behavior, used by DeliveryMethods.
- 1
module ClassMethods
# Provides a list of emails that have been delivered by Mail::TestMailer
- 1
delegate :deliveries, :deliveries=, to: Mail::TestMailer
# Adds a new delivery method through the given class using the given
# symbol as alias and the default options supplied.
#
# add_delivery_method :sendmail, Mail::Sendmail,
# location: '/usr/sbin/sendmail',
# arguments: '-i'
- 1
def add_delivery_method(symbol, klass, default_options = {})
- 10
class_attribute(:"#{symbol}_settings") unless respond_to?(:"#{symbol}_settings")
- 10
send(:"#{symbol}_settings=", default_options)
- 10
self.delivery_methods = delivery_methods.merge(symbol.to_sym => klass).freeze
end
- 1
def wrap_delivery_behavior(mail, method = nil, options = nil) # :nodoc:
- 191
method ||= delivery_method
- 191
mail.delivery_handler = self
- 191
case method
when NilClass
- 1
raise "Delivery method cannot be nil"
when Symbol
- 186
if klass = delivery_methods[method]
- 185
mail.delivery_method(klass, (send(:"#{method}_settings") || {}).merge(options || {}))
else
- 1
raise "Invalid delivery method #{method.inspect}"
end
else
- 4
mail.delivery_method(method)
end
- 189
mail.perform_deliveries = perform_deliveries
- 189
mail.raise_delivery_errors = raise_delivery_errors
end
end
- 1
def wrap_delivery_behavior!(*args) # :nodoc:
- 191
self.class.wrap_delivery_behavior(message, *args)
end
end
end
# frozen_string_literal: true
- 1
module ActionMailer
# Returns the version of the currently loaded Action Mailer as a <tt>Gem::Version</tt>.
- 1
def self.gem_version
Gem::Version.new VERSION::STRING
end
- 1
module VERSION
- 1
MAJOR = 6
- 1
MINOR = 1
- 1
TINY = 0
- 1
PRE = "alpha"
- 1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
end
# frozen_string_literal: true
- 1
require "base64"
- 1
module ActionMailer
# Implements a mailer preview interceptor that converts image tag src attributes
# that use inline cid: style URLs to data: style URLs so that they are visible
# when previewing an HTML email in a web browser.
#
# This interceptor is enabled by default. To disable it, delete it from the
# <tt>ActionMailer::Base.preview_interceptors</tt> array:
#
# ActionMailer::Base.preview_interceptors.delete(ActionMailer::InlinePreviewInterceptor)
#
- 1
class InlinePreviewInterceptor
- 1
PATTERN = /src=(?:"cid:[^"]+"|'cid:[^']+')/i
- 1
include Base64
- 1
def self.previewing_email(message) #:nodoc:
- 3
new(message).transform!
end
- 1
def initialize(message) #:nodoc:
- 3
@message = message
end
- 1
def transform! #:nodoc:
- 3
return message if html_part.blank?
html_part.body = html_part.decoded.gsub(PATTERN) do |match|
if part = find_part(match[9..-2])
%[src="#{data_url(part)}"]
else
match
end
end
message
end
- 1
private
- 1
attr_reader :message
- 1
def html_part
- 3
@html_part ||= message.html_part
end
- 1
def data_url(part)
"data:#{part.mime_type};base64,#{strict_encode64(part.body.raw_source)}"
end
- 1
def find_part(cid)
message.all_parts.find { |p| p.attachment? && p.cid == cid }
end
end
end
# frozen_string_literal: true
- 1
require "active_support/log_subscriber"
- 1
module ActionMailer
# Implements the ActiveSupport::LogSubscriber for logging notifications when
# email is delivered or received.
- 1
class LogSubscriber < ActiveSupport::LogSubscriber
# An email was delivered.
- 1
def deliver(event)
- 2
info do
- 2
perform_deliveries = event.payload[:perform_deliveries]
- 2
if perform_deliveries
- 1
"Delivered mail #{event.payload[:message_id]} (#{event.duration.round(1)}ms)"
else
- 1
"Skipped delivery of mail #{event.payload[:message_id]} as `perform_deliveries` is false"
end
end
- 4
debug { event.payload[:mail] }
end
# An email was generated.
- 1
def process(event)
- 2
debug do
- 2
mailer = event.payload[:mailer]
- 2
action = event.payload[:action]
- 2
"#{mailer}##{action}: processed outbound mail in #{event.duration.round(1)}ms"
end
end
# Use the logger configured for ActionMailer::Base.
- 1
def logger
- 128
ActionMailer::Base.logger
end
end
end
- 1
ActionMailer::LogSubscriber.attach_to :action_mailer
# frozen_string_literal: true
- 1
require "active_job"
- 1
module ActionMailer
# The <tt>ActionMailer::MailDeliveryJob</tt> class is used when you
# want to send emails outside of the request-response cycle. It supports
# sending either parameterized or normal mail.
#
# Exceptions are rescued and handled by the mailer class.
- 1
class MailDeliveryJob < ActiveJob::Base # :nodoc:
- 33
queue_as { ActionMailer::Base.deliver_later_queue_name }
- 1
rescue_from StandardError, with: :handle_exception_with_mailer_class
- 1
def perform(mailer, mail_method, delivery_method, args:, kwargs: nil, params: nil)
- 18
mailer_class = params ? mailer.constantize.with(params) : mailer.constantize
- 18
message = if kwargs
mailer_class.public_send(mail_method, *args, **kwargs)
else
- 18
mailer_class.public_send(mail_method, *args)
end
- 18
message.send(delivery_method)
end
- 1
private
# "Deserialize" the mailer class name by hand in case another argument
# (like a Global ID reference) raised DeserializationError.
- 1
def mailer_class
- 2
if mailer = Array(@serialized_arguments).first || Array(arguments).first
- 2
mailer.constantize
end
end
- 1
def handle_exception_with_mailer_class(exception)
- 2
if klass = mailer_class
- 2
klass.handle_exception exception
else
raise exception
end
end
end
end
# frozen_string_literal: true
- 1
module ActionMailer
# Provides helper methods for ActionMailer::Base that can be used for easily
# formatting messages, accessing mailer or message instances, and the
# attachments list.
- 1
module MailHelper
# Take the text and format it, indented two spaces for each line, and
# wrapped at 72 columns:
#
# text = <<-TEXT
# This is
# the paragraph.
#
# * item1 * item2
# TEXT
#
# block_format text
# # => " This is the paragraph.\n\n * item1\n * item2\n"
- 1
def block_format(text)
- 2
formatted = text.split(/\n\r?\n/).collect { |paragraph|
- 4
format_paragraph(paragraph)
}.join("\n\n")
# Make list points stand on their own line
- 5
formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { " #{$1} #{$2.strip}\n" }
- 2
formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { " #{$1} #{$2.strip}\n" }
- 2
formatted
end
# Access the mailer instance.
- 1
def mailer
- 6
@_controller
end
# Access the message instance.
- 1
def message
- 1
@_message
end
# Access the message attachments list.
- 1
def attachments
- 5
mailer.attachments
end
# Returns +text+ wrapped at +len+ columns and indented +indent+ spaces.
# By default column length +len+ equals 72 characters and indent
# +indent+ equal two spaces.
#
# my_text = 'Here is a sample text with more than 40 characters'
#
# format_paragraph(my_text, 25, 4)
# # => " Here is a sample text with\n more than 40 characters"
- 1
def format_paragraph(text, len = 72, indent = 2)
- 6
sentences = [[]]
- 6
text.split.each do |word|
- 94
if sentences.first.present? && (sentences.last + [word]).join(" ").length > len
- 9
sentences << [word]
else
- 85
sentences.last << word
end
end
- 6
indentation = " " * indent
- 6
sentences.map! { |sentence|
- 15
"#{indentation}#{sentence.join(' ')}"
}.join "\n"
end
end
end
# frozen_string_literal: true
- 1
require "delegate"
- 1
module ActionMailer
# The <tt>ActionMailer::MessageDelivery</tt> class is used by
# ActionMailer::Base when creating a new mailer.
# <tt>MessageDelivery</tt> is a wrapper (+Delegator+ subclass) around a lazy
# created <tt>Mail::Message</tt>. You can get direct access to the
# <tt>Mail::Message</tt>, deliver the email or schedule the email to be sent
# through Active Job.
#
# Notifier.welcome(User.first) # an ActionMailer::MessageDelivery object
# Notifier.welcome(User.first).deliver_now # sends the email
# Notifier.welcome(User.first).deliver_later # enqueue email delivery as a job through Active Job
# Notifier.welcome(User.first).message # a Mail::Message object
- 1
class MessageDelivery < Delegator
- 1
def initialize(mailer_class, action, *args) #:nodoc:
- 238
@mailer_class, @action, @args = mailer_class, action, args
# The mail is only processed if we try to call any methods on it.
# Typical usage will leave it unloaded and call deliver_later.
- 238
@processed_mailer = nil
- 238
@mail_message = nil
end
- 1
ruby2_keywords(:initialize) if respond_to?(:ruby2_keywords, true)
# Method calls are delegated to the Mail::Message that's ready to deliver.
- 1
def __getobj__ #:nodoc:
- 406
@mail_message ||= processed_mailer.message
end
# Unused except for delegator internals (dup, marshalling).
- 1
def __setobj__(mail_message) #:nodoc:
- 10
@mail_message = mail_message
end
# Returns the resulting Mail::Message
- 1
def message
- 87
__getobj__
end
# Was the delegate loaded, causing the mailer action to be processed?
- 1
def processed?
- 38
@processed_mailer || @mail_message
end
# Enqueues the email to be delivered through Active Job. When the
# job runs it will send the email using +deliver_now!+. That means
# that the message will be sent bypassing checking +perform_deliveries+
# and +raise_delivery_errors+, so use with caution.
#
# Notifier.welcome(User.first).deliver_later!
# Notifier.welcome(User.first).deliver_later!(wait: 1.hour)
# Notifier.welcome(User.first).deliver_later!(wait_until: 10.hours.from_now)
# Notifier.welcome(User.first).deliver_later!(priority: 10)
#
# Options:
#
# * <tt>:wait</tt> - Enqueue the email to be delivered with a delay
# * <tt>:wait_until</tt> - Enqueue the email to be delivered at (after) a specific date / time
# * <tt>:queue</tt> - Enqueue the email on the specified queue
# * <tt>:priority</tt> - Enqueues the email with the specified priority
#
# By default, the email will be enqueued using <tt>ActionMailer::DeliveryJob</tt>. Each
# <tt>ActionMailer::Base</tt> class can specify the job to use by setting the class variable
# +delivery_job+.
#
# class AccountRegistrationMailer < ApplicationMailer
# self.delivery_job = RegistrationDeliveryJob
# end
- 1
def deliver_later!(options = {})
- 2
enqueue_delivery :deliver_now!, options
end
# Enqueues the email to be delivered through Active Job. When the
# job runs it will send the email using +deliver_now+.
#
# Notifier.welcome(User.first).deliver_later
# Notifier.welcome(User.first).deliver_later(wait: 1.hour)
# Notifier.welcome(User.first).deliver_later(wait_until: 10.hours.from_now)
# Notifier.welcome(User.first).deliver_later(priority: 10)
#
# Options:
#
# * <tt>:wait</tt> - Enqueue the email to be delivered with a delay.
# * <tt>:wait_until</tt> - Enqueue the email to be delivered at (after) a specific date / time.
# * <tt>:queue</tt> - Enqueue the email on the specified queue.
# * <tt>:priority</tt> - Enqueues the email with the specified priority
#
# By default, the email will be enqueued using <tt>ActionMailer::DeliveryJob</tt>. Each
# <tt>ActionMailer::Base</tt> class can specify the job to use by setting the class variable
# +delivery_job+.
#
# class AccountRegistrationMailer < ApplicationMailer
# self.delivery_job = RegistrationDeliveryJob
# end
- 1
def deliver_later(options = {})
- 36
enqueue_delivery :deliver_now, options
end
# Delivers an email without checking +perform_deliveries+ and +raise_delivery_errors+,
# so use with caution.
#
# Notifier.welcome(User.first).deliver_now!
#
- 1
def deliver_now!
- 2
processed_mailer.handle_exceptions do
- 2
message.deliver!
end
end
# Delivers an email:
#
# Notifier.welcome(User.first).deliver_now
#
- 1
def deliver_now
- 81
processed_mailer.handle_exceptions do
- 77
message.deliver
end
end
- 1
private
# Returns the processed Mailer instance. We keep this instance
# on hand so we can delegate exception handling to it.
- 1
def processed_mailer
- 256
@processed_mailer ||= @mailer_class.new.tap do |mailer|
- 182
mailer.process @action, *@args
end
end
- 1
def enqueue_delivery(delivery_method, options = {})
- 30
if processed?
- 1
::Kernel.raise "You've accessed the message before asking to " \
"deliver it later, so you may have made local changes that would " \
"be silently lost if we enqueued a job to deliver it. Why? Only " \
"the mailer method *arguments* are passed with the delivery job! " \
"Do not access the message in any way if you mean to deliver it " \
"later. Workarounds: 1. don't touch the message before calling " \
"#deliver_later, 2. only touch the message *within your mailer " \
"method*, or 3. use a custom Active Job instead of #deliver_later."
else
- 29
job = @mailer_class.delivery_job
- 29
if job <= MailDeliveryJob
- 27
job.set(options).perform_later(
@mailer_class.name, @action.to_s, delivery_method.to_s, args: @args)
else
- 2
job.set(options).perform_later(
@mailer_class.name, @action.to_s, delivery_method.to_s, *@args)
end
end
end
end
end
# frozen_string_literal: true
- 1
module ActionMailer
# Provides the option to parameterize mailers in order to share instance variable
# setup, processing, and common headers.
#
# Consider this example that does not use parameterization:
#
# class InvitationsMailer < ApplicationMailer
# def account_invitation(inviter, invitee)
# @account = inviter.account
# @inviter = inviter
# @invitee = invitee
#
# subject = "#{@inviter.name} invited you to their Basecamp (#{@account.name})"
#
# mail \
# subject: subject,
# to: invitee.email_address,
# from: common_address(inviter),
# reply_to: inviter.email_address_with_name
# end
#
# def project_invitation(project, inviter, invitee)
# @account = inviter.account
# @project = project
# @inviter = inviter
# @invitee = invitee
# @summarizer = ProjectInvitationSummarizer.new(@project.bucket)
#
# subject = "#{@inviter.name.familiar} added you to a project in Basecamp (#{@account.name})"
#
# mail \
# subject: subject,
# to: invitee.email_address,
# from: common_address(inviter),
# reply_to: inviter.email_address_with_name
# end
#
# def bulk_project_invitation(projects, inviter, invitee)
# @account = inviter.account
# @projects = projects.sort_by(&:name)
# @inviter = inviter
# @invitee = invitee
#
# subject = "#{@inviter.name.familiar} added you to some new stuff in Basecamp (#{@account.name})"
#
# mail \
# subject: subject,
# to: invitee.email_address,
# from: common_address(inviter),
# reply_to: inviter.email_address_with_name
# end
# end
#
# InvitationsMailer.account_invitation(person_a, person_b).deliver_later
#
# Using parameterized mailers, this can be rewritten as:
#
# class InvitationsMailer < ApplicationMailer
# before_action { @inviter, @invitee = params[:inviter], params[:invitee] }
# before_action { @account = params[:inviter].account }
#
# default to: -> { @invitee.email_address },
# from: -> { common_address(@inviter) },
# reply_to: -> { @inviter.email_address_with_name }
#
# def account_invitation
# mail subject: "#{@inviter.name} invited you to their Basecamp (#{@account.name})"
# end
#
# def project_invitation
# @project = params[:project]
# @summarizer = ProjectInvitationSummarizer.new(@project.bucket)
#
# mail subject: "#{@inviter.name.familiar} added you to a project in Basecamp (#{@account.name})"
# end
#
# def bulk_project_invitation
# @projects = params[:projects].sort_by(&:name)
#
# mail subject: "#{@inviter.name.familiar} added you to some new stuff in Basecamp (#{@account.name})"
# end
# end
#
# InvitationsMailer.with(inviter: person_a, invitee: person_b).account_invitation.deliver_later
- 1
module Parameterized
- 1
extend ActiveSupport::Concern
- 1
included do
- 1
attr_accessor :params
end
- 1
module ClassMethods
# Provide the parameters to the mailer in order to use them in the instance methods and callbacks.
#
# InvitationsMailer.with(inviter: person_a, invitee: person_b).account_invitation.deliver_later
#
# See Parameterized documentation for full example.
- 1
def with(params)
- 16
ActionMailer::Parameterized::Mailer.new(self, params)
end
end
- 1
class Mailer # :nodoc:
- 1
def initialize(mailer, params)
- 16
@mailer, @params = mailer, params
end
- 1
private
- 1
def method_missing(method_name, *args)
- 15
if @mailer.action_methods.include?(method_name.to_s)
- 15
ActionMailer::Parameterized::MessageDelivery.new(@mailer, method_name, @params, *args)
else
super
end
end
- 1
ruby2_keywords(:method_missing) if respond_to?(:ruby2_keywords, true)
- 1
def respond_to_missing?(method, include_all = false)
- 4
@mailer.respond_to?(method, include_all)
end
end
- 1
class DeliveryJob < ActionMailer::DeliveryJob # :nodoc:
- 1
def perform(mailer, mail_method, delivery_method, params, *args)
- 1
mailer.constantize.with(params).public_send(mail_method, *args).send(delivery_method)
end
- 1
ruby2_keywords(:perform) if respond_to?(:ruby2_keywords, true)
end
- 1
class MessageDelivery < ActionMailer::MessageDelivery # :nodoc:
- 1
def initialize(mailer_class, action, params, *args)
- 15
super(mailer_class, action, *args)
- 15
@params = params
end
- 1
ruby2_keywords(:initialize) if respond_to?(:ruby2_keywords, true)
- 1
private
- 1
def processed_mailer
- 11
@processed_mailer ||= @mailer_class.new.tap do |mailer|
- 6
mailer.params = @params
- 6
mailer.process @action, *@args
end
end
- 1
def enqueue_delivery(delivery_method, options = {})
- 8
if processed?
super
else
- 8
job = delivery_job_class
- 8
if job <= MailDeliveryJob
- 6
job.set(options).perform_later(
@mailer_class.name, @action.to_s, delivery_method.to_s, params: @params, args: @args)
else
- 2
job.set(options).perform_later(
@mailer_class.name, @action.to_s, delivery_method.to_s, @params, *@args)
end
end
end
- 1
def delivery_job_class
- 8
if @mailer_class.delivery_job <= MailDeliveryJob
- 6
@mailer_class.delivery_job
else
- 2
Parameterized::DeliveryJob
end
end
end
end
end
# frozen_string_literal: true
- 1
require "active_support/descendants_tracker"
- 1
module ActionMailer
- 1
module Previews #:nodoc:
- 1
extend ActiveSupport::Concern
- 1
included do
# Set the location of mailer previews through app configuration:
#
# config.action_mailer.preview_path = "#{Rails.root}/lib/mailer_previews"
#
- 1
mattr_accessor :preview_path, instance_writer: false
# Enable or disable mailer previews through app configuration:
#
# config.action_mailer.show_previews = true
#
# Defaults to +true+ for development environment
#
- 1
mattr_accessor :show_previews, instance_writer: false
# :nodoc:
- 1
mattr_accessor :preview_interceptors, instance_writer: false, default: [ActionMailer::InlinePreviewInterceptor]
end
- 1
module ClassMethods
# Register one or more Interceptors which will be called before mail is previewed.
- 1
def register_preview_interceptors(*interceptors)
- 3
interceptors.flatten.compact.each { |interceptor| register_preview_interceptor(interceptor) }
end
# Unregister one or more previously registered Interceptors.
- 1
def unregister_preview_interceptors(*interceptors)
- 3
interceptors.flatten.compact.each { |interceptor| unregister_preview_interceptor(interceptor) }
end
# Register an Interceptor which will be called before mail is previewed.
# Either a class or a string can be passed in as the Interceptor. If a
# string is passed in it will be constantized.
- 1
def register_preview_interceptor(interceptor)
- 5
preview_interceptor = interceptor_class_for(interceptor)
- 5
unless preview_interceptors.include?(preview_interceptor)
- 5
preview_interceptors << preview_interceptor
end
end
# Unregister a previously registered Interceptor.
# Either a class or a string can be passed in as the Interceptor. If a
# string is passed in it will be constantized.
- 1
def unregister_preview_interceptor(interceptor)
- 5
preview_interceptors.delete(interceptor_class_for(interceptor))
end
- 1
private
- 1
def interceptor_class_for(interceptor)
- 10
case interceptor
when String, Symbol
- 6
interceptor.to_s.camelize.constantize
else
- 4
interceptor
end
end
end
end
- 1
class Preview
- 1
extend ActiveSupport::DescendantsTracker
- 1
attr_reader :params
- 1
def initialize(params = {})
- 10
@params = params
end
- 1
class << self
# Returns all mailer preview classes.
- 1
def all
load_previews if descendants.empty?
descendants
end
# Returns the mail object for the given email name. The registered preview
# interceptors will be informed so that they can transform the message
# as they would if the mail was actually being delivered.
- 1
def call(email, params = {})
- 10
preview = new(params)
- 10
message = preview.public_send(email)
- 10
inform_preview_interceptors(message)
- 10
message
end
# Returns all of the available email previews.
- 1
def emails
public_instance_methods(false).map(&:to_s).sort
end
# Returns +true+ if the email exists.
- 1
def email_exists?(email)
emails.include?(email)
end
# Returns +true+ if the preview exists.
- 1
def exists?(preview)
all.any? { |p| p.preview_name == preview }
end
# Find a mailer preview by its underscored class name.
- 1
def find(preview)
all.find { |p| p.preview_name == preview }
end
# Returns the underscored name of the mailer preview without the suffix.
- 1
def preview_name
name.delete_suffix("Preview").underscore
end
- 1
private
- 1
def load_previews
if preview_path
Dir["#{preview_path}/**/*_preview.rb"].sort.each { |file| require_dependency file }
end
end
- 1
def preview_path
Base.preview_path
end
- 1
def show_previews
Base.show_previews
end
- 1
def inform_preview_interceptors(message)
- 10
Base.preview_interceptors.each do |interceptor|
- 8
interceptor.previewing_email(message)
end
end
end
end
end
# frozen_string_literal: true
require "active_job/railtie"
require "action_mailer"
require "rails"
require "abstract_controller/railties/routes_helpers"
module ActionMailer
class Railtie < Rails::Railtie # :nodoc:
config.action_mailer = ActiveSupport::OrderedOptions.new
config.eager_load_namespaces << ActionMailer
initializer "action_mailer.logger" do
ActiveSupport.on_load(:action_mailer) { self.logger ||= Rails.logger }
end
initializer "action_mailer.set_configs" do |app|
paths = app.config.paths
options = app.config.action_mailer
options.assets_dir ||= paths["public"].first
options.javascripts_dir ||= paths["public/javascripts"].first
options.stylesheets_dir ||= paths["public/stylesheets"].first
options.show_previews = Rails.env.development? if options.show_previews.nil?
options.cache_store ||= Rails.cache
if options.show_previews
options.preview_path ||= defined?(Rails.root) ? "#{Rails.root}/test/mailers/previews" : nil
end
# make sure readers methods get compiled
options.asset_host ||= app.config.asset_host
options.relative_url_root ||= app.config.relative_url_root
ActiveSupport.on_load(:action_mailer) do
include AbstractController::UrlFor
extend ::AbstractController::Railties::RoutesHelpers.with(app.routes, false)
include app.routes.mounted_helpers
register_interceptors(options.delete(:interceptors))
register_preview_interceptors(options.delete(:preview_interceptors))
register_observers(options.delete(:observers))
if delivery_job = options.delete(:delivery_job)
self.delivery_job = delivery_job.constantize
end
options.each { |k, v| send("#{k}=", v) }
end
ActiveSupport.on_load(:action_dispatch_integration_test) do
include ActionMailer::TestHelper
include ActionMailer::TestCase::ClearTestDeliveries
end
end
initializer "action_mailer.set_autoload_paths" do |app|
options = app.config.action_mailer
if options.show_previews && options.preview_path
ActiveSupport::Dependencies.autoload_paths << options.preview_path
end
end
initializer "action_mailer.compile_config_methods" do
ActiveSupport.on_load(:action_mailer) do
config.compile_methods! if config.respond_to?(:compile_methods!)
end
end
initializer "action_mailer.eager_load_actions" do
ActiveSupport.on_load(:after_initialize) do
ActionMailer::Base.descendants.each(&:action_methods) if config.eager_load
end
end
config.after_initialize do |app|
options = app.config.action_mailer
if options.show_previews
app.routes.prepend do
get "/rails/mailers" => "rails/mailers#index", internal: true
get "/rails/mailers/*path" => "rails/mailers#preview", internal: true
end
end
end
end
end
# frozen_string_literal: true
- 1
module ActionMailer #:nodoc:
# Provides +rescue_from+ for mailers. Wraps mailer action processing,
# mail job processing, and mail delivery.
- 1
module Rescuable
- 1
extend ActiveSupport::Concern
- 1
include ActiveSupport::Rescuable
- 1
class_methods do
- 1
def handle_exception(exception) #:nodoc:
- 2
rescue_with_handler(exception) || raise(exception)
end
end
- 1
def handle_exceptions #:nodoc:
- 267
yield
rescue => exception
- 10
rescue_with_handler(exception) || raise
end
- 1
private
- 1
def process(*)
- 188
handle_exceptions do
- 188
super
end
end
end
end
# frozen_string_literal: true
- 1
require "active_support/test_case"
- 1
require "rails-dom-testing"
- 1
module ActionMailer
- 1
class NonInferrableMailerError < ::StandardError
- 1
def initialize(name)
- 1
super "Unable to determine the mailer to test from #{name}. " \
"You'll need to specify it using tests YourMailer in your " \
"test case definition"
end
end
- 1
class TestCase < ActiveSupport::TestCase
- 1
module ClearTestDeliveries
- 1
extend ActiveSupport::Concern
- 1
included do
- 1
setup :clear_test_deliveries
- 1
teardown :clear_test_deliveries
end
- 1
private
- 1
def clear_test_deliveries
- 2
if ActionMailer::Base.delivery_method == :test
- 2
ActionMailer::Base.deliveries.clear
end
end
end
- 1
module Behavior
- 1
extend ActiveSupport::Concern
- 1
include ActiveSupport::Testing::ConstantLookup
- 1
include TestHelper
- 1
include Rails::Dom::Testing::Assertions::SelectorAssertions
- 1
include Rails::Dom::Testing::Assertions::DomAssertions
- 1
included do
- 1
class_attribute :_mailer_class
- 1
setup :initialize_test_deliveries
- 1
setup :set_expected_mail
- 1
teardown :restore_test_deliveries
- 1
ActiveSupport.run_load_hooks(:action_mailer_test_case, self)
end
- 1
module ClassMethods
- 1
def tests(mailer)
- 5
case mailer
when String, Symbol
- 2
self._mailer_class = mailer.to_s.camelize.constantize
when Module
- 3
self._mailer_class = mailer
else
raise NonInferrableMailerError.new(mailer)
end
end
- 1
def mailer_class
- 5
if mailer = _mailer_class
- 4
mailer
else
- 1
tests determine_default_mailer(name)
end
end
- 1
def determine_default_mailer(name)
- 2
mailer = determine_constant_from_test_name(name) do |constant|
- 2
Class === constant && constant < ActionMailer::Base
end
- 2
raise NonInferrableMailerError.new(name) if mailer.nil?
- 1
mailer
end
end
- 1
private
- 1
def initialize_test_deliveries
- 56
set_delivery_method :test
- 56
@old_perform_deliveries = ActionMailer::Base.perform_deliveries
- 56
ActionMailer::Base.perform_deliveries = true
- 56
ActionMailer::Base.deliveries.clear
end
- 1
def restore_test_deliveries
- 56
restore_delivery_method
- 56
ActionMailer::Base.perform_deliveries = @old_perform_deliveries
end
- 1
def set_delivery_method(method)
- 56
@old_delivery_method = ActionMailer::Base.delivery_method
- 56
ActionMailer::Base.delivery_method = method
end
- 1
def restore_delivery_method
- 58
ActionMailer::Base.deliveries.clear
- 58
ActionMailer::Base.delivery_method = @old_delivery_method
end
- 1
def set_expected_mail
- 56
@expected = Mail.new
- 56
@expected.content_type ["text", "plain", { "charset" => charset }]
- 56
@expected.mime_version = "1.0"
end
- 1
def charset
- 58
"UTF-8"
end
- 1
def encode(subject)
- 1
Mail::Encodings.q_value_encode(subject, charset)
end
- 1
def read_fixture(action)
- 1
IO.readlines(File.join(Rails.root, "test", "fixtures", self.class.mailer_class.name.underscore, action))
end
end
- 1
include Behavior
end
end
# frozen_string_literal: true
- 1
require "active_job"
- 1
module ActionMailer
# Provides helper methods for testing Action Mailer, including #assert_emails
# and #assert_no_emails.
- 1
module TestHelper
- 1
include ActiveJob::TestHelper
# Asserts that the number of emails sent matches the given number.
#
# def test_emails
# assert_emails 0
# ContactMailer.welcome.deliver_now
# assert_emails 1
# ContactMailer.welcome.deliver_now
# assert_emails 2
# end
#
# If a block is passed, that block should cause the specified number of
# emails to be sent.
#
# def test_emails_again
# assert_emails 1 do
# ContactMailer.welcome.deliver_now
# end
#
# assert_emails 2 do
# ContactMailer.welcome.deliver_now
# ContactMailer.welcome.deliver_later
# end
# end
- 1
def assert_emails(number, &block)
- 14
if block_given?
- 12
original_count = ActionMailer::Base.deliveries.size
- 16
perform_enqueued_jobs(only: ->(job) { delivery_job_filter(job) }, &block)
- 12
new_count = ActionMailer::Base.deliveries.size
- 12
assert_equal number, new_count - original_count, "#{number} emails expected, but #{new_count - original_count} were sent"
else
- 2
assert_equal number, ActionMailer::Base.deliveries.size
end
end
# Asserts that no emails have been sent.
#
# def test_emails
# assert_no_emails
# ContactMailer.welcome.deliver_now
# assert_emails 1
# end
#
# If a block is passed, that block should not cause any emails to be sent.
#
# def test_emails_again
# assert_no_emails do
# # No emails should be sent from this block
# end
# end
#
# Note: This assertion is simply a shortcut for:
#
# assert_emails 0, &block
- 1
def assert_no_emails(&block)
- 3
assert_emails 0, &block
end
# Asserts that the number of emails enqueued for later delivery matches
# the given number.
#
# def test_emails
# assert_enqueued_emails 0
# ContactMailer.welcome.deliver_later
# assert_enqueued_emails 1
# ContactMailer.welcome.deliver_later
# assert_enqueued_emails 2
# end
#
# If a block is passed, that block should cause the specified number of
# emails to be enqueued.
#
# def test_emails_again
# assert_enqueued_emails 1 do
# ContactMailer.welcome.deliver_later
# end
#
# assert_enqueued_emails 2 do
# ContactMailer.welcome.deliver_later
# ContactMailer.welcome.deliver_later
# end
# end
- 1
def assert_enqueued_emails(number, &block)
- 19
assert_enqueued_jobs(number, only: ->(job) { delivery_job_filter(job) }, &block)
end
# Asserts that a specific email has been enqueued, optionally
# matching arguments.
#
# def test_email
# ContactMailer.welcome.deliver_later
# assert_enqueued_email_with ContactMailer, :welcome
# end
#
# def test_email_with_arguments
# ContactMailer.welcome("Hello", "Goodbye").deliver_later
# assert_enqueued_email_with ContactMailer, :welcome, args: ["Hello", "Goodbye"]
# end
#
# If a block is passed, that block should cause the specified email
# to be enqueued.
#
# def test_email_in_block
# assert_enqueued_email_with ContactMailer, :welcome do
# ContactMailer.welcome.deliver_later
# end
# end
#
# If +args+ is provided as a Hash, a parameterized email is matched.
#
# def test_parameterized_email
# assert_enqueued_email_with ContactMailer, :welcome,
# args: {email: 'user@example.com'} do
# ContactMailer.with(email: 'user@example.com').welcome.deliver_later
# end
# end
- 1
def assert_enqueued_email_with(mailer, method, args: nil, queue: "mailers", &block)
- 7
args = if args.is_a?(Hash)
- 2
[mailer.to_s, method.to_s, "deliver_now", params: args, args: []]
else
- 5
[mailer.to_s, method.to_s, "deliver_now", args: Array(args)]
end
- 7
assert_enqueued_with(job: mailer.delivery_job, args: args, queue: queue, &block)
end
# Asserts that no emails are enqueued for later delivery.
#
# def test_no_emails
# assert_no_enqueued_emails
# ContactMailer.welcome.deliver_later
# assert_enqueued_emails 1
# end
#
# If a block is provided, it should not cause any emails to be enqueued.
#
# def test_no_emails
# assert_no_enqueued_emails do
# # No emails should be enqueued from this block
# end
# end
- 1
def assert_no_enqueued_emails(&block)
- 3
assert_enqueued_emails 0, &block
end
- 1
private
- 1
def delivery_job_filter(job)
- 13
job_class = job.is_a?(Hash) ? job.fetch(:job) : job.class
- 13
Base.descendants.map(&:delivery_job).include?(job_class) ||
ActionMailer::Parameterized::DeliveryJob == job_class
end
end
end
# frozen_string_literal: true
- 1
require_relative "gem_version"
- 1
module ActionMailer
# Returns the version of the currently loaded Action Mailer as a
# <tt>Gem::Version</tt>.
- 1
def self.version
gem_version
end
end
# frozen_string_literal: true
module Rails
module Generators
class MailerGenerator < NamedBase
source_root File.expand_path("templates", __dir__)
argument :actions, type: :array, default: [], banner: "method method"
check_class_collision suffix: "Mailer"
def create_mailer_file
template "mailer.rb", File.join("app/mailers", class_path, "#{file_name}_mailer.rb")
in_root do
if behavior == :invoke && !File.exist?(application_mailer_file_name)
template "application_mailer.rb", application_mailer_file_name
end
end
end
hook_for :template_engine, :test_framework
private
def file_name # :doc:
@_file_name ||= super.sub(/_mailer\z/i, "")
end
def application_mailer_file_name
@_application_mailer_file_name ||= if mountable_engine?
"app/mailers/#{namespaced_path}/application_mailer.rb"
else
"app/mailers/application_mailer.rb"
end
end
end
end
end