# Build Email Into Your AI-Agent Platform

Published: November 17, 2026

An end-to-end build: provision per-agent mailboxes, scope credentials, send, route inbound replies and resume the right customer's agent.

To build email into your AI-agent platform, you provision one mailbox per customer agent, store the mapping between that mailbox and your own customer and agent records, send with a credential scoped to that mailbox, and resume the right agent when an inbound webhook arrives. Robotomail supplies the addresses, transport, storage, threads and events. Your platform owns onboarding, authentication, tenancy, permissions and job execution.

This post follows one fictional platform, RelayDesk, which runs enquiry-handling agents for its business customers. Two fictional customers, Cedar and Harbor, each have a qualification agent. Every ID, address and example.com domain below is illustrative. All application code is labelled as RelayDesk's own, not a Robotomail feature.

## The completed flow

Read this once before you write anything, because it tells you how many pieces your team owns.

1. Cedar signs up on RelayDesk. RelayDesk creates `customer_id = cus_cedar` and `agent_id = agt_cedar_qualifier` in its own database.
2. RelayDesk's provisioning service reserves an onboarding operation for `(cus_cedar, agt_cedar_qualifier)` and an intended address.
3. The provisioning service calls Robotomail to create the mailbox and persists the returned mailbox ID and full address against that pair.
4. The provisioning service mints a runtime API key scoped to that one mailbox and stores it in a secret store, recording only a reference in the association row.
5. Cedar's agent sends a follow-up to an enquiry using the scoped key. RelayDesk persists the send result and a conversation mapping keyed by mailbox ID and thread ID.
6. The prospect replies. Robotomail posts a `message.received` event to RelayDesk's webhook endpoint.
7. RelayDesk verifies the signature, resolves the mailbox ID to `(cus_cedar, agt_cedar_qualifier)`, dedupes the delivery, enqueues work and acknowledges. A worker resumes Cedar's agent with its thread context and its own scoped credential.

### Who owns what

| Robotomail | RelayDesk (your platform) |
| --- | --- |
| Mailbox creation and addresses, platform domain and verified custom domains | Customer onboarding, sign-in, sessions and billing |
| Sending, receiving, MIME parsing, attachments, storage | Which customer and agent a mailbox belongs to |
| Threading and stored message records | Conversation and run mappings, agent scheduling, model calls |
| `message.received` events with signatures | Signature verification, dedupe, retries, reconciliation queues |
| Scoped API keys for runtime workers | Secret storage, rotation policy, permission checks |

Robotomail account ownership does not distinguish RelayDesk's customers. One Robotomail account holds many mailboxes, and the tenancy meaning of each mailbox lives only in RelayDesk's database. That boundary is the single most important thing to internalise: if your database loses the association, Robotomail cannot tell you whose mail a mailbox holds.

If you want the shorter product-level framing before the build, the [email API for AI agents](/email-api-for-ai-agents) page covers it.

## Size the account before you provision

Decide capacity first, because mailbox count is the constraint that bites a platform earliest. Current monthly figures at the time of writing:

- **Solo**, $5/month, one mailbox and one custom domain, 500 sends and 500 receives per month. Fine for a single agent, not for a multi-tenant platform.
- **Starter**, $19/month, 10 mailboxes total, one custom domain, 500 sends/day and 15,000 sends/month per mailbox, 2,000 inbound messages/month across the account.
- **Growth**, $79/month, 50 mailboxes, five custom domains, 1,000 sends/day per mailbox, 20,000 inbound messages/month across the account. Growth has no monthly sending cap, but daily and rate limits still apply.

Count every mailbox, not just customer ones. Your signup mailbox and any test or operations mailbox consume the same budget. Ten customers with two agent mailboxes each is 20 mailboxes, so Starter does not fit, and Growth fits that mailbox count only if the inbound and per-mailbox send limits also fit your traffic.

The restricted starter experience exchanges mail only with the verified owner address at 10 sends and 10 receives per calendar month. It is useful for a first loop against your own address. External customer correspondence and custom domains require a paid plan, so a real customer pilot starts on a paid account. Check [pricing](/pricing) for current terms, and include storage, shared inbound volume, custom domain count and your own model and hosting costs in the decision. Mailboxes are a metered resource, not unlimited tenants.

## Create platform records before the mailbox

RelayDesk writes its own rows first. The association table is application-owned:

```
(customer_id, agent_id, mailbox_id, mailbox_address, credential_secret_ref, lifecycle_state)
```

