In Rails 8.1, what does bin/rails generate mailer Order confirmation create, and how do mail() and its templates build the email?
answer
- class, views, test and preview
- default from: plus layout "mailer"
- one template per format, one part each
- text/plain part before text/html
- subject falls back to I18n, then action name
basics
~20 sThe 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.
solid answer
~30 s`bin/rails generate mailer Order confirmation` creates `app/mailers/order_mailer.rb` (a subclass of `ApplicationMailer`), `app/views/order_mailer/confirmation.text.erb` and `.html.erb`, `test/mailers/order_mailer_test.rb` and `test/mailers/previews/order_mailer_preview.rb`, plus `ApplicationMailer` and the `mailer` layouts if they are missing. Inside the action you set instance variables and call `mail(to: @order.email, subject: "Your order")`. `mail` merges the class-level `default` headers (the generated `from:`), finds every template named after the action, renders each inside `layouts/mailer.<format>.erb` and builds a `multipart/alternative` message with the text part first. Leave out `subject:` and Rails looks up `<mailer>.<action>.subject` in I18n, then falls back to the humanized action name.
code
ruby · 12 linesclass OrderMailer < ApplicationMailer
def confirmation(order)
@order = order
return if @order.email.blank?
mail to: @order.email, subject: "Your order ##{@order.number} is confirmed"
end
end
# app/views/order_mailer/confirmation.text.erb
# app/views/order_mailer/confirmation.html.erb
# -> one multipart/alternative email, text part firstgo deeper
Name the files the mailer generator writes and show an action that assigns @order and calls mail with to: and subject:.
Explain how mail merges default headers, discovers one template per format and orders the multipart parts, and how the subject falls back.
Use the null-message behaviour for conditional sends, keep shared headers and layout in ApplicationMailer, and insist on previews with real records.
Argue for a small number of mailers with clear ownership and shared layouts, so brand changes land in one layout instead of dozens of templates.
## What the generator writes Action Mailer is the part of Rails that sends email. A **mailer** is a class under `app/mailers`, and each public instance method is an **action** that builds one kind of email. For a furniture store that confirms orders, `bin/rails generate mailer Order confirmation` writes: - `app/mailers/order_mailer.rb`: `class OrderMailer < ApplicationMailer` with a `confirmation` method that sets `@greeting` and calls `mail to: "[email protected]"`. - `app/views/order_mailer/confirmation.text.erb` and `confirmation.html.erb`: one template per format. - `test/mailers/order_mailer_test.rb` and `test/mailers/previews/order_mailer_preview.rb`, from the test framework hook. - `app/mailers/application_mailer.rb` and `app/views/layouts/mailer.html.erb` / `mailer.text.erb`, only if they do not exist yet. A new app already has them, because `rails new` writes them too. The generated `ApplicationMailer` holds two lines that every mailer inherits: `default from: "[email protected]"` and `layout "mailer"`. The generator strips a trailing `_mailer` from the name, so `generate mailer OrderMailer` still gives `OrderMailer`, not `OrderMailerMailer`. ## How `mail` builds the message You never call `OrderMailer.new`. You call the action on the class, `OrderMailer.confirmation(order)`, and Rails creates the instance, runs the method and keeps the result. Inside the action, `mail` does the work: 1. It merges the headers you pass with the class-level `default` hash. A value you pass wins; a lambda in `default` is evaluated on the mailer instance. 2. If no `:subject` was given, it calls `default_i18n_subject`, which looks up `order_mailer.confirmation.subject` in the current locale and falls back to `"Confirmation"`, the humanized action name. 3. It looks up every template named `confirmation` under `app/views/order_mailer/` (or `template_path:` / `template_name:` if you pass them) and renders each one inside the layout for its format. 4. It turns each rendered template into a part and sorts the parts by `parts_order`, whose default is `text/plain`, then `text/enriched`, then `text/html`. With both a text and an HTML template you get one `multipart/alternative` email whose mail client shows the richest part it can display. With a single template you get a single-part message of that type. ## Templates, formats and the layout | File | Role | |---|---| | `confirmation.html.erb` | HTML body, rendered inside `layouts/mailer.html.erb` | | `confirmation.text.erb` | plain-text body, rendered inside `layouts/mailer.text.erb` | | `layouts/mailer.html.erb` | wrapper with `<%= yield %>`; the generated one has an empty `<style>` block noting that email styles need to be inline | | `ApplicationMailer` | shared `default` headers and the `layout "mailer"` call | Instance variables set in the action, such as `@order`, are visible in both templates, just as in controller views. A block form, `mail(to: ...) { |format| format.html; format.text }`, lets you choose formats or render inline bodies instead of relying on template discovery. ## Edge cases interviewers probe - **No template at all.** If no `confirmation.*` template exists and no block or `body:` is given, `mail` raises `ActionView::MissingTemplate`. - **An action that never calls `mail`.** Rails swaps the message for a null object, so `deliver_now` sends nothing and raises nothing. That makes a guard such as `return if @order.email.blank?` a clean way to skip an email. - **Instance, not class, state.** Each delivery builds a fresh mailer instance; nothing set on one email leaks into the next. - **Mailer views are not controller views.** They have no request, so links need absolute URLs and a configured host, and `*_path` helpers are not available there. ## Seeing the result while you build The generated preview class has one method per action that returns `OrderMailer.confirmation`; in development you open `/rails/mailers/order_mailer/confirmation` and see the rendered email, with a switch between its HTML and text parts. Replace the generated body with a real record, for example `OrderMailer.confirmation(Order.last)`, so the preview renders realistic data. ## Shared headers belong in `ApplicationMailer` Because every mailer inherits from `ApplicationMailer`, it is the natural home for what all of the store's emails share: - **`default from:`** replaces the generated `[email protected]`. `email_address_with_name("[email protected]", "Oak & Pine Furniture")` returns the `Name <address>` form, so the customer sees a store name rather than a bare address. - **`default reply_to:`** sends replies to a monitored inbox instead of a no-reply sender. - **Lambdas in `default`**, such as `default to: -> { @order.email }`, are evaluated per message on the mailer instance, so they can use instance variables the action set. - **Custom headers** go through `headers["X-Order-Number"] = @order.number` inside an action, before `mail`. A subclass can override any of these with its own `default` call or by passing the header to `mail`, which always wins over the class defaults. Keeping the layout and the sender in one place means a rebrand touches two files, not every mailer.
- How do you preview the confirmation email in development?Edit `test/mailers/previews/order_mailer_preview.rb` so its `confirmation` method returns `OrderMailer.confirmation(Order.last)` without calling a deliver method, then open `/rails/mailers/order_mailer/confirmation`. Previews are served only when `show_previews` is true, which defaults to the development environment.
- How would you render the confirmation with templates from another folder?Pass `template_path:` and `template_name:` to `mail`, for example `mail(to: @order.email, template_path: "notifications", template_name: "order_confirmation")`. `template_path` also accepts an array that is searched in order.
A mailer action is like a print shop job ticket: the ticket (the action) names the recipient and subject, and the shop prints every version of the flyer it has on file for that job (each template) inside the same letterhead (the layout), then staples them into one envelope.
- You build the email with OrderMailer.new.confirmation(order).
- Without a subject: key, mail raises an ArgumentError.
- With HTML and text templates, Rails sends only the HTML one.
- Mailers render inside layouts/application.html.erb like controllers.
- An action that skips mail still renders and sends its template.