In Rails Action Mailbox, how do routing rules in ApplicationMailbox match an inbound email, and what happens when none match?
answer
- String, Regexp, Proc, match?, :all
- first matching rule wins
- to, cc, bcc plus X-Original-To
- :receipts becomes ReceiptsMailbox
- no match: bounced plus RoutingError
basics
~20 sApplicationMailbox'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 sEach `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 linesclass 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
endgo deeper
Read a routing line such as routing(/^receipts@/i => :receipts) and name the mailbox class it reaches.
Explain the matcher kinds, first-match ordering, the recipients list with X-Original-To, and what happens when nothing matches.
Order rules deliberately, anchor patterns, add a backstop, and use matcher objects for data-driven routing without slowing every email.
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.