skip to content

Mailer & Mailbox

Rails handles email both ways: Action Mailer renders and delivers outbound messages, and Action Mailbox receives inbound mail and routes it to mailbox classes. Interviewers probe delivery and routing.

part ofRuby on Railsread it →
on this pageshow

explore

questions

12

In Rails Action Mailer, what is the difference between deliver_now and deliver_later, and where does the mailer action actually run?

level: juniorimportance: must knowfreq 74%

answer

  1. the class call returns a lazy wrapper
  2. ActionMailer::MailDeliveryJob
  3. only class name, action and args travel
  4. load_defaults sets the queue name to nil
  5. touching the message first raises

basics

~10 s

deliver_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 lines
ruby
class 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
end

go deeper

for a junior

Say that deliver_now sends during the request and deliver_later hands the work to a background job, and use deliver_later from controllers.

for a middle

Explain the lazy MessageDelivery, what MailDeliveryJob receives, why arguments are reloaded in the worker, and which queue a new app uses.

for a senior

Watch transactions, deleted records and queue routing: enqueue after commit, handle deserialization failures and give mail its own queue when volumes demand it.

for a principal

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.

open as a page

In Rails 8.1, what does bin/rails generate mailer Order confirmation create, and how do mail() and its templates build the email?

level: juniorimportance: must knowfreq 62%

basics

~20 s

The generator writes OrderMailer with a confirmation action, text and HTML views under app/views/order_mailer, a test and a preview. Calling mail(to:, subject:) merges the class defaults, renders every confirmation template inside the mailer layout and returns a multipart message.

open as a page

In Rails Action Mailbox, how do routing rules in ApplicationMailbox match an inbound email, and what happens when none match?

level: middleimportance: should knowfreq 24%

basics

~20 s

ApplicationMailbox's routing rules map an address matcher to a mailbox name, and the first rule that matches wins. Strings and regexps are compared with every recipient; with no match the email is marked bounced and ActionMailbox::Router::RoutingError is raised.

open as a page

In Rails Action Mailbox, what happens to an inbound email between the ingress request and a mailbox's process method?

level: middleimportance: should knowfreq 28%

basics

~20 s

The configured ingress controller saves the raw message as an InboundEmail with status pending and answers at once. A RoutingJob then asks ApplicationMailbox for the first matching route and runs that mailbox's callbacks and process, updating the status.

open as a page

In Rails Action Mailer, how does OrderMailer.with(order: order).confirmation work, and what must its params hold for deliver_later?

level: middleimportance: should knowfreq 42%

basics

~20 s

with(params) returns a proxy whose action calls build a parameterized delivery; inside the mailer, params is readable in actions, before_action callbacks and default lambdas. deliver_later passes that hash to the job, so every value must be Active Job serializable.

open as a page

In a Rails mailer, how do you attach a generated PDF receipt, and why must attachments[]= run before mail is called?

level: middleimportance: should knowfreq 44%

basics

~20 s

Assign attachments["receipt-1042.pdf"] = pdf_bytes in the action before calling mail; Rails guesses the MIME type and Base64-encodes it. After mail has run, attachments rejects writes with a RuntimeError, because mail already built the message parts.

open as a page

In an Action Mailbox mailbox, how do before_processing, bounce_with and bounced! reject a forwarded receipt from an unknown sender?

level: seniorimportance: should knowfreq 20%

basics

~10 s

Check the sender in a before_processing callback; calling bounce_with(SomeMailer.action(inbound_email)) marks the email bounced, enqueues the reply and halts the chain so process never runs. bounced! halts the same way without sending anything.

open as a page

How do Action Mailer's delivery_method, interceptors and preview settings keep a Rails staging server from emailing real furniture-store customers?

level: seniorimportance: should knowfreq 32%

basics

~10 s

Pick the delivery_method per environment, and register an interceptor whose delivering_email(message) rewrites recipients before every send on staging. Keep previews development-only, because show_previews defaults to development and staging previews render real records.

open as a page

In Rails 8.1, what is Action Mailbox for, and what do bin/rails action_mailbox:install and bin/rails generate mailbox add?

level: juniorimportance: nice to knowfreq 20%

basics

~20 s

Action Mailbox receives email into a Rails app and routes each message to a mailbox class whose process method handles it. The installer adds ApplicationMailbox and the migrations; generate mailbox adds a mailbox class with process and a test.

open as a page

In a Rails mailbox test, how does receive_inbound_email_from_mail differ from create_inbound_email_from_mail, and what does each exercise?

level: middleimportance: nice to knowfreq 16%

basics

~10 s

create_inbound_email_from_mail only builds and saves an InboundEmail, with status processing by default. receive_inbound_email_from_mail does the same and then routes it immediately, so ApplicationMailbox's rules, callbacks and process all run inside the test.

open as a page

In Rails Action Mailbox, what is incineration, when does it delete an InboundEmail, and what must a mailbox do before then?

level: seniorimportance: nice to knowfreq 15%

basics

~10 s

Incineration deletes processed InboundEmails and their raw messages after config.action_mailbox.incinerate_after, 30 days by default. A mailbox must copy everything the app needs, attachments included, into its own models before then.

open as a page