with a unique constraint on `(customer_id, agent_id)` for the per-agent design. Conversation and run mappings are separate and keyed by `mailbox_id` plus `thread_id`.

Before calling Robotomail, RelayDesk inserts an onboarding operation row with state `reserved` and the intended address, keyed by the same pair. Repeated onboarding, double-clicked buttons, retried webhooks from your billing provider, a replayed queue message, must resolve to the same association rather than minting a second mailbox. Mailboxes cost money and a stray second mailbox for Cedar will silently receive mail nobody routes.

A naming convention worth adopting early: `relaydesk-<customer-slug>-<agent-role>`. It makes an account listing readable during an incident and gives you a deterministic intended address to reconcile against.

Never accept a browser-supplied mailbox ID as proof of ownership. Any endpoint that takes a mailbox ID from a client must re-resolve it through the association table under the authenticated customer.

## Provision the mailbox

One call creates Cedar's agent mailbox. Keep this call inside the trusted provisioning service, using the full-access key, server-side only.

```bash
curl -X POST https://api.robotomail.com/v1/mailboxes \
  -H "Authorization: Bearer rm_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{"address": "relaydesk-cedar-qualifier"}'
```

Omit `domainId` to get an address on the Robotomail platform domain, for example `relaydesk-cedar-qualifier@robotomail.co`. For customer-facing addresses on your own domain, include the UUID of a domain your account owns and has verified. The response wraps the created mailbox, with `id` and `fullAddress` among its camelCase fields. API responses use camelCase; webhook payloads use snake_case. That asymmetry trips people up, so handle it once in a mapping layer.

Persist `id` and `fullAddress` onto the reserved onboarding row and flip `lifecycle_state` to `active`. Until that write commits, treat provisioning as incomplete.

Handling 409: a conflict means the address is taken. Reconcile by checking whether the intended address already exists among mailboxes your account owns and matches your reserved operation. If it does, adopt that mailbox ID. If it does not, fail the operation and surface it. Never adopt an arbitrary existing mailbox because its address looked close enough; that is how one customer's agent ends up reading another's mail.

Provisioning returns promptly, but mailbox readiness and inbound deliverability are not a latency guarantee. Do not block a signup UI on the first inbound message arriving. The `mailbox create` CLI command is handy while you are exploring:

```bash
npx @robotomail/cli mailbox create relaydesk-cedar-qualifier
```

Field-by-field detail lives in [the mailboxes API reference](/docs/api/mailboxes).

## Scope a runtime credential

The provisioning service holds the full-access key. Runtime workers should not.

Create an API key scoped to Cedar's mailbox ID, give it a name you can recognise in an audit, and store the returned secret in your secret manager. The create response includes the key material, a prefix and a flag indicating the key is scoped. Record the prefix and a secret-store reference in `credential_secret_ref`. Do not write key material into customer-visible rows, logs, or anything a support tool renders. The exact request and response shapes are documented in the [API keys reference](/docs/api/api-keys), and the scoping model is explained in [authentication](/docs/authentication).

Why this matters on a platform: a worker executing Cedar's agent run receives only Cedar's scoped key. A prompt-injected agent, a mis-targeted job, or a bug in your scheduler then cannot read or send from Harbor's mailbox. That containment is a property of the credential you issue, not of your prompt.

## Send the first outbound message

Cedar's agent qualifies an inbound enquiry and sends a follow-up. The worker uses the scoped key loaded from the secret store.

```bash
curl -X POST https://api.robotomail.com/v1/mailboxes/${mailboxId}/messages \
  -H "Authorization: Bearer rm_scoped_key_for_cedar" \
  -H "Content-Type: application/json" \
  -d '{"to": ["prospect@example.com"], "subject": "Your enquiry about Cedar fit-out quotes", "bodyText": "Hi Dana, thanks for getting in touch. Two quick questions so I can route this correctly: what is the site square footage, and what is your target start date?"}'
```

Persist the result before the worker exits: the returned message identifiers, the thread ID, and the conversation or run association for `(mailbox_id, thread_id)`. If you skip this write, the reply arrives with nowhere to go.

Accepted is not delivered. A 2xx means Robotomail took the message, not that the prospect's provider accepted it. Treat delivery as an event you observe later, and keep bounce and complaint handling in your roadmap rather than assuming send success.

For an ambiguous timeout, where you do not know whether the send happened, do not blind-retry. List the mailbox's outbound messages, which the messages endpoint can filter by direction, and look for your subject and recipient in the recent window before resending. Two identical follow-ups to a prospect is a visible product defect. The [messages API reference](/docs/api/messages) covers the filters.

