In Rails Action Mailer, what is the difference between deliver_now and deliver_later, and where does the mailer action actually run?
answer
- the class call returns a lazy wrapper
- ActionMailer::MailDeliveryJob
- only class name, action and args travel
- load_defaults sets the queue name to nil
- touching the message first raises
basics
~10 sdeliver_now runs the mailer action, renders and sends the email in the current process. deliver_later enqueues ActionMailer::MailDeliveryJob with the mailer name, action and arguments, and the worker runs the action and sends it later.
solid answer
~40 s`OrderMailer.confirmation(order)` returns an `ActionMailer::MessageDelivery`, a lazy wrapper: the action has not run yet. `deliver_now` instantiates the mailer, runs the action, renders the templates and hands the message to the delivery method inside the current request, so the customer waits on the mail server. `deliver_later` enqueues `ActionMailer::MailDeliveryJob` with only the mailer class name, the action name and the serialized arguments; the worker re-runs the action and renders there. On a Rails 8.1 app with `load_defaults 8.1`, `deliver_later_queue_name` is `nil`, so the job lands on Active Job's `"default"` queue. If you read the message before calling `deliver_later`, Rails raises, because your changes would be lost.
code
ruby · 12 linesclass OrdersController < ApplicationController
def create
@order = Order.new(params.expect(order: [:product_id, :quantity, :email]))
if @order.save
OrderMailer.confirmation(@order).deliver_later
redirect_to @order, notice: "Order placed"
else
render :new, status: :unprocessable_content
end
end
endgo deeper
Say that deliver_now sends during the request and deliver_later hands the work to a background job, and use deliver_later from controllers.
Explain the lazy MessageDelivery, what MailDeliveryJob receives, why arguments are reloaded in the worker, and which queue a new app uses.
Watch transactions, deleted records and queue routing: enqueue after commit, handle deserialization failures and give mail its own queue when volumes demand it.
Decide which emails are transactional and must be fast and reliable versus bulk, and size queues, retries and bulk enqueue around that split.
## The lazy wrapper Calling a mailer action on the class, `OrderMailer.confirmation(order)`, does not build an email. It returns an `ActionMailer::MessageDelivery`, a delegator around a `Mail::Message` that is created only when something asks for it. What happens next depends on the method you call on that wrapper. ## `deliver_now`: everything in the current process `deliver_now` runs the whole pipeline synchronously: 1. Instantiate `OrderMailer` and run `confirmation(order)`, which calls `mail`. 2. Render the templates and build the message. 3. Run the `before_deliver` / `after_deliver` callbacks around delivery. 4. Hand the message to the configured `delivery_method`, such as `:smtp`. In a controller this means the furniture store's checkout request waits for the mail server and fails or slows down with it. `deliver_now` is right inside a job you already run in the background, in a console, or when the email must be sent before the code continues. ## `deliver_later`: only a recipe travels `deliver_later` does not render anything. It enqueues `ActionMailer::MailDeliveryJob` (the class held in the mailer's `delivery_job` attribute) with four things: the mailer class name, the action name, the delivery method to call (`"deliver_now"`) and the arguments, plus `params:` for a parameterized mailer. When a worker picks the job up, it looks the class up, calls the action again with the deserialized arguments and calls `deliver_now`. Consequences: - **Arguments must be serializable by Active Job.** An `Order` travels as a Global ID and is reloaded in the worker, so the worker sees the row as it is then, not as it was at enqueue time. - **Rendering happens in the worker.** Expensive work in the action, such as building a PDF receipt, moves off the request too. - **Reading the message first is an error.** Calling `.subject` or `.message` processes the action; a later `deliver_later` then raises a `RuntimeError` explaining that local changes would be silently lost, because only the arguments are passed to the job. - **Options.** `deliver_later(wait: 10.minutes)`, `wait_until:`, `queue:` and `priority:` are passed to the job when it is enqueued. ## Which queue, and when it is enqueued | Setting | Value on a new 8.1 app | |---|---| | `delivery_job` | `ActionMailer::MailDeliveryJob` | | `deliver_later_queue_name` class default | `:mailers` | | after `load_defaults` 6.1 or later | `nil`, so the job uses Active Job's `"default"` queue | | deferred until the transaction commits? | no; `MailDeliveryJob` keeps `enqueue_after_transaction_commit` at `false` | The queue row surprises people: the attribute's own default is `:mailers`, but `config.load_defaults` for 6.1 and later sets `config.action_mailer.deliver_later_queue_name = nil`, and a `nil` queue name resolves to `"default"`. Set it back explicitly, app-wide or per mailer with `self.deliver_later_queue_name = :mailers`, if your worker setup has a dedicated mail queue. The transaction row matters for checkout code. Calling `deliver_later` inside `Order.transaction do ... end` enqueues immediately in 8.1, so a worker can pick the job up before the order commits, or the job can outlive a rollback. Send the email after the transaction block, or from an after-commit hook. ## The bang variants and bulk delivery - `deliver_now!` and `deliver_later!` deliver **without checking** `perform_deliveries` and `raise_delivery_errors`, so they ignore an environment that has switched delivery off. Use them only on purpose. - **New in 8.1:** `ActionMailer.deliver_all_later(deliveries)` enqueues many emails in one call through `ActiveJob.perform_all_later`, cutting round-trips to the queue; adapters without bulk enqueue fall back to one job at a time. ## Choosing between them in practice - **From a controller or model callback:** `deliver_later`. The response no longer waits on the mail server, and a slow or failing server affects the job, not the checkout page. - **Inside a job you already run:** `deliver_now`. Enqueuing a second job from a job only adds latency and another failure point. - **In a console or a one-off script:** `deliver_now`, so you see errors immediately. - **When ordering matters**, for example a receipt that must exist before a follow-up survey: enqueue the first with `deliver_later` and schedule the second with `wait:`, or send both from one job. Failure handling differs too. A `deliver_now` that fails raises in the caller, unless `raise_delivery_errors` is false or a `rescue_from` on the mailer handles it. A failed `deliver_later` raises in the worker, where the queue backend records the failed job and the mailer's `rescue_from` handlers still apply, because `MailDeliveryJob` hands exceptions to the mailer class.
- Why can't you set a header on the message and then call deliver_later?Only the mailer class name, action name and arguments go into `MailDeliveryJob`; the worker rebuilds the message from scratch. Any change made to the in-process message would be lost, so `MessageDelivery` raises a `RuntimeError` if the message was processed before `deliver_later`. Set headers inside the mailer action, or use your own job.
- How do you send 5,000 back-in-stock emails without 5,000 queue round-trips in Rails 8.1?Build the `MessageDelivery` objects without delivering them and pass the array to `ActionMailer.deliver_all_later(deliveries)`, optionally with `queue:`. It builds one `MailDeliveryJob` per email and enqueues them through `ActiveJob.perform_all_later`, which enqueues them in one batch when the adapter implements `enqueue_all`.
- Calling OrderMailer.confirmation(order) sends the email immediately.
- deliver_later serializes the fully rendered email into the job.
- On a new Rails 8.1 app, mail jobs go to the mailers queue.
- deliver_later inside a transaction waits for the commit in Rails 8.1.
- deliver_later! still respects perform_deliveries when the job runs.
Assumes Rails 8.1 with load_defaults 8.1: deliver_later_queue_name is nil (since the 6.1 defaults), enqueues are not deferred to commit, and ActionMailer.deliver_all_later is new in 8.1.