Mailgun Inbound Routes Alternative: Route Mail by Address, Not Regex

A Mailgun Routes alternative: an address per customer by API call, a signed message.received webhook, GET /messages/:id and routing in your own code.

By · · 13 min read

TypeScript code that routes a message.received event by its inboxId, with a default branch in place of catch_all

Mailgun Routes turn inbound mail into rules. Each route pairs an expression, such as a regular expression on the recipient, with one or more actions, and Mailgun runs the routes in priority order every time a message reaches your receiving domain. If you are searching for a Mailgun inbound Routes alternative, you already have rules like these in production: one route per customer subdomain, a header match for urgent mail, a catch-all at the bottom that archives the rest. This guide shows the same intake on Mailcycle, where each recipient is an address you create by API call and the rules are ordinary code in your own handler.

Everything we quote about Mailgun comes from Mailgun’s own documentation, read on 28 November 2026. The page for each statement is listed at the end.

The parts of a Mailgun route

Mailgun’s Routes page describes a route as a filter expression and an action, ordered by priority, where “lower numbers have higher priority”. Unless a route runs stop(), the docs say “all lower priority Routes will also be evaluated”, so one message can trigger several routes on its way down the list. A route’s expression and its actions are stored as short strings, created in the control panel or with POST /v3/routes.

Filter expressions: match_recipient, match_header and catch_all

Three filters do the matching:

  • match_recipient(pattern) tests the SMTP recipient against a Python-style regular expression. Mailgun’s examples range from an exact address to match_recipient("^chris\+(.*)@example.com$") for plus addressing, and captures can be reused in the action, including named groups such as (?P<user>.*?)@(?P<domain>.*).
  • match_header(header, pattern) tests a header against a pattern, for example match_header("subject", ".*support").
  • catch_all() matches when no route above it matched, so it belongs at the lowest priority.

Actions: forward, store and stop

A matching route can run any mix of three actions. forward() sends the message on, for example to your URL. store() keeps the message “for up to 3 days”, and with notify set it posts to your URL with a message-url your code fetches later. stop() “simply stops the priority waterfall”, so routes below it are skipped.

What Mailgun posts to your URL

When forward() targets a URL, Mailgun posts a parsed copy of the message, as a form post by default.

The form post carries recipient, sender, from, subject, body-plain, body-html, message-headers, the attachment fields attachment-count, attachment-1 and onwards plus content-id-map, and three fields for checking the post: timestamp, token and signature. The signature is a hex HMAC-SHA256 of the timestamp joined to the token, keyed with your account’s webhook signing key. A 200 reply or a 406 ends delivery, and other replies are retried “10 minutes, 15 minutes, 30 minutes, 1 hour, 2 hours, and 4 hours”, eight hours in total.

How Mailcycle models the same intake

Mailcycle starts from the address rather than the domain. Your code calls addresses.create and gets back a working address on a shared Mailcycle domain, with nothing to add to DNS. When mail lands there, it is sealed to that address’s key, and every webhook subscribed to message.received gets a signed JSON event naming the message and the address. Your code then reads the message by id, opened in your own process.

Flow: your code creates one address per customer, mail is encrypted on arrival, a signed event names the address, and your own router decides what happens next
Each customer gets an address. The event names the address, and your router takes it from there.

The difference that matters for routing is where the rule lives. In Mailgun the rule is a string on the provider’s side, matched against text in the message. In Mailcycle the rule is the address itself: the inboxId in the event already tells you who the mail is for, and any further decision is a line of your code, tested and versioned with everything else.

Routing by address instead of by regex

Replacing match_recipient with one address per tenant

A typical Mailgun setup gives each customer a recipient pattern, like (?P<tenant>.*)@inbound.example.com, and pulls the customer out of the capture. On Mailcycle you make the address when you make the customer, and save its id:

import { Mailcycle } from 'mailcycle-sdk';

const mc = await Mailcycle.withApiKey({
  apiKey: process.env.MAILCYCLE_API_KEY!,
  phrase: process.env.MAILCYCLE_PHRASE!,
});

