Mailman API

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

base url
https://mail.baliyang.com/v1

All 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.

  1. 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.
  2. Store it as a secret in your service (e.g. MAILMAN_KEY). It looks like mm_ab12cd34_….
  3. Send:
curl
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>"
  }'
200 response
{
  "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_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Keys 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.

Create & revoke keys in the Mailman web app (they're issued behind your own login, not via this API). Revoking a key takes effect immediately — subsequent requests return 401 invalid_key.
Never expose a key in client-side code, a mobile app bundle, or a public repo. Anyone with the key can act as its owner within its scopes. Treat it like a password; keep it server-side.

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.

ScopeGrants
sendSend email (POST /v1/emails)
inbox:readRead threads, messages, labels, filters, key context
inbox:modifyArchive / trash / read / snooze threads, manage labels & filters
searchFull-text search (GET /v1/search)
attachments:readDownload attachments
attachments:writeUpload attachments to send
admin:tenantReserved 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:

Read the current key's owner, scopes, default account, and mailbox list from GET /v1/me.

Rate limits & quotas

Idempotency

Send POST /v1/emails with an Idempotency-Key header (any unique string, ≤ 255 chars) so retries never send twice.

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.

example error
{
  "error": "insufficient_scope",
  "required": "send",
  "granted": ["inbox:read", "search"]
}
StatusCodeMeaning
400invalid_json / missing_fields / invalid_inputBad body, missing required field, or a malformed value (see field).
400invalid_id / idempotency_key_too_long / invalid_scopeNon-numeric id, an Idempotency-Key over 255 chars, or an unknown scope.
400account_requiredNo accountId and the key has no default.
401unauthorized / invalid_keyMissing/malformed header, or a revoked/unknown/expired key.
403insufficient_scopeKey lacks the required scope.
403account_not_authorized_by_key / forbiddenThe key isn't allowed on that mailbox.
403owner_disabledThe key's owner account has been disabled.
404not_foundThread / message / label / filter / attachment doesn't exist.
409idempotency_in_progressA send with the same Idempotency-Key is still processing.
413attachment_too_largeAn uploaded file exceeds the per-file limit (maxBytes in the response).
429send_daily_limit_exceeded / key_daily_limit_exceededQuota hit — back off and retry later.
502send_failedTransient delivery failure — safe to retry (use an Idempotency-Key).
503sending_not_enabledThe sender domain isn't onboarded for sending.
Retry policy: retry 429 (after a delay) and 502 (with the same Idempotency-Key). Do not blindly retry 400/401/403 — fix the request first.

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

  1. Open the Mailman app and go to Settings → API keys, then click + New key.
  2. Give it a name (for example claude-mcp or billing-service) and choose the mailbox it may use, or tick All accounts I own.
  3. Tick the scopes it needs and optionally set an expiry in days.
  4. 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 caseScopes
Transactional email from a servicesend (plus attachments:write if it sends files)
Read-only assistant: summarize and search the inboxinbox: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 behalftriage set plus send
Revoking: delete the key in the same Settings → API keys list. It stops working immediately. The operator can also revoke any user's key from Other accounts' keys.

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

Steps

  1. Open Admin → Domains and choose Onboard a domain.
  2. Enter the Domain (for example yourdomain.com). Optionally set the Admin email (defaults to whoever is onboarding) and a Default account (the first mailbox).
  3. 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, skipped or error. The request itself can succeed while an individual step reports an error, so read the list.
  4. 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.
  5. Back in Admin → Domains, confirm Routing and Sending both show enabled.

After onboarding

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:

Claude Code

add the server
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.

claude_desktop_config.json
{
  "mcpServers": {
    "mailman": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote",
        "https://<worker>/mcp",
        "--header",
        "Authorization: Bearer <token>"
      ]
    }
  }
}
Why not a local stdio MCP pointed at the public host? The Mailman host sits behind Cloudflare bot protection that blocks non-browser clients, so a locally run MCP calling 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

ToolWhat it does
send_emailSend mail from the key's default mailbox (or a given accountId). Needs send.
list_threadsList Inbox, Sent, Archive or Trash with cursor pagination.
read_threadA thread with all its messages (text bodies inline).
searchFull-text search over subject, snippet, body and addresses.
get_messageOne message by numeric id or Message-ID.
get_account_infoThe 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

SymptomFix
command not found: claudeInstall 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 workerThe 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_scopeThe key lacks that scope (for example no send). Ask for a key with the scope you need.
A tool returns invalid_keyThe 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 appQuit 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 hostExpected; use the hosted worker instead (see above).

Send email

POST/v1/emailsscope send

Send a message from one of your mailboxes. Supports plain text and/or HTML, CC/BCC, reply threading, attachments, and a free-form tag.

