Mailman API
A REST API to send, receive, search, and organize email programmatically. Authenticate with an mm_ key, call JSON endpoints, and (optionally) receive signed webhooks for inbound mail and delivery events.
Introduction
Every endpoint lives under /v1, speaks JSON, and is authenticated with a bearer API key. A single key belongs to one owner and is granted a set of scopes and access to one or all of the owner's mailboxes (accounts). Use it to build transactional email, inbound-mail automations, inbox tooling, or a full mail client.
Base URL
https://mail.baliyang.com/v1All paths in this reference are relative to that base. Requests are server-to-server (send the key from your backend, never from a browser). All requests must be HTTPS.
Quickstart
Send your first email in three steps.
- Create a key in the Mailman app (Settings → API keys). Pick scopes (at least
send) and either a specific mailbox or all mailboxes. The full key is shown once — copy it. - Store it as a secret in your service (e.g.
MAILMAN_KEY). It looks likemm_ab12cd34_…. - Send:
curl -X POST https://mail.baliyang.com/v1/emails \
-H "Authorization: Bearer $MAILMAN_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: welcome-user-9f3a" \
-d '{
"to": [{ "address": "user@example.com", "name": "New User" }],
"subject": "Welcome to Acme",
"text": "Thanks for signing up!",
"html": "<p>Thanks for signing up!</p>"
}'{
"messageId": "<9f3a…@baliyang.com>",
"threadId": 1024,
"dbId": 50231,
"sentAt": 1737700000000,
"tag": null
}Authentication
Pass your key as a bearer token on every request:
Authorization: Bearer mm_ab12cd34_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxKeys have the shape mm_<prefix>_<secret>. The 8-character prefix is safe to log or display for identification; the secret is only shown once at creation and is stored SHA-256-hashed — Mailman can never show it again. Rotate by creating a new key and revoking the old one.
invalid_key.Scopes
Each key carries a set of scopes. A request that needs a scope the key lacks returns 403 insufficient_scope with the required and granted fields.
| Scope | Grants |
|---|---|
send | Send email (POST /v1/emails) |
inbox:read | Read threads, messages, labels, filters, key context |
inbox:modify | Archive / trash / read / snooze threads, manage labels & filters |
search | Full-text search (GET /v1/search) |
attachments:read | Download attachments |
attachments:write | Upload attachments to send |
admin:tenant | Reserved for tenant management, and no /v1 endpoint checks it yet. Only the operator can issue it, and only on a key whose owner is an admin of that mailbox's tenant. It does not appear in anyone else's key dialog. |
The list of valid scopes is the one in the Mailman key dialog; an unknown scope is rejected with 400 invalid_scope, and a reserved scope you may not grant with 403 scope_not_grantable. A key never reaches further than its owner: it only acts on mailboxes its owner owns at the time of each request, and "all mailboxes" means all of the owner's. Grant the minimum a service needs. A transactional-email service usually needs only send (plus attachments:write if it sends files).
Accounts (mailboxes)
An owner can have several mailboxes ("accounts"). How a request picks one:
- All-mailboxes key — pass any
accountIdyou own; if omitted, the key'sdefaultAccountIdis used. - Single-mailbox key — you may omit
accountId(the bound mailbox is used) or pass that same id. A different id returns 403account_not_authorized_by_key. - If a key has no default and you omit
accountId, you get 400account_required.
Read the current key's owner, scopes, default account, and mailbox list from GET /v1/me.
Rate limits & quotas
- Daily send quota: up to 1000 sends per key per day. Exceeding returns 429
send_daily_limit_exceeded(with alimitfield). - Per-key request quota: a key may carry an optional daily request cap; exceeding returns 429
key_daily_limit_exceeded. - Messages larger than 5 MiB encoded (about 3.5 MB of raw attachments in total) are rejected for sending; upload returns 413
attachment_too_large. - Only successful (2xx/3xx) requests count against quotas. Windows are hourly/daily buckets, not per-second throttling.
Idempotency
Send POST /v1/emails with an Idempotency-Key header (any unique string, ≤ 255 chars) so retries never send twice.
- Replaying the same key within 24 hours returns the original response — no duplicate message is created.
- A concurrent request with the same key while the first is still in flight returns 409
idempotency_in_progress— retry in a few seconds. - Best practice: derive the key from your own event id (e.g.
invoice-4821-receipt), so a retry of the same logical action reuses it.
Errors
Errors are JSON with a machine-readable error code and an optional human detail. Validation errors add field; scope errors add required/granted; rate limits add limit.
{
"error": "insufficient_scope",
"required": "send",
"granted": ["inbox:read", "search"]
}| Status | Code | Meaning |
|---|---|---|
| 400 | invalid_json / missing_fields / invalid_input | Bad body, missing required field, or a malformed value (see field). |
| 400 | invalid_id / idempotency_key_too_long / invalid_scope | Non-numeric id, an Idempotency-Key over 255 chars, or an unknown scope. |
| 400 | account_required | No accountId and the key has no default. |
| 401 | unauthorized / invalid_key | Missing/malformed header, or a revoked/unknown/expired key. |
| 403 | insufficient_scope | Key lacks the required scope. |
| 403 | account_not_authorized_by_key / forbidden | The key isn't allowed on that mailbox. |
| 403 | owner_disabled | The key's owner account has been disabled. |
| 404 | not_found | Thread / message / label / filter / attachment doesn't exist. |
| 409 | idempotency_in_progress | A send with the same Idempotency-Key is still processing. |
| 413 | attachment_too_large | An uploaded file exceeds the per-file limit (maxBytes in the response). |
| 429 | send_daily_limit_exceeded / key_daily_limit_exceeded | Quota hit — back off and retry later. |
| 502 | send_failed | Transient delivery failure — safe to retry (use an Idempotency-Key). |
| 503 | sending_not_enabled | The sender domain isn't onboarded for sending. |
Getting access
Everything programmatic (the REST API and the MCP server) runs on an mm_ API key. There are two ways to get one.
If you have your own Mailman login
- Open the Mailman app and go to Settings → API keys, then click + New key.
- Give it a name (for example
claude-mcporbilling-service) and choose the mailbox it may use, or tick All accounts I own. - Tick the scopes it needs and optionally set an expiry in days.
- Create it, then copy the key immediately. It is shown once; only a hash is stored.
If the operator issues it for you
Users who don't sign in to Mailman themselves get their key from the operator. In Settings → API keys, under Other accounts' keys, the operator opens the + New key for… menu and picks the person. The key belongs to that person and can only target that person's own mailboxes. The operator then picks the mailbox (or all of that person's mailboxes), the scopes and an expiry, creates the key, and passes it on over a private channel. It is shown once, so the operator should hand it over straight away or put it directly into the MCP worker (see MCP setup) rather than pasting it into chat.
Choosing scopes: least privilege
| Use case | Scopes |
|---|---|
| Transactional email from a service | send (plus attachments:write if it sends files) |
| Read-only assistant: summarize and search the inbox | inbox:read, search (add attachments:read to open attachments) |
| Assistant that triages (archive, label, snooze) | read-only set plus inbox:modify |
| Assistant that also sends on your behalf | triage set plus send |
- Prefer a single-mailbox key over an all-mailboxes key.
- Set an expiry (for example 90 days) for anything that isn't a long-lived server integration.
- Don't ask for
admin:tenant; it is reserved and grants nothing on/v1today. - One key per integration, so you can revoke one without breaking the rest.
Onboarding a domain
Mailman can receive and send mail for any domain whose DNS is managed on the operator's Cloudflare account. Domains are managed at Admin → Domains. Adding a domain is done by the operator; as a tenant admin you prepare the domain and then manage the mailboxes under it.
Before you start
- The domain must be registered, and its DNS (a Cloudflare zone) must be on the operator's Cloudflare account. Ask the operator how to move or delegate it.
- Decide who the domain admin is (an email address they sign in with) and the first mailbox address, for example
you@yourdomain.
Steps
- Open Admin → Domains and choose Onboard a domain.
- Enter the Domain (for example
yourdomain.com). Optionally set the Admin email (defaults to whoever is onboarding) and a Default account (the first mailbox). - Submit. Mailman looks up the zone, turns on inbound routing with a catch-all rule, and creates the domain record, its admin and the first mailbox. The dialog lists each step as
ok,skippedorerror. The request itself can succeed while an individual step reports an error, so read the list. - Sending is a separate step. Outbound mail has to be enabled for the domain in Cloudflare (Email Sending) before the Sending toggle on the domain's row is turned on; if the toggle is on first, sends fail with 503
sending_not_enabled. The operator does both. - Back in Admin → Domains, confirm Routing and Sending both show enabled.
After onboarding
- Add more mailboxes under the domain from the admin pages, and invite their owners.
- Send a test message in and out. New domains often land in the recipient's spam folder at first; that is sender reputation warming up, not a fault. Mark it "not spam" and keep sending real mail.
- If the domain already had SPF set (or a parked
v=spf1 -allrecord), tell the operator, since two SPF records break SPF.
MCP setup
Mailman ships an MCP server so Claude can read your inbox, search, and send on your behalf, using the same key and scopes as the REST API. The server can only do what its key's scopes allow.
Recommended: a hosted per-user MCP worker
The operator deploys a small Cloudflare Worker just for you, holding your API key as a Worker secret and protected by its own bearer token. Your client only ever sees the worker URL and the token, never the mm_ key. You receive two things:
- the worker URL,
https://<worker>/mcp - a bearer token,
<token>
Claude Code
claude mcp add --transport http mailman https://<worker>/mcp --header "Authorization: Bearer <token>"Then start Claude Code (or run /mcp inside it) and check that mailman is connected.
Claude desktop app
The desktop app launches MCP servers as local commands, so use the mcp-remote bridge. Add this to claude_desktop_config.json (Settings → Developer → Edit Config), then quit and reopen the app. It needs Node.js installed.
{
"mcpServers": {
"mailman": {
"command": "npx",
"args": [
"-y",
"mcp-remote",
"https://<worker>/mcp",
"--header",
"Authorization: Bearer <token>"
]
}
}
}https://mail.baliyang.com/v1 directly is rejected (typically a 403 challenge). The hosted worker reaches Mailman through an internal binding that bypasses it, which is why hosted is the supported path.Tools
| Tool | What it does |
|---|---|
send_email | Send mail from the key's default mailbox (or a given accountId). Needs send. |
list_threads | List Inbox, Sent, Archive or Trash with cursor pagination. |
read_thread | A thread with all its messages (text bodies inline). |
search | Full-text search over subject, snippet, body and addresses. |
get_message | One message by numeric id or Message-ID. |
get_account_info | The key's owner, allowed mailboxes and scopes. |
The server also exposes label, filter and thread-action tools (archive, trash, snooze, mark read), available when the key has inbox:modify.
Troubleshooting
| Symptom | Fix |
|---|---|
command not found: claude | Install Claude Code: curl -fsSL https://claude.ai/install.sh | bash, then open a new terminal. |
command not found: npx (desktop app) | Install Node.js, then restart the desktop app. |
| 401 Unauthorized from the worker | The bearer token is wrong or was rotated. Ask the operator for the current one, and check there is a single Bearer prefix. |
A tool returns insufficient_scope | The key lacks that scope (for example no send). Ask for a key with the scope you need. |
A tool returns invalid_key | The key was revoked or expired. Ask for a new one; the operator updates the worker's secret. |
| Server shows as failed / tools missing in the desktop app | Quit the app fully and reopen after editing the config; validate the JSON; confirm npx -y mcp-remote <url> --header "Authorization: Bearer <token>" runs in a terminal. |
| 403 / challenge page when running a local MCP against the public host | Expected; use the hosted worker instead (see above). |
Send email
sendSend a message from one of your mailboxes. Supports plain text and/or HTML, CC/BCC, reply threading, attachments, and a free-form tag.
| Field | Type | Notes | |
|---|---|---|---|
to | Address[] | required | 1–50 recipients. Each is { "address": string, "name"?: string }. |
subject | string | required | Up to 998 bytes. |
text | string | required | Plain-text body (≤ 1 MB). Always send this, even with HTML. |
html | string | optional | HTML body (≤ 1 MB). |
accountId | number | optional | Sending mailbox; defaults to the key's default. |
cc, bcc | Address[] | optional | Same shape as to. |
replyTo | string | optional | Reply-To address. |
inReplyTo | string | optional | A Message-ID to reply to (RFC 5322). |
references | string | optional | Space-separated Message-IDs for threading. |
tag | string | optional | Your label for the send (echoed back & stored). |
attachments | Attachment[] | optional | Up to 20. Each is { key, filename, mime, size } from the upload endpoint. |
curl -X POST https://mail.baliyang.com/v1/emails \
-H "Authorization: Bearer $MAILMAN_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-4821-shipped" \
-d '{
"accountId": 5,
"to": [{ "address": "buyer@example.com", "name": "Buyer" }],
"cc": [{ "address": "ops@acme.co" }],
"subject": "Your order shipped",
"text": "Tracking: 1Z999…",
"html": "<p>Tracking: <b>1Z999…</b></p>",
"tag": "transactional"
}'{
"messageId": "<a1b2…@baliyang.com>",
"threadId": 2048,
"dbId": 99123,
"sentAt": 1737700123000,
"tag": "transactional"
}Get a message
inbox:read:id may be a numeric message id or a Message-ID header (with or without the angle brackets). Returns metadata + delivery status; fetch the full thread for bodies & attachments.
{
"id": 99123,
"threadId": 2048,
"messageId": "<a1b2…@baliyang.com>",
"subject": "Your order shipped",
"direction": "out",
"from": { "address": "shop@acme.co" },
"to": [{ "address": "buyer@example.com" }],
"sentAt": 1737700123000,
"hasAttachments": false,
"deliveryStatus": "delivered",
"deliveryError": null,
"tag": "transactional"
}Get a message (full)
inbox:readOne stored message by numeric id, with its text and HTML bodies and its attachment list (use the attachment ids with GET /v1/attachments/:id). Built for webhook consumers: mail.received carries the message id, and this is where you read it. Unlike the in-app thread view it never marks anything read.
List threads
inbox:readCursor-paginated list of threads in a mailbox folder.
| Query | Notes | |
|---|---|---|
accountId | optional | Defaults to the key's default mailbox. |
folder | optional | inbox (default), sent, archive, trash, all. |
limit | optional | Default 50, max 200. |
cursor | optional | Pass nextCursor from the previous page. |
curl -H "Authorization: Bearer $MAILMAN_KEY" \
"https://mail.baliyang.com/v1/threads?accountId=5&folder=inbox&limit=25"{
"threads": [
{
"id": 2048,
"subject": "Project sync",
"snippet": "Let's line up Q3…",
"participants": [{ "name": "Alice", "address": "alice@x.com" }],
"lastMessageAt": 1737700000000,
"messageCount": 6,
"unreadCount": 1
}
],
"nextCursor": "1737699000000"
}Get a thread
inbox:readThe thread plus every message (with plain-text bodies and attachment counts).
{
"thread": { "id": 2048, "subject": "Project sync", "unreadCount": 1, "archived": false, "trashed": false },
"messages": [
{
"id": 99120,
"direction": "in",
"from": { "name": "Alice", "address": "alice@x.com" },
"to": [{ "address": "you@acme.co" }],
"subject": "Project sync",
"text": "Full plain-text body…",
"sentAt": 1737699000000,
"read": true,
"attachmentCount": 1
}
]
}Archive · Trash · Read · Spam · Snooze
inbox:modifyEach takes a small JSON body and returns { "ok": true }.
| Endpoint | Body |
|---|---|
…/archive | { "archived": true } (or false to un-archive) |
…/trash | { "trashed": true } (or false to restore) |
…/read | { "read": true } (marks all messages read/unread) |
…/spam | { "spam": true } (or false to mark not-spam) |
…/snooze | { "until": 1737800000000 } (ms timestamp, or null to un-snooze) |
Thread labels
inbox:readinbox:modifyinbox:modifyApply with { "labelId": 3 } (the label must belong to the thread's mailbox). All return { "ok": true }; GET returns { "labels": [{ "id", "name", "color" }] }.
Labels
inbox:readinbox:modifyinbox:modifyCreate with { "name": "Receipts", "color": "#34d399", "accountId": 5 }. List with ?accountId=5 (or ?accountId=all for a multi-mailbox key).
{
"labels": [
{ "id": 3, "accountId": 5, "name": "Receipts", "color": "#34d399", "threadCount": 42 }
]
}Search
searchFull-text search with Gmail-style operators. q is required; accountId (or all) and limit (max 100) are optional.
| Operator | Matches |
|---|---|
from:alice@x.com | sender |
to:me@acme.co | recipient |
subject:invoice | subject contains |
has:attachment | has an attachment |
is:unread · is:read · is:sent | state |
before:2026-01-01 · after:2025-12-01 | date range |
curl -H "Authorization: Bearer $MAILMAN_KEY" \
"https://mail.baliyang.com/v1/search?q=from:stripe%20is:unread&accountId=all"Filters
inbox:readinbox:modifyinbox:modifyinbox:modifyFilters run on inbound mail: a match (substring on from/to/subject/body, or hasAttachment) triggers an ordered list of actions. POST creates (omit id) or updates (include id); run-on applies a filter to one thread for testing.
{
"accountId": 5,
"name": "Auto-file receipts",
"enabled": true,
"stopOnMatch": false,
"match": { "subject": "receipt", "hasAttachment": true },
"actions": [
{ "type": "apply_label", "label_id": 3 },
{ "type": "mark_read" },
{ "type": "archive" }
]
}Action types: apply_label (with label_id), archive, mark_read, add_to_contacts.
Attachments
attachments:writeattachments:readSending a file is two steps: upload the raw bytes to get a key, then reference that key in POST /v1/emails. Up to 20 attachments per message.
curl -X POST "https://mail.baliyang.com/v1/attachments/upload?accountId=5" \
-H "Authorization: Bearer $MAILMAN_KEY" \
-H "Content-Type: application/pdf" \
-H "X-Filename: invoice.pdf" \
--data-binary @invoice.pdf{
"key": "5/uploads/9f3a…-invoice.pdf",
"filename": "invoice.pdf",
"mime": "application/pdf",
"size": 102400
}{
"to": [{ "address": "buyer@example.com" }],
"subject": "Your invoice",
"text": "Attached.",
"attachments": [
{ "key": "5/uploads/9f3a…-invoice.pdf", "filename": "invoice.pdf", "mime": "application/pdf", "size": 102400 }
]
}Download an inbound attachment by its id (found on a message): GET /v1/attachments/:id returns the raw bytes with a Content-Disposition filename.
Key context
Introspect the current key — owner, scopes, default mailbox, and the mailboxes it can reach. Useful at startup to validate a key and discover account ids.
{
"owner": { "id": 1, "email": "you@acme.co", "displayName": "Acme" },
"key": { "id": 42, "scopes": ["send", "inbox:read"], "allAccounts": false, "defaultAccountId": 5, "dailyLimit": null },
"accounts": [
{ "id": 5, "address": "shop@acme.co", "displayName": "Shop" }
]
}Webhooks
Register an HTTPS endpoint in the Mailman app to receive events for inbound mail and outbound delivery. Every delivery is signed so you can verify it came from Mailman.
Events
| Type | Fires when |
|---|---|
mail.received | An inbound message arrives |
email.queued · email.delivered | Outbound send accepted / delivered |
email.bounced · email.complaint | Delivery failed / spam complaint |
thread.archived · thread.trashed · thread.read_changed | Thread state changed |
thread.purged · trash.emptied | A thread was permanently deleted / the trash was emptied |
message.read | A message was marked read |
account.created · account.deleted | A mailbox was added to / removed from a domain (admin events) |
tenant_admin.added · tenant_admin.removed | A domain admin was added / removed (admin events) |
Delivery
Mailman POSTs JSON to your URL with these headers:
Content-Type: application/json
X-Mailman-Event-Id: 7f1c… # unique per event
X-Mailman-Event-Type: email.delivered
X-Mailman-Attempt: 1 # 1–5
X-Mailman-Signature: t=1737700000,v1=<hex-hmac-sha256>{
"id": "7f1c…",
"type": "email.delivered",
"createdAt": 1737700000000,
"data": { "messageId": "<a1b2…>", "threadId": 2048, "accountId": 5, "deliveryStatus": "delivered" }
}Verify the signature
The signature is HMAC-SHA256("<t>.<raw-body>") using the endpoint's signing secret (a hex string shown once when you create the endpoint). Compute it and constant-time-compare to the v1= value. Reject if t is older than ~5 minutes.
import crypto from "node:crypto";
function verify(rawBody, header, secret) {
const { t, v1 } = Object.fromEntries(header.split(",").map((p) => p.split("=")));
const expected = crypto.createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex");
const ok = crypto.timingSafeEqual(Buffer.from(v1), Buffer.from(expected));
const fresh = Math.abs(Date.now() / 1000 - Number(t)) < 300;
return ok && fresh;
}X-Mailman-Event-Id.Wire up a service
A minimal transactional-email helper in Node — the pattern most services need:
const BASE = "https://mail.baliyang.com/v1";
const KEY = process.env.MAILMAN_KEY; // mm_… kept server-side
export async function sendEmail({ to, subject, text, html, idempotencyKey }) {
const res = await fetch(`${BASE}/emails`, {
method: "POST",
headers: {
Authorization: `Bearer ${KEY}`,
"Content-Type": "application/json",
...(idempotencyKey && { "Idempotency-Key": idempotencyKey }),
},
body: JSON.stringify({ to, subject, text, html }),
});
const body = await res.json();
if (!res.ok) throw new Error(`mailman ${res.status}: ${body.error}`);
return body; // { messageId, threadId, sentAt, … }
}
// usage — idempotent per business event
await sendEmail({
to: [{ address: user.email, name: user.name }],
subject: "Password reset",
text: `Reset: ${link}`,
idempotencyKey: `pwreset-${resetToken}`,
});Mailman API · v1 · base https://mail.baliyang.com/v1