// When a tenant signs up: one address, kept for 30 days.
const inbox = await mc.addresses.create({ prefix: 'acme', label: 'Acme Ltd intake', retentionDays: 30 });
await db.tenants.update(tenant.id, { inboxId: inbox.id, intakeAddress: inbox.emailAddress });

The server adds a random ending to the prefix, so acme becomes something like acme-x7k2@ on a shared domain, and the address takes mail as soon as the call returns. The label is sealed on your machine before it is stored. No pattern can drift out of step with your customer table, because the customer row holds the address id.

Replacing match_header, stop() and catch_all() in one handler

Once the event arrives, the rest of the Mailgun waterfall becomes a short function. The order of the checks is the priority, an early return is stop(), and the last line is catch_all():

import type { Message } from 'mailcycle-sdk';

export async function routeMail(inboxId: string, messageId: string) {
  const message: Message = await mc.messages.get(messageId);
  const tenant = await db.tenants.findByInboxId(inboxId); // was match_recipient

  if (!tenant) return archive(message); // was catch_all()

  if (/urgent|help|asap/i.test(message.subject)) {
    return pageOnCall(tenant, message); // was match_header("subject", ...) plus stop()
  }

  return createTicket(tenant, message);
}

Because the rules are code, they can use anything you know: the tenant’s plan, office hours, whether the sender is already a contact, or a model’s guess at intent. They also get unit tests: routeMail runs in your test suite like any other function, and a change to a rule goes through code review.

Routing several features without a shared domain

With one receiving domain, every inbound feature shares the same local-part namespace, and the patterns have to keep out of each other’s way. With addresses made on demand, each feature simply has its own: a support address per tenant, a receipts address per user, a fresh address for each test run, an address for each agent. The event’s inboxId keeps them apart with no pattern at all.

The signed message.received webhook

Add the webhook in the web app under API, on the Webhooks tab, pick message.received, and copy the whsec_ secret, which is shown once. Each delivery is a small JSON body with an event id, its type, a timestamp and a payload of messageId and inboxId, sent with a Mailcycle-Signature header.

The receiver checks that header against the raw body, answers within 10 seconds, and then calls routeMail:

const ok = await verifyWebhookSignature(secret, rawBody, req.get('Mailcycle-Signature'));
if (!ok) return res.status(401).end();
const event = JSON.parse(rawBody);
res.status(204).end();
if (event.type === 'message.received') await routeMail(event.payload.inboxId, event.payload.messageId);

The signature is an HMAC-SHA256 over the timestamp and the entire body, keyed with a secret that belongs to that one webhook. Rotating it for one endpoint leaves the others alone. The SDK helper compares in constant time and refuses a timestamp older than five minutes, so a captured delivery cannot be replayed later.

The complete receiver, with Express, Next.js and FastAPI versions, deduplication on Mailcycle-Event-Id and a durable queue, is in Receive email with a webhook. Use that one in production rather than the four lines above.

Reading the message with GET /messages/:id

The event is a pointer. The content comes from GET https://api.mailcycle.email/messages/:id, called with your API key as a bearer token, which returns the sealed message for the SDK to open with your phrase. In code that is mc.messages.get(id) in TypeScript and mc.messages.get(message_id) in Python.

If you are porting a handler that reads Mailgun’s form fields, this is where each value lives on the opened message:

Mailgun field Mailcycle message
recipient to, plus the inboxId of the receiving address
sender, from from and fromName, with replyTo for answers
subject subject
body-plain text
body-html html, and safeHtml with remote content removed for display
attachment-count, attachment-1… attachments, each with filename, mimeType and size
content-id-map contentId on each inline image in attachments
timestamp receivedAt
Message-Id in message-headers messageId, ready for threading a reply

Files are fetched one at a time with mc.messages.attachment(message, index), which returns the bytes opened on your machine. A handler that only needs the subject never downloads a large PDF. Python works the same way, and the reading mail guide covers folders, read state and paging.

Stored mail with a retention you choose

Mailgun’s store() keeps a message for up to three days. In Mailcycle, storage is not an action you have to remember to add: every message waits at its address for that address’s retention, from 1 to 90 days, 7 by default. Set retentionDays per address when you create it, or change it later with addresses.update. A shorter retention also clears older mail, so each address keeps exactly as much history as you want.

