# API and integrations Send mail and manage domains, accounts, mailboxes, calendars and bookings from your own code. ## Create API keys | Key | Create it in | Scopes | | --- | --- | --- | | Personal | **Settings → API keys** | Such as `send`, `read`, `calendar:read`, `calendar:write`, `jmap`, MCP mail access | | Admin | **Admin → API keys** (asks you to confirm identity) | `domains`, `accounts`, `mailboxes`, `storage` | Creating a key that reaches mail or administers the installation asks you to confirm your identity (calendar-only keys do not). Admin keys need an owner who is still an admin, and cannot read or send mail. **All keys are deleted** when the password or two-step sign-in changes. ## Send email ```bash curl https://mail.example.com/api/v1/send \ -H "Authorization: Bearer $MAILFLARE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "mailboxId": "", "from": "support@example.com", "to": "user@example.net", "subject": "Report", "text": "Hello." }' ``` | Field | Notes | | --- | --- | | `mailboxId` | Required: the sending mailbox. Limited keys get 404 without it. | | `from` | Sender address | | `to`, `cc`, `bcc` | Comma-separated string or array; names allowed (`"Maya Chen" `). 50 recipients in total. | | `subject`, `text` | Message | | `attachments` | `[{ "filename", "type", "contentBase64" }]` | | `inReplyTo`, `references` | Parent Message-ID and chain, to thread replies | Request body with copies and an attachment: ```json { "mailboxId": "", "from": "support@example.com", "to": ["user@example.net", "\"Maya Chen\" "], "cc": "ops@example.com", "bcc": ["audit@example.com"], "subject": "Report", "text": "Attached.", "attachments": [ { "filename": "report.pdf", "type": "application/pdf", "contentBase64": "" } ] } ``` Threaded reply: ```json { "mailboxId": "", "from": "support@example.com", "to": "user@example.net", "subject": "Re: Report", "text": "Thanks, received.", "inReplyTo": "", "references": ["", ""] } ``` ### Size limits | Limit | Value | | --- | --- | | `/api/v1/send` JSON body | 40 MiB (about 30 MB of files) | | Composer attachments | 10 files | | Outgoing per file and total | Admin sets on **General**: 1 MB up to 100 MB; default 100 MB. Files over 20 MB upload in 64 MiB parts straight to storage | | Incoming | 25 MB decoded attachments (and a count limit), else rejected. Cloudflare also caps the raw message at 25 MiB. | **Cloudflare sending** allows a whole encoded message of up to 25 MiB (files stay attached up to the admin's direct-attach limit, 20 MB by default), 50 recipients, 998-character subject and 16 KB headers. Files past that limit become download cards valid 30 days. **Anyone with the link can download.** Resend and SES follow the same direct-attach limit (never above Gmail's 25 MB), and use download cards beyond that. Admins set it on **General** from 1 to 25 MB. The web composer sends HTML with a plain-text copy. Quotes are wrapped in `
`. ## Search `GET /api/messages?q=...` (session) or `GET /api/v1/messages?q=...` (key with `read`). | Syntax | Meaning | | --- | --- | | `invoice` | Prefix match (`inv` finds "invoice") | | `"private window"` | Exact phrase | | `-word` | Exclude | | `from:maya`, `to:sam`, `subject:report` | One field (`to:` includes Cc) | | `has:attachment` | Has a non-inline attachment | | `is:unread`, `is:read`, `is:starred` | Flags | | `after:2026-09-01`, `before:2026-09-30` | Dates, at midnight in your time zone (or `X-Time-Zone`); `before` excludes the day | Terms combine with AND. Search uses a full-text index on SQLite/D1 ([other databases differ](databases.md#differences-between-databases)). Admins check or rebuild it with `GET`/`POST /api/admin/search-index`, needed only after restoring a very old backup. ## Messages and drafts These use a signed-in session. | Route | Purpose | | --- | --- | | `GET /api/messages/{id}/thread` | Conversation, oldest first, without drafts and trash | | `GET /api/messages?group=thread` | One row per conversation, with `threadCount`, `threadUnread`, `threadMessageIds` | | `POST /api/messages/bulk` (`action: "delete"`) | Permanently delete messages already in Trash or Spam; others counted in `skipped` | | `POST /api/messages/empty` (`{ mailboxId, folder: "trash" \| "spam" }`) | Delete 100 at a time; returns `{ deleted, remaining }`. Repeat until `remaining` is 0. | | `GET`/`PATCH /api/settings/trash-retention` (`{ days }`) | Auto-delete after 1–365 days; `null` for never | | `POST /api/drafts` (`forwardOfMessageId`) | Draft with the source's attachments | | `DELETE /api/drafts/{id}/attachments/{attachmentId}` | Remove one | | `POST /api/send` (`draftId`) | Send the draft with stored and uploaded files | Permanent deletes are audit-logged (`email.delete`). Auto-delete (**Settings → Inbox → Trash and Spam clean-up**) covers your own mailboxes and runs in batches of 200. Message downloads require mailbox access. ## Domain management Adding or removing a domain also changes Cloudflare resources. See [providers](providers.md). | Admin key (`domains`) | Purpose | | --- | --- | | `GET /api/v1/domains` | `{ domains, dns }`; `dns[id].auth` shows `ok` / `missing` / `unknown` for MX, SPF, DKIM, DMARC | | `POST /api/v1/domains` | Connect a domain | | `GET /api/v1/domains/[id]` | Get one | | `DELETE /api/v1/domains/[id]` | [Schedule removal](#removing-a-domain) | | `GET`/`DELETE /api/v1/domains/[id]/deletion` | Preview mailbox choices; cancel removal | | `GET /api/v1/domains/[id]/dns` | Full DNS check | | `POST /api/v1/domains/[id]/dns/setup` | Create a missing record: `{ "record": "mx" \| "spf" \| "dkim" \| "dmarc" }` | Create fields: `{ hostname, enableRouting?, enableSending?, replaceMxRecords?, receivingProvider?, sendingProvider? }`. Providers are `none`, `cloudflare`, `resend` or `ses`. Receiving defaults to `cloudflare`; sending to `cloudflare`, or `none` if `enableSending` is `false`. Cloudflare routing and sending are set up only when chosen. The hostname must be a zone apex, or a subdomain, that your Cloudflare credentials can access. Creating a mailbox also creates its Cloudflare routing rule to the `mailflare` Worker. DMARC setup creates `v=DMARC1; p=none`. DNS setup fails for manually managed DNS. ### Dashboard routes Session auth. | Route | Purpose | | --- | --- | | `GET`/`POST /api/domains`, `GET /api/domains/[id]`, `GET /api/domains/[id]/dns` | As above | | `DELETE /api/domains/[id]` | Schedule removal | | `GET`/`DELETE /api/domains/[id]/deletion` | Preview; cancel a removal not started, or stuck | | `PUT /api/domains/[id]/sending`, `.../receiving` | Choose provider: `{ provider }` | | `GET /api/domains/[id]/sending`, `.../receiving` | Providers with configuration | | `DELETE /api/domains/[id]/sending`, `.../receiving` | Clean up an unselected provider: `{ target }` | | `GET`/`POST /api/domains/[id]/resend`, `.../ses` | Sending status, setup, verify, test | | `GET`/`POST /api/domains/[id]/receiving/[provider]` | Receiving checklist and setup (`resend`, `ses`; `POST` also `cloudflare`). `409 MX_CONFLICT` until `{ replaceMx: true }`. | | `GET`/`PUT`/`DELETE /api/admin/resend-key` | Shared Resend key (primary admin) | | `GET`/`PUT`/`POST`/`DELETE /api/admin/aws` | AWS credentials; `PUT` validates, `POST` re-checks (primary admin) | ### Removing a domain Removal happens **7 days** later and can be cancelled until it runs. You must choose for every mailbox, or you get `409 MAILBOX_CHOICES_REQUIRED`: ```json { "mailboxes": { "mbx_1": { "action": "move", "domainId": "dom_2" }, "mbx_2": { "action": "delete" } } } ``` | Action | Effect | | --- | --- | | `move` | Keeps name and mail; old address stops working; matching login email changes | | `delete` | **Deletes mailbox and mail permanently** | The primary admin's first personal mailbox can only be moved. Large removals take several runs. If a choice becomes impossible, removal stops and shows why: cancel and reschedule. A removal running normally cannot be cancelled. To force past MTA-STS, see [force delete](mta-sts.md#force-delete). ## Account and mailbox management Accounts need a Pro or Team license; shared mailboxes need Team. A key reaches only accounts its owner created, and mailboxes of those accounts or the admin. | Scope | Route | Purpose | | --- | --- | --- | | `accounts` | `GET /api/v1/accounts` | List | | `accounts` | `POST /api/v1/accounts` | Create: `{ username, domainId, password, role?, useAllDomains?, aliases? }` | | `accounts` | `GET /api/v1/accounts/[id]` | Get | | `accounts` | `PATCH /api/v1/accounts/[id]` | `{ name, role, disabled, canManageMailboxes, calendarEnabled?, driveEnabled?, forwardingEmail?, password? }` | | `mailboxes` | `GET /api/v1/mailboxes` | List | | `mailboxes` | `POST /api/v1/mailboxes` | `{ domainId, localPart, displayName?, type?, ownerUserId? }` | | `mailboxes` | `GET`/`PATCH /api/v1/mailboxes/[id]` | Get; update | | `mailboxes` | `DELETE /api/v1/mailboxes/[id]` | Delete (409 for the primary admin's primary mailbox) | | `storage` | `GET /api/v1/storage` | `{ storage: { provider, configured, bucket, endpoint }, warning }`; no credentials | | `storage` | `POST /api/v1/storage` | Test: `{ ok, error?, latencyMs, storage }` (502 on failure) | - `provider` is `backblaze`, `s3`, `r2` or `files` ([storage setup](deployment.md#object-storage-r2-backblaze-b2-or-aws-s3)). - Admin keys may set `forwardingEmail` without extra confirmation, except on the owner's own account (`403 verification_required`; use the web app). - With **Allow MCP access**, admin keys offer `manage_domains`, `manage_accounts`, `manage_mailboxes`, `manage_storage` on `/mcp`. No mail tools. ### Create an account with aliases ```json { "username": "sam", "domainId": "dom_example_com", "password": "REPLACE_WITH_A_STRONG_PASSWORD", "useAllDomains": false, "aliases": [{ "domainId": "dom_example_net", "localPart": "sales" }] } ``` This creates `sam@example.com` with alias `sales@example.net`. For MCP, pass it as `data` to `manage_accounts` with `action: "create"`. - **API and MCP default `useAllDomains` to `true`.** Pass `false` for chosen aliases only. The dashboard defaults to `false`. - `useAllDomains` receives and sends as the username on all your active domains, including future ones. - Alias domains must be active and yours. Duplicates are refused, including dot and plus variants. - An alias shares the mailbox's mail and sending rights. - Creation is all-or-nothing. If Cloudflare routing fails, changes are rolled back; the response says if you must check by hand. ### Masked addresses On a mailbox's settings page, **Generate masked address** creates a random alias with an optional label. Mail sent from it shows only the label or address, and replies default to it. Turning it off stops its mail, including catch-all. ## Calendar | Route | Purpose | | --- | --- | | `GET /api/calendar/events?start=&end=` | List an ISO 8601 range (default next 31 days); series appear once | | `POST /api/calendar/events` | `{ title, startsAt, endsAt, description?, location?, attendees?, color?, repeat?, repeatDays?, timeZone?, mailboxId?, from? }` | | `PATCH /api/calendar/events/[eventId]` | Update; use an occurrence ID or `effectiveFrom` to change from there on | | `DELETE /api/calendar/events/[eventId]` | Delete an event, or a series from an occurrence | Auth: session, or a key with `calendar:read` / `calendar:write`. Invitations also need `send` on the mailbox. - `repeat`: `daily`, `weekly`, `monthly`, `weekdays`, with an optional end and skipped dates. - With attendees and a sending mailbox, invitations, updates and cancellations are emailed as `.ics`. Failed addresses are returned in `inviteErrors`. - MCP and assistant events send no invitations ([tools](email-assistant-and-mcp.md#calendar-tools)). ## Booking pages Open **Booking** to create an event type: name, link, duration, location, weekdays, time ranges, time zone, on/off. Two disabled templates (15 and 30 minutes) get you started. Public pages need no login: `/book/` and `/book//`. The username is derived from your email and unique; admins can change it. - Slots: every 15 minutes, 1 hour to 60 days ahead, only when free. Two guests cannot take one slot. - The guest enters name, email, optional guests and notes. The booking is added to the host's calendar. Only the booker gets a confirmation email with a calendar file, from the event owner's mailbox (customizable per event). - Team license: add co-hosts; a slot needs everyone free. | Route | Purpose | | --- | --- | | `GET`/`POST /api/booking` | List or create your events | | `PATCH`/`DELETE /api/booking/[eventId]` | Update or delete | | `PATCH /api/booking/settings` | Change username (admin) | | `GET /api/public/booking?username=` | Public: host and events | | `GET /api/public/booking/[eventId]?username=` | Public: open slots | | `POST /api/public/booking/[eventId]?username=` | Public: book (`{ name, email, startsAt, guestEmails?, notes? }`) | ## JMAP **JMAP** is an open protocol for mail apps (RFC 8620, 8621). 1. Create an app password under **Settings → App passwords** and pick mailboxes ([security](security.md#app-passwords)). 2. Point the client to `/.well-known/jmap`. A GET without credentials redirects to `/jmap/session`; a GET with credentials returns the session there. The discovery URL also accepts JMAP POST requests and OPTIONS preflights. If the client asks for a full session URL, copy it from **Settings → App passwords**. 3. Authenticate with Bearer, or HTTP Basic with the key as password (any username). **Use HTTPS.** Plain HTTP works but exposes the key. The account ID is your user ID. Each mailbox has `inbox`, `drafts`, `sent`, `archive`, `junk`, `trash` and your folders. A message is in exactly one. | Methods | Support | | --- | --- | | `Mailbox/get\|query\|set\|changes` | Yes (`set` for folders only) | | `Thread/get\|changes` | Yes | | `Email/get\|query\|set\|import\|changes` | Yes | | `Identity/get\|set\|changes`, `EmailSubmission/get\|query\|set\|changes` | Yes | | `SearchSnippet/get`, `Core/echo` | Yes | | `Email/copy`, `Email/parse` | No | - Real change lists: `Email/changes`, `Mailbox/changes`, `Thread/changes`. `*/queryChanges`, `Identity/changes` and `EmailSubmission/changes` return `cannotCalculateChanges`; query again. - `/jmap/eventsource` pushes changes by polling. - `Email/set` creates drafts, sets `$seen` and `$flagged`, moves, and destroys (Trash first). - `EmailSubmission/set` sends a draft, which is reported destroyed. - Upload and download use the session's URLs. - `Email/query` header filter supports only `Message-ID`, `In-Reply-To`, `References` (angle brackets and case ignored). Example: `["Message-ID", ""]`. Others return `unsupportedFilter`. ### Import a message For clients that build MIME: upload a `message/rfc822` blob, call `Email/import`, then `EmailSubmission/set`. - Fields: `blobId`, `mailboxIds`, optional `keywords`, `receivedAt`. - **Target exactly one Drafts mailbox.** - `$seen` and `$flagged` are kept; `$draft` is implied. - Date: `receivedAt`, else the `Date` header, else now. - The original bytes and `Message-ID` are preserved. - Errors: `blobNotFound`, `invalidEmail`, `invalidProperties`, `forbidden` (From not allowed), `tooLarge`. ## Sign-in and security ### Password reset | Route | Behavior | | --- | --- | | `POST /api/auth/password-reset/request` `{ email }` | Always `200`. Mails a 30-minute single-use link if the account is enabled and has a recovery email. | | `POST /api/auth/password-reset/confirm` `{ token, password }` | Sets the password and signs out everywhere | A passkey-only account that sets a password this way then needs a passkey too. ### Passkeys and two-step sign-in | Task | Route | | --- | --- | | Passwordless sign-in | `POST /api/auth/passkey/options`, then `/verify` | | Password sign-in with second step | `POST /api/auth/login` returns `{ ok, mfaRequired, challengeToken, methods }` (`passkey`, `totp`, `recovery`) | | Finish with passkey | `/api/auth/passkey/mfa/options`, then `/verify` | | Finish with code | `POST /api/auth/mfa/verify` | | Manage passkeys | `/api/settings/passkeys/*` | | Test a passkey (changes nothing) | `POST /api/settings/passkeys/check/options`, then `/verify` → `{ ok, passkeyId }` | | Turn off authenticator | `POST /api/settings/mfa/disable` | | Change password | `PATCH /api/settings/password` `{ currentPassword, newPassword }`, plus `stepUpToken` or `code` if a second step is required | | Add password (passkey-only) | `POST /api/settings/password` `{ newPassword, stepUpToken, requireSecondFactor? }` | | Remove password | `DELETE /api/settings/password` | | Remove passkey | `DELETE /api/settings/passkeys/:id` | - Challenges expire in 5 minutes. - A passkey is a full second step. Recovery codes work only with the authenticator app. - Removing the authenticator keeps your second-step rule. Removing the last passkey needs a password; without an authenticator, the second step turns off. Passkey-only accounts cannot remove it (`last_method`). - One `password.set` grant covers the password and second-step choice; omitting the choice keeps it. - Changing sign-in methods cancels open recovery and reset links. ### Confirm sensitive changes These need a fresh identity check ("step-up"): `passkey.add`, `passkey.remove`, `password.set`, `password.remove`, `password.change`, `mfa.enroll`, `mfa.disable`, `mfa.codes`, `second_factor.toggle`, `profile.recovery_email`, `routing.forward`, `webhook.change`, and admin actions such as `admin.forwarding_email` and `admin.transfer_primary`. - Get a grant from `POST /api/auth/step-up`, or `/step-up/options` + `/step-up/verify` (passkey). - Grants work once, for one session, action, user and target. Security changes void them. - Authenticator management and admin recovery links also accept the password (plus code if required). - Missing or bad proof returns `401` `verification_failed`. - `routing.forward` covers new, retargeted, rematched or re-enabled forwards to addresses outside your accessible mailboxes. - `webhook.change` covers new webhooks, URL changes, new events and re-enabling. ### Recover a lost passkey An admin can issue a one-time enrollment link on the account page. If you are the only admin, run from a source checkout: ```bash npm run auth:recovery-link -- admin@example.com https://mail.example.com ``` Send the 30-minute link safely. With `DATABASE_URL` it writes to the database. Without it, it prints `wrangler d1 execute DB --remote` commands. For default Docker, run the printed SQL against `mailflare.sqlite` in `DATA_DIR` with `sqlite3` on the host. ## Inbound provider endpoints Public routes that authenticate themselves. | Route | Checked by | | --- | --- | | `POST /api/inbound/resend` | Svix signature | | `POST /api/inbound/ses?token=…` | URL token, SNS topic, message read from your bucket | | `POST /api/inbound` | HMAC from the [relay Worker](deploy-docker.md#cloudflare-email-routing-relay) | ## Real-time updates New mail is pushed over a WebSocket (Durable Object, `REALTIME` binding in `wrangler.jsonc`) to everyone with mailbox access. If it drops, the app reconnects and refreshes slowly meanwhile. [Vercel](deploy-vercel.md#limits) uses polling. ## Troubleshooting | Problem | Cause | Fix | | --- | --- | --- | | 404 on send | Limited key without `mailboxId` | Include it | | Keys stopped working | Password or two-step changed | Create new keys | | `403 verification_required` | Owner forwarding change | Use the web app | | `422 SUPPRESSED_RECIPIENT` | [Suppression list](deliverability.md) | Remove the entry or address | | `409 MX_CONFLICT` | Other MX records | Send `replaceMx: true` |