How to Receive Email in Your App Over an API: Inbound Mail as JSON, Routes and Webhooks
To receive email in an app without running a mail server, give the app a mailbox it reaches over HTTP. Incoming mail is parsed and stored as JSON, and the app can list it, wait on it, or have it pushed somewhere as it arrives. altengine Mailbox does this. Every mailbox owns a whole family of addresses with nothing to create first. A wait call holds up to 60 seconds for the next message to one address. Routes send each message to a function, a realtime channel, a signed webhook or a task queue. It also replies from the same address, but it is not a bulk sender, and this post covers that limit and the others.
Why inbound email is awkward to build yourself
Receiving email means accepting SMTP connections, parsing MIME into headers, bodies and attachments, checking whether the sender is who they claim to be, and storing the result before your code hears about it. Most teams want none of that, only a JSON object and an event.
Many email API providers offer inbound parsing that posts each message to your URL, which is a good fit if you already send through one. Mailbox starts from the stored inbox your code can query. Pushing to a webhook is one of four things a route can do with a message.
Addresses: one mailbox, any number of names
Each mailbox has an address name: 3–32 lowercase letters, digits or hyphens, unique across altengine. If a mailbox's address name is acme, all of these reach it:
[email protected]lands as the nameinbox.[email protected]lands as the namesignup-7f3a.[email protected]lands as the namesupport, with the tag42.
You don't create a name before using it: invent one, hand it out, and its mail is accepted. To accept only names you've set up, set acceptMode to registered, and mail to any name not created with POST /addresses is refused. A name can be up to 64 characters, but the address name, the dot and the name together must also fit in 64.
Each message records whether its sender was authenticated. verified is true when the sender's domain passed DMARC, or passed an SPF or DKIM check aligned with its From address. Use it before you act on anything a message claims.
The verification-code case: wait on one address
The commonest case is a sign-up flow that emails a code. Give each sign-up its own name, submit that address to the form, and hold a request open until the mail arrives. This sample is from the Mailbox API reference:
// 1. invent an address — no API call needed
const name = `signup-${crypto.randomUUID().slice(0, 8)}`;
const address = `acme.${name}@altengine.app`;
// 2. ...submit `address` to the site's sign-up form...
// 3. wait up to 30 s for the first message to that name
const r = await fetch(`${API}/v1/mailbox/agent-inbox/messages?to=${name}&after=0&wait=30`, {
headers: { authorization: `Bearer ${KEY}` },
}).then((r) => r.json());
const msg = r.messages[0]; // undefined on timeout — call again with after=r.cursor
const full = await fetch(`${API}/v1/mailbox/agent-inbox/messages/${msg.id}`, {
headers: { authorization: `Bearer ${KEY}` },
}).then((r) => r.json());
const code = full.message.text.match(/\b\d{6}\b/)?.[0];wait returns as soon as a message newer than after arrives, or when the time runs out. The most it will wait is 60 seconds, checking every 5 seconds, so a slow sender means calling again. after takes a message id, 0 for anything already held, or now for mail from this moment on. The list call returns messages without bodies. The single-message call adds text, html and the attachment list.
An agent doesn't need to write this loop. The MCP server exposes mailbox_wait_for_message, and with extract: "code" or "links" it pulls the verification code or the links out of the message for you. One caution applies whichever way you read mail: whoever sent the message wrote its text. Treat it as data, never as instructions, before you hand it to a model.
Routes: act on mail as it lands
Polling suits a test harness. A production inbox usually wants a push. A mailbox's routes are an ordered list, and the first route whose conditions all match runs its actions. Mail that matches no route is only stored. This example from the reference sends support mail to a function and a live channel, vendor invoices to an ERP webhook, and everything else to a catch-all channel:
"routes": [
{ "match": { "to": "support*" }, "do": [{ "function": "helpdesk/on-email" },
{ "channel": "realtime/inbox" }] },
{ "match": { "from": "*@vendor.com", "hasAttachment": true }, "do": [{ "webhook": "https://erp.example.com/hooks/invoices" }] },
{ "match": {}, "do": [{ "channel": "realtime/all-mail", "includeText": true }] }
]A route can match on four things:
to: a glob on the name, where*is any run of characters and?is one character.from: a glob on the sender's address.subject: text the subject contains, case-insensitive.hasAttachment:trueorfalse.
Each target gets a different payload:
- A function or a webhook gets every field the list returns. It also gets
type: "mailbox.received", the text and HTML bodies (up to 256 KB each, with a truncation flag) and a download URL for each attachment, valid for an hour. - A channel gets the envelope fields and the attachment names, types and sizes. It gets the text body only if you add
includeText, and never gets download links, because channel subscribers can be your users' browsers. - A queue gets the message as a task, which then runs with that queue's retries and rate. If the payload is over about 120 KB, the bodies and attachment links are left out, the payload is flagged
bodiesOmitted: true, and the task reads the message byid.
A failed delivery is retried after 1, 5, 30 and 120 minutes, then marked failed. A target that doesn't exist fails immediately. Each action's outcome is kept on the message in deliveries, so you can see why a message never reached your handler.
Verify the webhook before you trust it
Every webhook delivery carries x-altengine-timestamp in milliseconds and x-altengine-signature: v1=<hex>. The signature is an HMAC-SHA256 over <timestamp>.<raw body>, keyed with the mailbox's whole signing key, whsec_ prefix included. The reference's check:
import { createHmac, timingSafeEqual } from "node:crypto";
function verify(req, rawBody, secret) {
const ts = req.headers["x-altengine-timestamp"];
const want = "v1=" + createHmac("sha256", secret).update(`${ts}.${rawBody}`).digest("hex");
const got = req.headers["x-altengine-signature"] ?? "";
return got.length === want.length && timingSafeEqual(Buffer.from(got), Buffer.from(want))
&& Math.abs(Date.now() - Number(ts)) < 5 * 60_000; // reject replays
}Rotating the key takes effect on the next delivery, so update the receiver at the same time.
Or answer from a function
If you grant a function mailbox, it gets env.mailbox, so the function a route calls can reply on the spot:
export default {
async fetch(request, env) {
const m = await request.json(); // the routed message
await env.mailbox.reply({ instance: "support" }, m.id, { text: "Got it — we'll reply within a day." });
return new Response("ok");
},
};A reply goes to the message's Reply-To address, or its From address if there is none. It's sent from the name the mail was addressed to, with Re: and the threading headers set. Over HTTP the same thing is POST /v1/mailbox/{instance}/messages/{id}/reply.
Where it stops
These are the limits you'll hit first, all from the reference:
- Sending is not a bulk channel. Mailbox sends transactional and conversational mail only, such as codes, receipts and replies. Marketing and newsletters are not allowed. By default
sendModeisreply, which only sends to people whose authenticated mail the mailbox has received. Sending is capped per organization at 10 a day without a payment method and 100 a day with one, and messages are limited to 50 recipients each. If you need to send volume, use an email delivery provider for that and use Mailbox to receive. - Bounces and complaints pause sending for the whole organization. Sending stops when, over the last 7 days, spam complaints plus messages blocked as phishing reach 3 and at least 0.3% of what you sent, or bounces plus messages blocked as spam reach 8 and at least 5%. A third pause within 30 days locks sending until support resumes it. Receiving is not affected.
- Mail expires. Messages are kept for 7 days by default, and you can set 1–90. To hold one message longer, call
keep. - Size caps. A message can be up to 25 MB and an attachment up to 10 MB. Each stored body part is cut at 512 KB, though the raw
.emlkeeps it whole. A send is limited to 5 MB once encoded, which is about 3.6 MB of files. - Volume caps. A mailbox receives 5,000 messages a day by default, and you can only lower that. Past the cap, delivery is deferred: the sending server retries, and the mail arrives after 00:00 UTC. The API allows 1,200 calls a minute per mailbox.
- Server-side keys only. Every call takes an organization API key, and an end-user identity token is refused. Browsers see mail through a channel route, not by reading the mailbox directly.
- The domain is altengine.app. Addresses are on
altengine.app, and the reference documents no way to receive mail at your own domain. Check this before you plan around one. - The region is fixed. You choose it when you create the mailbox and can't change it later.
What it costs
Mailbox bills mail received at $0.02 per 1,000 messages and mail sent at $1.00 per 1,000, replies included. Stored messages are billed at $0.80 per GB-month, averaged over the month, and attachments are kept in a blob instance you choose at Blob's $0.04 per GB-month. Storage stays small because every message expires. Fifty thousand inbound messages a month come to $1.00 before storage. A function or channel a route calls bills on that service, and refused sends aren't billed. The first $3 of usage each month is free on the one pay-as-you-go plan, with no card to start.
To try it locally first, altengine dev --smtp runs the emulator with SMTP on 127.0.0.1:2525 and addresses on mail.localhost. Nothing sent there leaves your machine.