That turns recovery into a read. If your receiver was down for a deploy, mc.messages.list(inboxId) returns the address’s mail newest first, with a cursor for older pages, whether or not a webhook ever fired. The same list call powers a nightly reconciliation job, if you like the extra safety.

Retries and the delivery log

A delivery that does not get a 2xx within 10 seconds is retried after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours and 12 hours: eight attempts across about a day and a half. Every delivery stays in the log for 30 days with its attempts and last response code, and any finished one can be sent again, from the app or with an API key. Between the long retry window, the replayable log and mail that stays at its address, a bad deploy on a Friday evening is still recoverable on Monday.

Encrypted on arrival, opened in your process

Mail is encrypted the moment it arrives, with keys from your account’s 12-word recovery phrase. Each address has its own key pair, and the SDK derives them on your machine. Webhook events carry ids and no content, so request logs, tunnels and proxies between Mailcycle and your server only ever see a message id. Keep the phrase in your secret store, next to your database credentials.

When a no-code tool needs the plain message, the decrypt Worker runs in your own Cloudflare account, opens one address’s mail and posts the parsed message on to n8n, Make, Zapier or Pipedream. The mechanism is described in Encryption.

The same router in nine SDKs

addresses.create, the signature helper and messages.get exist in every Mailcycle SDK: TypeScript, Python, Go, Rust, Java, .NET, PHP, Ruby and Swift, all Apache-2.0. If your Mailgun handler is a Flask view, a Go http.HandlerFunc or a Rails controller, the port stays in that language. Each one has a read-side tutorial:

Install commands and references are on the SDK pages.

Routing to an AI agent

More inbound workflows now end with an agent: one that triages support mail, files invoices or finishes a sign-up. On Scale, you give an agent its own addresses, and the mailcycle-mcp server, running on the agent’s own machine, offers it tools to list them, read messages, wait for new mail and read attachments. It works with Claude Code, Claude Desktop, Cursor, Codex, VS Code or any other MCP client. Agents start reply-only.

Routing to an agent then needs no special rule. Create the address for the agent, give it to the agent in the app, and mail sent there is the agent’s to handle. The email MCP server guide and email for AI agents cover setup with npx -y mailcycle-mcp pair.

Your own domain on Scale

When the intake should read support@example.com, move up to Scale, which includes 10 custom domains and lets you choose the whole local part. You add the domain in the app, prove it with one TXT record and point its nameservers at Mailcycle, and receiving is configured for you. Scale also sends from the API, so the same router can answer from the address that received the mail. See your own domains and Role addresses on your own domain.

A smooth order is to start on shared-domain addresses on Operator, prove the router, then bring the domain across last.

Operator or Scale for a Mailgun Routes workload

Prices come from pricing, limits from plans and limits.

What you route Plan Price a month Includes
Inbound only, on shared domains Operator $15 250 addresses, 250,000 received messages, API keys and webhooks
Inbound with replies, own domains or agents Scale $19 1,000 addresses, 750,000 received messages, 10 domains, sending from the API, agent inboxes

Operator is the match for routes that only forward() and store(). Scale fits when a route’s destination answers back, or when the recipients must be on your domain.

Moving your routes over

  1. Write down each route. Note its priority, its expression and its actions, from the Routes page in Mailgun’s control panel.
  2. Group the match_recipient routes by owner. Each tenant, queue or feature becomes one Mailcycle address, created with addresses.create and saved on its record.
  3. Turn header matches into checks inside routeMail, in the same order as their priorities.
  4. Put the catch_all() destination in the handler’s last line.
  5. Add the message.received webhook and store its secret beside your API key and phrase.
  6. Hand out the new addresses. Update reply-to headers, help pages, forms and test fixtures.
  7. Run the old and new paths side by side for a few days, compare what each one routed, then retire the Mailgun routes. Bring your own domain over on Scale as the final step.

For a full inbound feature built this way, with tickets, threading and reply by email, follow Add inbound email to your SaaS.

Testing the router before go-live

