# How email works in xstate

> The architecture behind xstate mail. Every mailbox is a Cloudflare Agent with its own database, Amazon SES carries mail in and out, and each organization's messages live in its own storage bucket.

This page describes how xstate receives, stores and sends email, and how each step is secured. It is written for
engineers who want to know what happens to a message. For the full list of what xstate does to protect accounts and
data, see [Security](/docs/security).

## SES at the edge, a Cloudflare Agent per mailbox behind it

Amazon SES sits at the edge and speaks SMTP to the rest of the world. Everything behind it runs on Cloudflare.

| Part | What it does | Runs on |
| - | - | - |
| Mail in and out | Receives mail for your domain and delivers the mail you send | Amazon SES |
| API | Every request from the web, mobile and desktop apps, the email API, connected AI apps and mail apps | Cloudflare Workers |
| Mailbox | One agent per mailbox, with its own SQLite database | Cloudflare Agents (Durable Objects) |
| Messages | Every message kept whole, as it arrived or left | Cloudflare R2, one bucket per organization |
| Directory | Accounts, organizations, domains, addresses and sending limits | Cloudflare D1 |
| Background work | Delivery, attachment filing, search indexing, notifications | Cloudflare Queues |

## Every mailbox is an agent

Each mailbox is one [Cloudflare Agent](https://developers.cloudflare.com/agents/), addressed by the mailbox's id.
"Agent" here means what Cloudflare's SDK means by it: a small, stateful program with its own storage that other code
calls by name. It does not mean a language model reads your mail. The AI agents you set up in xstate are a separate
part of the product, and they are only offered the mail you point them at.

The mailbox's agent owns everything about that one mailbox:

- **The message index.** Sender, recipients, subject, preview, size, folders, read and starred state, and which
  conversation each message belongs to.
- **Search.** Two full-text indexes: one over senders, recipients and subjects that matches parts of words, so half
  an address or a domain finds its mail, and one over message text that matches whole words and their stems.
- **Conversations.** Messages are threaded by their `Message-ID`, `In-Reply-To` and `References` headers, with the
  subject as a fallback.
- **What mail apps need.** The per-folder numbering IMAP uses, so Apple Mail, Outlook and Thunderbird stay in step.
- **Calendars** and their events.
- **The delivery log**: where each message went.
- **What the mailbox knows about senders**: who it has written to, and whose mail someone marked as junk or not
  junk.

All of that is one SQLite database, private to the agent. There is no shared table of everyone's messages.

The agent does small, fast work only. Fetching, parsing and anything slow happens in the Workers and queues that
call it.

## Every message is one file

The agent holds the index. The message itself is kept whole, exactly as it arrived or left, as one file in your
organization's own R2 bucket, under the mailbox's folder:

```
<mailbox id>/raw/<message id>.eml
```

- **One bucket per organization.** Your mail is not in a bucket with anyone else's.
- **Nothing is rewritten.** The file is the message as it arrived or as it left, headers and attachments included,
  so what you export or open in a mail app is what was sent. (On the Free plan, mail you send leaves with a short
  "powered by xstate" line at the end, and the Sent copy includes it.)
- **Attachments are read in place.** The index records where each attachment sits inside its message, so opening
  one reads only that part of the file. Attachments that pass the file-type rules are also filed in Storage, where
  they can be searched.
- **Deleting is simple.** A message is one index row and one file. A mailbox is one agent and one folder.

## Receiving a message

1. **Your domain's MX record points at Amazon SES.** SES accepts the message, checks it for viruses and spam, checks
   SPF, DKIM and DMARC, and saves it to a private S3 bucket.
2. **SES notifies xstate.** The notification is accepted only from xstate's own topic and only with a valid
   signature. It is put on a queue and answered at once.
3. **A queue consumer finds the mailboxes.** Each recipient is looked up among xstate's addresses. Mail for an
   address that doesn't exist, or for a domain whose mail is turned off, is dropped and logged, never bounced: SES has already accepted it, so a bounce would go
   to a sender who may be forged.
4. **Inbox or Junk is decided** (see [below](#inbox-or-junk)).
5. **The message is stored.** The raw copy goes to the organization's bucket, then the mailbox's agent adds it to
   its index.
6. **The copy in S3 is deleted.** Anything left there is deleted after 7 days.
7. **The apps are told.** Open apps update live, and phones and browsers get a notification.
8. **Slow work happens afterwards**, on a second queue: attachments are filed, the message is indexed for search,
   calendar invitations are applied, and the message is offered to any AI agent watching that mailbox.

Every step is safe to repeat. A retried job finds what was already delivered by SES's id for the message and stops
there, so a message is never delivered twice. A job that keeps failing waits in a dead-letter queue while the
original stays in S3. Because delivery and the slow work are on separate queues, a problem with search or an AI
model never delays mail reaching the inbox.

## Sending a message

Mail can be written in the web, mobile or desktop app, by the [email API](/docs/transactional-email), by a
[connected AI app](/docs/mcp), by an AI agent, or in a [mail app](/docs/mail-apps) over SMTP. All of them take the
same path:

1. **Access.** The sender must be allowed to send from that mailbox, and only from its own address or one of its
   aliases.
2. **Recipients.** Addresses that bounced before, or marked your organization's mail as spam, aren't sent to: the
   apps refuse the message, and the email API skips those recipients and reports them.
3. **Attachments.** Every file is checked against the [file-type rules](/docs/security#attachments).
4. **Limits.** The send is counted against the mailbox's and the organization's limits before it leaves, in one
   database transaction, so two sends at the same moment can't both slip under a limit.
5. **The message is built.** xstate writes the MIME message itself. `Bcc` recipients are never in what leaves.
6. **It leaves through one door.** A single function hands the message to Amazon SES, which signs it with your
   domain's own DKIM key.
7. **The Sent copy is kept.** The exact bytes that left are stored in the bucket and added to the mailbox's index.
8. **Outcomes come back.** SES reports deliveries, bounces and complaints, which go into the delivery log.

## How security is handled

### Isolation

A mailbox's index is its own database inside its own agent, and an organization's messages are in its own bucket.
Reading another organization's mail would take more than a bad query: the data is not in the same place.

Two things are shared, and neither holds whole messages. The directory (accounts, organizations, domains,
addresses and sending limits) is one database. Search by meaning uses one index that holds passages of text, kept
in a separate partition for each organization, so a search can never cross organizations whatever it asks for.

### One access check for every client

The web app, the mobile and desktop apps, the email API, connected AI apps and mail apps all go through the same
check before they reach a mailbox. Personal mailboxes can be read only by their owner; admins can't read members'
personal mail. If you don't have access to a mailbox, xstate says it doesn't exist.

### Keys that can each do one thing

xstate talks to Amazon with three separate identities:

| Identity | The only things it can do |
| - | - |
| Receiving | Read, quarantine and delete messages in the bucket SES saves received mail to |
| Sending | Send a message |
| Domains | Register and check domains |

The key that sends can't read received mail, and the key that manages domains can't send.

### Trusting what arrives

- **Notifications are verified.** A notification that mail arrived, bounced or drew a complaint is accepted only from
  xstate's own topics, with a signature that checks out.
- **Senders are verified.** SES checks SPF, DKIM and DMARC on every received message, and its verdicts are kept with
  the message.
- **Calendar emails change a calendar only when the sender is proven** to be the organizer or the guest.

### Inbox or Junk

One decision is made per message, from:

- SES's spam verdict, and the sender domain's own DMARC policy;
- whether the mailbox has written to the sender, or the sender is one of your contacts;
- what people in the mailbox said before: junk, or not junk;
- phishing signs: a well-known brand's name from a free mail address, a domain that imitates a brand, a link that
  shows one address and goes to another, a display name of someone in your organization on an outside address;
- sites someone in your organization reported as phishing;
- [Google Web Risk](https://cloud.google.com/web-risk), which is sent only link addresses, never the message.

The reasons are kept with the message, and the app shows them when you open it in Junk.

### Viruses and attachments

A message SES finds a virus in is delivered to nobody. Attachments are checked against file-type rules on the way in,
on the way out, and when uploaded; blocked types can't be downloaded, sent or copied into Storage.

### Reading mail safely

A message opens in a sandboxed frame where its scripts never run and its forms can't be sent. Remote images stay
hidden until you choose to show them, so senders can't tell when you open their mail.

### Encryption

- **In transit.** Sending servers deliver to Amazon SES over TLS when they support it. For xstate's own domains we
  also publish an MTA-STS policy in enforce mode, so servers that honour it deliver only over an encrypted
  connection with a verified certificate; this isn't published for customer domains yet. The apps and the API use
  HTTPS only. Mail apps connect
  over TLS only, and sign in with an app password that is stored only as a hash.
- **At rest.** Messages in R2 and the mailbox databases are encrypted at rest by Cloudflare. xstate does not add
  encryption of its own on top, and mail is not end-to-end encrypted: xstate has to read a message to index it,
  thread it and check it for spam.

### Protecting sending

Customers share a sending reputation, so one abusive sender could hurt delivery for others. Two things prevent
that:

- **Limits.** Each mailbox can send to 100 outside recipients an hour and 500 a day; each organization to 400 an hour
  and 2,000 a day. Mail between xstate domains isn't counted.
- **Automatic suspension.** Sending is suspended automatically when bounces or spam complaints pass a safe rate.
  Reading mail keeps working.

### The delivery log

Each mailbox keeps a record of where every message went: delivered and to which folder, sent, accepted or bounced by
the receiving server, refused, or dropped. It holds ids, addresses and outcomes, never what a message says. It is
kept 30 days and only owners and admins can read it.

## Mail apps

Mail apps speak IMAP and SMTP, which need a plain network connection that Cloudflare Workers can't accept yet. A
small bridge in front listens on the mail ports, ends TLS, and passes each connection's bytes to xstate over a
WebSocket. It doesn't understand IMAP or SMTP, and it writes nothing to disk.

Each connection gets its own session on Cloudflare, which speaks the protocol and answers from the same mailbox
agent and the same files the web app uses. Mail you read, move or delete in a mail app shows the same everywhere,
because there is only one copy.

## Why this scales

- **Load stays local.** A busy mailbox is one busy agent. It doesn't slow the mailbox next to it, because they share
  no mail database.
- **Adding mailboxes adds agents**, not rows to one growing table. An idle mailbox uses no compute until mail arrives.
- **Queues absorb bursts.** A flood of mail waits in a queue; it doesn't overload the API people are using.
- **Large messages are handled one at a time**, so a 40 MB message can't crowd out the others in the same batch.