## Receive the reply and resume the right agent

Register a webhook as its own resource, pointing at your endpoint, subscribing to `message.received`, and bound to the mailbox you just provisioned. Doing this per mailbox during provisioning keeps routing explicit. The exact request shape and signature details are in the [webhooks reference](/docs/api/webhooks), and the end-to-end conversation walkthrough is in the [receive and reply guide](/docs/guides/receive-and-reply).

The event body looks like this:

```json
{
  "event": "message.received",
  "data": {
    "message_id": "...", "mailbox_id": "...", "mailbox_address": "relaydesk-cedar-qualifier@robotomail.co",
    "from": "prospect@example.com", "subject": "Re: Your enquiry about Cedar fit-out quotes", "body_text": "...",
    "thread_id": "...", "received_at": "2026-04-17T10:00:00.000Z"
  }
}
```

RelayDesk's handler, application-owned code, in TypeScript shape:

```ts
// RelayDesk application code. Not a Robotomail feature.
export async function handleInbound(rawBody: Buffer, signature: string) {
  // 1. Verify over the exact raw bytes, before JSON.parse.
  if (!verifyRobotomailSignature(rawBody, signature, process.env.ROBOTOMAIL_WEBHOOK_SECRET!)) {
    return { status: 401 };
  }

  const { event, data } = JSON.parse(rawBody.toString("utf8"));
  if (event !== "message.received") return { status: 200 };

  // 2. Tenancy comes from our own table, keyed by mailbox UUID only.
  const assoc = await db.mailboxAssociations.findByMailboxId(data.mailbox_id);
  if (!assoc || assoc.lifecycle_state !== "active") {
    await db.reconciliation.record("unmapped_inbound", data.mailbox_id, data.message_id);
    return { status: 200 }; // acknowledged, parked for a human
  }

  // 3. Dedupe and enqueue in one transaction, then acknowledge.
  await db.tx(async (tx) => {
    const fresh = await tx.deliveries.insertIfAbsent(data.message_id);
    if (!fresh) return;
    await tx.outbox.enqueue({
      kind: "resume_agent",
      customerId: assoc.customer_id,
      agentId: assoc.agent_id,
      mailboxId: data.mailbox_id,
      threadId: data.thread_id,
      messageId: data.message_id,
    });
  });

  return { status: 200 };
}
```

Three rules hold that code together.

**Verify the signature over the raw body.** Check `X-Robotomail-Signature` against the exact bytes you received, before any parsing or body-mutating middleware. An unverified inbound endpoint is an open door into your agent scheduler.

**Resolve tenancy from the mailbox UUID only.** Never select a tenant from the `from` address, the subject, or a `customer_id` in a body. Anyone can send mail to your mailbox and write whatever they like in it.

**Commit dedupe and the job together, then acknowledge.** Webhook deliveries can repeat. If the delivery insert and the outbox insert commit in one transaction, a repeat delivery produces no second agent run. Acknowledge quickly and let the worker do model calls and sends asynchronously; do not run the agent inside the webhook request.

### Replying in the same thread

The webhook's `message_id` is the stored message UUID, not an email header. To reply in-thread, fetch the stored message and use its camelCase `messageId` field, which is the RFC 5322 Message-ID, as `inReplyTo`:

```bash
curl -X POST https://api.robotomail.com/v1/mailboxes/${mailboxId}/messages \
  -H "Authorization: Bearer rm_scoped_key_for_cedar" \
  -H "Content-Type: application/json" \
  -d '{"to": ["prospect@example.com"], "subject": "Re: Your enquiry about Cedar fit-out quotes", "bodyText": "Thanks Dana. 4,200 sq ft with a March start is well within scope, I am pulling two quotes now.", "inReplyTo": "<original-rfc-message-id@example.com>"}'
```

Never pass the stored message UUID or the thread UUID as `inReplyTo`. If the RFC Message-ID is missing, send without the header or route the item to human handling rather than guessing a value. When the agent needs more context than one message, read the thread rather than reconstructing it from your own logs.

## The failure modes you will actually hit

Run these three cases before onboarding a second customer.

**Interleaved customers.** Cedar's prospect and Harbor's prospect reply within the same second. Two webhook calls arrive, each carrying a different `mailbox_id`. Each resolves to a different association row, so two runs start with different scoped credentials and different thread contexts. Expected result: no cross-tenant read, no shared state, and two separate outbound replies. If your handler caches a "current tenant" anywhere above the per-request