Since routing is a function, most of the testing needs no network: call routeMail with stubbed db and mc objects and assert where each message ends up. For the webhook path, a tunnel such as Cloudflare Tunnel or ngrok gives your laptop an HTTPS URL to register, and Send test in the app fires a webhook.test event through your signature check.

For a worker with no public URL, the event stream delivers the same events over a WebSocket, and mc.messages.waitFor({ inboxId }) resolves with the next message at an address, opened. End-to-end tests can send a real email to a fresh address and wait for it that way.

Troubleshooting a ported router

Events arrive for an address with no tenant

The address was made before the record was saved, or by a script outside your sign-up flow. Save the inboxId in the same transaction that creates the tenant, and let the default branch log anything it cannot place.

Every delivery gets 401

The body was parsed before the check. Verify the raw string first: in Express, mount express.text({ type: 'application/json' }) on the webhook route alone.

The same message is routed twice

A retry followed a slow answer. Reply 204 before calling routeMail, and record Mailcycle-Event-Id with a unique key so a second attempt is skipped.

Sources and dates

Each Mailgun statement above was read on 28 November 2026 on these pages:

What Page
Routes, priority, the waterfall and stop() https://documentation.mailgun.com/docs/mailgun/user-manual/receive-forward-store/routes
match_recipient, match_header, catch_all and captures https://documentation.mailgun.com/docs/mailgun/user-manual/receive-forward-store/route-filters
forward(), store() for up to 3 days, notify and stop() https://documentation.mailgun.com/docs/mailgun/user-manual/receive-forward-store/route-actions
Posted fields, response codes and retries https://documentation.mailgun.com/docs/mailgun/user-manual/receive-forward-store/receive-http
Signature over timestamp and token, signing key https://documentation.mailgun.com/docs/mailgun/user-manual/webhooks/securing-webhooks
Creating a route over the API https://documentation.mailgun.com/docs/mailgun/api-reference/send/mailgun/routes/post-v3-routes

Mailcycle figures come from https://mailcycle.email/pricing and https://docs.mailcycle.email/concepts/plans-and-limits/. Mailgun is a trademark of its owner. We are not affiliated with Mailgun.

FAQ

What can replace Mailgun inbound Routes?

Mailcycle gives each customer, queue or job its own address, created with one API call on a shared domain that already receives mail. When mail lands, a signed message.received event tells your code which address received it, and your code reads the message by id and decides where it goes. The routing lives in your codebase, next to the rest of your logic.

How do I replace match_recipient in Mailcycle?

Create one address per recipient you would have matched, and store its id next to the record it belongs to. The inboxId in each event then points straight at that record, so a database lookup replaces the regular expression and its captures.

What replaces the catch_all() route?

The default branch of your own handler. When an inboxId has no record attached, send the message wherever your catch-all route sent it: an archive, a review queue or a log.

Is there a store() action in Mailcycle?

Every message is kept at its address for that address's retention, which you set from 1 to 90 days and which defaults to 7. You can list an address's mail over REST at any time, with or without a webhook, and read each message by id.

Which plan do I need to receive email by API and webhook?

Operator, at $15 a month, includes API keys, webhooks, 250 addresses and 250,000 received messages a month. Scale, at $19 a month, adds 10 of your own domains, any local part you choose, sending from the API and AI agent inboxes. Plans are on https://mailcycle.email/pricing.

How long does Mailcycle keep retrying a webhook?

Eight attempts over about a day and a half: after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours and 12 hours. Each delivery is logged for 30 days and can be sent again from the log or with an API key.

How do I check that an event came from Mailcycle?

Pass the whsec_ secret, the raw request body and the Mailcycle-Signature header to the SDK helper, verifyWebhookSignature in TypeScript or verify_webhook_signature in Python. The signature covers the timestamp and the whole body, and a timestamp older than five minutes is refused.

Can an AI agent handle the routed mail?

Yes. On Scale, the mailcycle-mcp server gives an agent tools to list its addresses, read messages and wait for new mail, from Claude Code, Claude Desktop, Cursor, Codex or any other MCP client. You choose which addresses each agent holds, so routing to an agent is the same as routing to code.

Receive email in code