FieldTypeNotes
toAddress[]required1–50 recipients. Each is { "address": string, "name"?: string }.
subjectstringrequiredUp to 998 bytes.
textstringrequiredPlain-text body (≤ 1 MB). Always send this, even with HTML.
htmlstringoptionalHTML body (≤ 1 MB).
accountIdnumberoptionalSending mailbox; defaults to the key's default.
cc, bccAddress[]optionalSame shape as to.
replyTostringoptionalReply-To address.
inReplyTostringoptionalA Message-ID to reply to (RFC 5322).
referencesstringoptionalSpace-separated Message-IDs for threading.
tagstringoptionalYour label for the send (echoed back & stored).
attachmentsAttachment[]optionalUp to 20. Each is { key, filename, mime, size } from the upload endpoint.
curl
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"
  }'
200
{
  "messageId": "<a1b2…@baliyang.com>",
  "threadId": 2048,
  "dbId": 99123,
  "sentAt": 1737700123000,
  "tag": "transactional"
}

Get a message

GET/v1/emails/:idscope 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.

200
{
  "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)

GET/v1/messages/:idscope inbox:read

One 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

GET/v1/threadsscope inbox:read

Cursor-paginated list of threads in a mailbox folder.

QueryNotes
accountIdoptionalDefaults to the key's default mailbox.
folderoptionalinbox (default), sent, archive, trash, all.
limitoptionalDefault 50, max 200.
cursoroptionalPass nextCursor from the previous page.
curl -H "Authorization: Bearer $MAILMAN_KEY" \
  "https://mail.baliyang.com/v1/threads?accountId=5&folder=inbox&limit=25"
200
{
  "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

GET/v1/threads/:idscope inbox:read

The thread plus every message (with plain-text bodies and attachment counts).

200 (truncated)
{
  "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

POST/v1/threads/:id/archivescope inbox:modify
POST/v1/threads/:id/trash
POST/v1/threads/:id/read
POST/v1/threads/:id/spam
POST/v1/threads/:id/snooze

Each takes a small JSON body and returns { "ok": true }.

EndpointBody
…/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

GET/v1/threads/:id/labelsscope inbox:read
POST/v1/threads/:id/labelsscope inbox:modify
DELETE/v1/threads/:id/labels/:labelIdscope inbox:modify

Apply with { "labelId": 3 } (the label must belong to the thread's mailbox). All return { "ok": true }; GET returns { "labels": [{ "id", "name", "color" }] }.

Labels

GET/v1/labelsscope inbox:read
POST/v1/labelsscope inbox:modify
DELETE/v1/labels/:idscope inbox:modify

Create with { "name": "Receipts", "color": "#34d399", "accountId": 5 }. List with ?accountId=5 (or ?accountId=all for a multi-mailbox key).

GET /v1/labels → 200
{
  "labels": [
    { "id": 3, "accountId": 5, "name": "Receipts", "color": "#34d399", "threadCount": 42 }
  ]
}
GET/v1/searchscope search

Full-text search with Gmail-style operators. q is required; accountId (or all) and limit (max 100) are optional.

OperatorMatches
from:alice@x.comsender
to:me@acme.corecipient
subject:invoicesubject contains
has:attachmenthas an attachment
is:unread · is:read · is:sentstate
before:2026-01-01 · after:2025-12-01date range
curl -H "Authorization: Bearer $MAILMAN_KEY" \
  "https://mail.baliyang.com/v1/search?q=from:stripe%20is:unread&accountId=all"

Filters

GET/v1/filtersscope inbox:read
POST/v1/filtersscope inbox:modify
DELETE/v1/filters/:idscope inbox:modify
POST/v1/filters/:id/run-on/:threadIdscope inbox:modify

Filters 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.

POST /v1/filters body
{
  "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

POST/v1/attachments/uploadscope attachments:write
GET/v1/attachments/:idscope attachments:read

Sending 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.

1 · upload
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
→ 200
{
  "key": "5/uploads/9f3a…-invoice.pdf",
  "filename": "invoice.pdf",
  "mime": "application/pdf",
  "size": 102400
}
2 · attach in send
{
  "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

GET/v1/meno scope required

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.

200
{
  "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

TypeFires when
mail.receivedAn inbound message arrives
email.queued · email.deliveredOutbound send accepted / delivered
email.bounced · email.complaintDelivery failed / spam complaint
thread.archived · thread.trashed · thread.read_changedThread state changed
thread.purged · trash.emptiedA thread was permanently deleted / the trash was emptied
message.readA message was marked read
account.created · account.deletedA mailbox was added to / removed from a domain (admin events)
tenant_admin.added · tenant_admin.removedA 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>
payload
{
  "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.

node
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;
}
Retries: non-2xx responses are retried 5× with backoff (0s, 30s, 5m, 30m, 2h). After 5 consecutive failures the endpoint is auto-disabled. Return 2xx quickly and process asynchronously; dedupe on X-Mailman-Event-Id.

Wire up a service

A minimal transactional-email helper in Node — the pattern most services need:

mailman.js
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