skip to content

Inbound Email Routing

Action Mailbox accepts inbound email through relay or provider ingresses, stores an InboundEmail, and routes it to mailbox classes by address. Interviewers probe routing, bounces and incineration.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

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%

answer

  1. String, Regexp, Proc, match?, :all
  2. first matching rule wins
  3. to, cc, bcc plus X-Original-To
  4. :receipts becomes ReceiptsMailbox
  5. no match: bounced plus RoutingError

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.

solid answer

~40 s

Each `routing matcher => :name` call in `ApplicationMailbox` appends a route, and the router walks them in declaration order and uses the **first** match. A String matches a recipient exactly but case-insensitively; a Regexp is tried against each recipient; a Proc or lambda receives the `InboundEmail` and matches when it returns true; any object responding to `match?` is called with the `InboundEmail`; `:all` matches everything and belongs last. Recipients are the To, Cc and Bcc addresses plus any `X-Original-To` and `X-Forwarded-To` headers, which is how a Bcc'd or forwarded copy still routes. The symbol becomes a class, `:receipts` to `ReceiptsMailbox`. If no rule matches, the email is marked `bounced` and `ActionMailbox::Router::RoutingError` is raised in the routing job.

code

ruby · 13 lines
ruby
class RecipientTokenMatcher
  def match?(inbound_email)
    inbound_email.mail.recipients.any? do |address|
      token = address[/\Areceipts\+([a-z0-9]+)@books\.example\z/i, 1]
      token && User.exists?(receipts_token: token)
    end
  end
end

class ApplicationMailbox < ActionMailbox::Base
  routing RecipientTokenMatcher.new => :receipts
  routing :all => :backstop
end

go deeper

for a junior

Read a routing line such as routing(/^receipts@/i => :receipts) and name the mailbox class it reaches.

for a middle

Explain the matcher kinds, first-match ordering, the recipients list with X-Original-To, and what happens when nothing matches.

for a senior

Order rules deliberately, anchor patterns, add a backstop, and use matcher objects for data-driven routing without slowing every email.

for a principal

Design the address scheme itself, shared versus per-user tokens, weighing guessability, revocation and how routing scales with accounts.

## Routing in one class Routing decides which **mailbox** handles an `InboundEmail`. All rules live in `ApplicationMailbox`, declared with the class method `routing`, which takes a hash of **matcher => mailbox name**. Each pair becomes an `ActionMailbox::Router::Route`, appended to one router shared by the mailbox classes. ```ruby class ApplicationMailbox < ActionMailbox::Base routing "[email protected]" => :receipts routing(/\Areceipts\+[a-z0-9]+@books\.example\z/i => :receipts) routing ->(inbound_email) { inbound_email.mail.subject.to_s.start_with?("[support]") } => :support routing :all => :backstop end ``` For a bookkeeping app, the shared address and per-user plus-addresses both reach `ReceiptsMailbox`, support requests go elsewhere, and anything left falls through to `BackstopMailbox`. ## The five kinds of matcher | Matcher | Matches when | |---|---| | String | any recipient equals it, compared with `casecmp?` (case-insensitive) | | Regexp | the pattern matches any recipient | | Proc / lambda | it returns truthy when called with the `InboundEmail` | | object with `match?` | `matcher.match?(inbound_email)` returns truthy | | `:all` | always | Anything else raises `ArgumentError` ("Expected a Symbol, String, Regexp, Proc, or matchable") when the class loads, so a typo surfaces as soon as `ApplicationMailbox` loads, not on the first email. A custom matcher object is useful when the rule needs data, for example looking up whether the recipient's token belongs to an active account. ## What counts as a recipient String and Regexp matchers are checked against `mail.recipients`, a Rails extension to `Mail::Message` that concatenates: - the **To**, **Cc** and **Bcc** addresses; - any **`X-Original-To`** headers; - any **`X-Forwarded-To`** headers. The last two matter in practice. When a user Bcc's `[email protected]`, the visible headers do not name it, but the Mailgun, Postmark and SendGrid ingresses prepend an `X-Original-To` header with the envelope recipient the provider reports, and a relay mail server can be set up to add one. Without that header a Bcc'd receipt would match nothing. ## Order and the first match The router evaluates routes in declaration order and stops at the first one whose matcher returns true: 1. Put specific rules first: exact addresses, then patterns. 2. Put lambdas that load data after cheap matchers, since every email runs through each rule until one matches. 3. Put `routing :all => :backstop` last; placed first, it would capture every message. Anchor regular expressions. `/receipts@/` also matches `[email protected]`; `/\Areceipts@/i` does not. ## From name to class The mailbox name is turned into a class with `"#{name.to_s.camelize}Mailbox".constantize`, so `:receipts` becomes `ReceiptsMailbox` and `:vendor_invoices` becomes `VendorInvoicesMailbox`. The lookup happens only when a message matches, so a misspelled name raises `NameError` in the routing job rather than at boot. The router then calls `ReceiptsMailbox.receive(inbound_email)`, which instantiates the mailbox and runs its callbacks and `process`. ## When nothing matches `ActionMailbox::Router#route` marks the `InboundEmail` **bounced** and raises `ActionMailbox::Router::RoutingError`. No bounce email is sent, because the router has no mailer to send one with; the exception fails the routing job, so the queue backend and your error reporting record it. A backstop mailbox turns that error into a decision you control: log it, notify someone, or reply to the sender through a mailer. ## Designing addresses for routing Routing is only as good as the address scheme behind it. A few patterns cover most apps: - **One shared address per feature**, such as `[email protected]`, with the sender's From address identifying the user. Simple, but a forged From can claim to be anyone, so the mailbox must verify the sender. - **Per-user tokens** in a plus-address, `[email protected]`. The token identifies the account even when the user forwards from another address, and it can be revoked by issuing a new one. - **Per-record reply addresses**, such as `reply+<signed-id>@books.example`, so a reply to a notification lands on the right thread. Whatever the scheme, keep the routing rule cheap and push identity checks into the mailbox: the rule decides which **kind** of mail it is, and `before_processing` decides whether **this** message is acceptable.

  • How would you send unmatched mail to a mailbox instead of raising?
    Add `routing :all => :backstop` as the last rule and create `BackstopMailbox` with a `process` method. Every email that no earlier rule claims then reaches it, so it can log, alert or reply through a mailer instead of failing the routing job with `RoutingError`.
  • Why can a misspelled mailbox name in routing go unnoticed until production traffic?
    The name is only constantized when an email matches that route: `"#{name.to_s.camelize}Mailbox".constantize`. Until then nothing looks the class up, so a typo raises `NameError` in the routing job for the first matching email. A mailbox test that routes a sample message catches it.

Routing is a mailroom clerk working down a sorting list taped to the wall: the first line on the list that fits the envelope decides the pigeonhole, and a catch-all "everything else" line only works if it is written at the bottom.

  • Every matching route runs, so one email can reach several mailboxes.
  • String routes are case-sensitive, like Ruby string equality.
  • A routing Proc receives the parsed Mail::Message, not the InboundEmail.
  • Bcc'd copies can never be routed because the To header lacks the address.
  • Unmatched email triggers an automatic bounce message to the sender.
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 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

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