In a Rails mailer, how do you attach a generated PDF receipt, and why must attachments[]= run before mail is called?
answer
- filename key, bytes as value
- MIME type guessed, Base64 by default
- Can't add attachments after mail
- multipart/mixed around multipart/alternative
- attachments.inline plus image_tag url
basics
~20 sAssign 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.
solid answer
~30 sIn the action, assign `attachments["receipt-#{@order.number}.pdf"] = ReceiptPdf.new(@order).render` and then call `mail`. Rails guesses the MIME type from the file name and Base64-encodes the content; pass a hash with `mime_type:`, `content:` and `encoding:` to control them. The order matters because `mail` assembles the parts: with an attachment present it builds a `multipart/mixed` message whose first part is a `multipart/alternative` holding the text and HTML bodies. After `mail` has been called, `attachments` returns a proxy whose `[]=` raises `RuntimeError` ("Can't add attachments after `mail` was called"). For an image shown in the body, use `attachments.inline["logo.png"]` and `image_tag attachments["logo.png"].url` in the view.
code
ruby · 11 linesclass OrderMailer < ApplicationMailer
def confirmation(order)
@order = order
attachments.inline["logo.png"] = File.binread(Rails.root.join("app/assets/images/logo.png"))
attachments["receipt-#{order.number}.pdf"] = {
mime_type: "application/pdf",
content: ReceiptPdf.new(order).render
}
mail to: order.email, subject: "Your receipt for order ##{order.number}"
end
endgo deeper
Show attachments["receipt.pdf"] = bytes inside the action, placed before the mail call.
Explain the late-attachment RuntimeError, the hash form with mime_type and content, and how inline images use a cid URL.
Build the PDF in the worker from the reloaded order, watch message size, and test attachment names and types in mailer tests.
Weigh attaching documents against linking to them behind authentication: attachments are convenient but large, permanent copies outside your control.
## Attaching a file An **attachment** is a file carried inside the email as its own MIME part. In Action Mailer you add one with the `attachments` hash inside the mailer action. For a furniture store sending an order confirmation with a receipt, the action renders the PDF and assigns it under the file name the customer will see: ```ruby def confirmation(order) @order = order attachments["receipt-#{order.number}.pdf"] = ReceiptPdf.new(order).render mail to: order.email, subject: "Your receipt for order ##{order.number}" end ``` `ReceiptPdf` stands for whatever PDF library the app uses; Action Mailer only needs the bytes. Two forms are accepted: - **Name and content.** `attachments["receipt.pdf"] = bytes`: Rails guesses the MIME type from the extension (`application/pdf`) and Base64-encodes the content. - **Name and hash.** `attachments["receipt.pdf"] = { mime_type: "application/pdf", content: bytes }`: you set the type yourself, and if you pass `encoding:` with pre-encoded content, Rails does not encode it again. Read files from disk with `File.binread`, which returns the bytes tagged as binary, the safer choice for PDFs and images. ## Why the order relative to `mail` matters `mail` is the step that turns templates and attachments into a MIME tree. It renders the bodies, then decides the structure from what is already attached: 1. Templates are rendered into one response per format. 2. If attachments exist and there is more than one body, the bodies go into a `multipart/alternative` container. 3. That container and each attachment become parts of the message, which is typed `multipart/mixed`, or `multipart/related` when the only attachments are inline. 4. If there are both inline and regular attachments, the inline ones are wrapped with the bodies in a `multipart/related` part, leaving the regular files beside it. Once `mail` has run, the mailer flags it, and `attachments` returns a `LateAttachmentsProxy`. Reading still works, but `attachments[...] =` raises `RuntimeError`: "Can't add attachments after `mail` was called. Make sure to use `attachments[]=` before calling `mail`." The error is deliberate: a late attachment would not be placed in the already-built tree. | Attachments present | Resulting top-level type | |---|---| | none, text and HTML templates | `multipart/alternative` | | a PDF, text and HTML templates | `multipart/mixed` with a `multipart/alternative` part plus the PDF | | only an inline logo | `multipart/related` | | an inline logo and a PDF | `multipart/mixed` holding a `multipart/related` part and the PDF | ## Inline images A logo shown in the HTML body is an **inline attachment**. Mark it with `attachments.inline["logo.png"] = File.binread(...)` and reference it from the view with `<%= image_tag attachments["logo.png"].url, alt: "Store logo" %>`. The `url` is a `cid:` reference to the part, so the image travels with the message instead of being fetched from your server. The alternative is a normal `image_tag` pointing at a hosted file, which needs `config.action_mailer.asset_host`. ## Practical consequences - **With `deliver_later`, the PDF is built in the worker**, because the action runs there. Pass the order, not the PDF bytes, so the job payload stays small. - **Mind the size.** Base64 makes the attachment roughly a third larger than the file, and receiving servers enforce message size limits. - **Test the parts, not just the body.** The delivered message exposes `attachments`, so a test can assert the file name and content type of the receipt. - **Callbacks can add attachments too**, as long as they run before `mail`: a `before_action` that attaches a terms-of-sale PDF to every order email works, an `after_action` does not. ## Files that already live in Active Storage If the receipt was generated once and stored, attach its bytes rather than rendering again: `attachments[order.receipt.filename.to_s] = order.receipt.download`. `download` reads the whole file into memory, which is fine for a receipt and a poor idea for a large catalogue; for big files, link to them instead of attaching. Templates can also read the message's attachments: the `attachments` view helper returns the same collection, which is how `image_tag attachments["logo.png"].url` works, and a text template can list the attached file names so plain-text readers know what arrived.
- Why should the job receive the order rather than the PDF bytes?`deliver_later` serializes the mailer arguments into the job payload. A Global ID for the order is tiny, while a PDF would bloat every queued job. Because the action runs in the worker, it can render the receipt there from the reloaded order.
- Can an after_action callback add a default attachment to every order email?No. `after_action` runs after the action, and the action has already called `mail`, so `attachments[]=` raises the late-attachment `RuntimeError`. Use a `before_action`, which runs before the action and therefore before `mail`.
- Attachments can be added after mail, since files are added at send time.
- You must Base64-encode the PDF yourself before assigning it.
- With an attachment, the text and HTML bodies become separate alternatives to the PDF.
- An inline logo is shown with image_tag "logo.png" and no asset host.
- An after_action is a good place to add a default attachment.