Metadata-Version: 2.5
Name: cloudmail
Version: 1.0.0
Summary: Python SDK for cloudmail, self-hosted email on your own Cloudflare account: send and read mail, AI agent inboxes with approval, webhooks and realtime events.
Project-URL: Homepage, https://trycloudmail.com
Project-URL: Documentation, https://trycloudmail.com/docs
Project-URL: Repository, https://github.com/cloudmail-hq/cloudmail
Project-URL: Demo, https://demo.trycloudmail.com
Project-URL: Changelog, https://github.com/cloudmail-hq/cloudmail/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/cloudmail-hq/cloudmail/issues
Author: cloudmail
License-Expression: LicenseRef-FCL-1.0-ALv2
License-File: LICENSE
Keywords: agent-inbox,ai-agents,cloudflare,cloudflare-email,cloudflare-workers,cloudmail,email,email-api,email-routing,inbox,mcp,sdk,self-hosted,self-hosted-email,transactional-email,webhooks,webmail
Classifier: Development Status :: 5 - Production/Stable
Classifier: Framework :: Pydantic :: 2
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Communications :: Email
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Requires-Dist: pydantic<3,>=2.6
Provides-Extra: dev
Requires-Dist: httpx==0.28.1; extra == 'dev'
Requires-Dist: pydantic==2.14.1; extra == 'dev'
Requires-Dist: pytest==9.1.1; extra == 'dev'
Requires-Dist: respx==0.23.1; extra == 'dev'
Description-Content-Type: text/markdown

<p align="center">
  <a href="https://trycloudmail.com"><img src="https://raw.githubusercontent.com/cloudmail-hq/cloudmail/main/docs/images/logo.svg" alt="cloudmail" height="64"></a>
</p>

# cloudmail

The Python SDK for [cloudmail](https://trycloudmail.com): send and read email, run AI agent inboxes with human approval, verify webhooks and follow realtime events.

[cloudmail](https://trycloudmail.com) is self-hosted email on your own Cloudflare account: a full webmail app on Cloudflare Workers, with mail for your domains arriving through Cloudflare Email Routing. Every deployment has a REST API, signed webhooks, a realtime event stream and an MCP server, and AI agents get their own mailboxes whose sends wait for a person's approval. This package is the client for that API. It talks to your deployment, not to a service of ours.

[Website](https://trycloudmail.com) · [Live demo](https://demo.trycloudmail.com) · [API docs](https://trycloudmail.com/docs) · [For AI agents](https://trycloudmail.com/agents) · [Pricing](https://trycloudmail.com/pricing) · [GitHub](https://github.com/cloudmail-hq/cloudmail) · [Agent Skill](https://github.com/cloudmail-hq/skills)

## Install

```bash
pip install cloudmail
```

A typed, synchronous client built on `httpx` and `pydantic` v2. It needs Python 3.10 or later. It covers the REST API that API tokens can use: sending and reading mail, mailboxes, agent inboxes, approvals, webhooks, labels, threads, folders, rules, templates, sequences, domains, analytics and the rest. It sends idempotency keys automatically and retries safely.

Works with every cloudmail 1.x deployment. Verifying webhooks needs a deployment that sends the `X-Cloudmail-*` headers this package reads. The [changelog](https://github.com/cloudmail-hq/cloudmail/blob/main/CHANGELOG.md) names the release that added them; update your deployment to it or later.

You need a cloudmail deployment and an API token from it (Settings → API tokens). To get a deployment, see [trycloudmail.com/deploy](https://trycloudmail.com/deploy), or look around the [live demo](https://demo.trycloudmail.com) first. The [SDK guide](https://demo.trycloudmail.com/docs/sdks/python) has more examples.

## Usage

```python
from cloudmail import Cloudmail, is_pending_approval

cm = Cloudmail("https://mail.example.com", token="ttk_...")

result = cm.mail.send(
    "support@example.com",
    to="customer@example.org",
    subject="Your order shipped",
    text="It's on the way.",
)
if is_pending_approval(result):
    print("Waiting for approval:", result.approval_url)  # nothing was sent; don't retry
else:
    print("Sent:", result.id)

page = cm.mail.list("support@example.com", folder="inbox", unread=True, limit=20)
email = cm.mail.get("support@example.com", page.emails[0].id)
cm.mail.reply("support@example.com", email.id, to=email.sender, subject=f"Re: {email.subject}", text="Thanks!")

label = cm.labels.create("support@example.com", "Billing", color="#0a7")
cm.labels.add_to_email("support@example.com", email.id, label["id"])
thread = cm.threads.get("support@example.com", email.thread_id)

for msg in cm.mail.iter_unified(unread=True):  # follows nextCursor across mailboxes
    ...
```

### Formatted mail: pass `markdown`

`mail.send`, `mail.reply`, `mail.forward` and `scheduled_sends.schedule` take the body as `html`, `text` or `markdown`. `mail.save_draft` takes `body` or `markdown`, and `approvals.edit` and `approvals.revise` take `html` or `markdown`. With `markdown`, the server renders headings, lists, bold and italic, links, tables, code and quotes as email HTML, keeps a single line break as a line break, and sends a matching plain text part without the Markdown marks unless you also pass `text`. `html` and `markdown` can't be combined.

```python
cm.mail.send(
    "support@example.com",
    to="customer@example.org",
    subject="Your order",
    markdown="Hi Ana,\n\n- **Shipped:** 2 items\n- **Arriving:** Friday\n\nThanks,\nSupport",
)
```

## Agent flow: send, held for approval, revise, wait

```python
from cloudmail import Cloudmail, is_pending_approval

agent = Cloudmail("https://mail.example.com", token=AGENT_TOKEN)
mailbox = "agent-7@example.com"

sent = agent.mail.send(mailbox, to="lead@example.org", subject="Quote", html="<p>EUR 1,200</p>")
if is_pending_approval(sent):
    # Held for a person. Change it in place instead of sending again.
    revised = agent.approvals.revise(mailbox, sent.approval_id, html="<p>EUR 1,150, valid 30 days</p>")
    print("revision", revised.revision, revised.revised_by)  # 2 requester

    decided = agent.approvals.wait_for_decision(mailbox, sent.approval_id, interval=10, timeout=600)
    print(decided.status)  # sent, rejected, failed, sent_unconfirmed, or still pending after the timeout
```

The reviewer approves the revision they read. A newer one raises `ApprovalChangedError`, and nothing is sent:

```python
from cloudmail import ApprovalChangedError

held = reviewer.approvals.get(mailbox, approval_id)
try:
    reviewer.approvals.approve(mailbox, approval_id, revision=held.revision)
except ApprovalChangedError as err:
    print("changed; review revision", err.approval.revision)
```

## Resources

`mail`, `mailboxes`, `agent_inboxes`, `approvals`, `webhooks` and `events` return pydantic models, as in 0.1. The other resources return the decoded JSON (dicts and lists), so a field the server adds is never lost:

`threads`, `folders`, `labels`, `signatures`, `snooze`, `followups`, `triage`, `screener`, `scheduled_sends`, `senders`, `rules`, `imports`, `delegates`, `audit`, `templates`, `sequences`, `suppressions`, `sending_health`, `domains`, `products`, `people`, `analytics`, `usage`, `ai`, `assistant`, `cloudflare`, `licence`, `privacy`, `access`, `branding`, `preferences`, `notifications`, `meta`, `migration`.

Each method's docstring names the OpenAPI operation it calls. Downloads (`mail.attachment`, `mailboxes.export`, `privacy.download_export`, `branding.logo`) return bytes, or stream into a binary file passed as `dest=`. `tests/test_coverage.py` fails if an operation in `sdk/typescript/openapi.json` has no method and no listed reason.

### Not in the SDK

These operations refuse API tokens, so they have no methods:

- Cloudflare connect, verify, disconnect, apply and revert; account deletion; starting an account export. These need a browser session that re-confirmed its password or passkey in the last 15 minutes.
- Licence activate and deactivate. These need a browser session.
- Web Push subscriptions, push preferences and test pushes. These belong to a browser device.
- Creating, changing or deleting AI providers, model lists and routing. These need a person in the app.
- The WebSocket event stream. Use `events.iter_sse` instead.

For any other route, use `cm.request(method, path, params=..., json=...)`.

### Retries and idempotency

- Sends, creates and `approvals.approve` carry an `Idempotency-Key`: a fresh UUID, or the one you pass as `idempotency_key=`.
- GETs and keyed requests are retried up to `max_retries` times (default 2, exponential backoff with jitter), always with the same key, after:
  - network errors
  - 429 and `409 idempotency_request_in_progress` (honouring `Retry-After`)
  - 408 and 5xx, except on sends
- Sends (`SEND_POST_PATHS`: send, reply, forward, scheduled sends, send-now, template sends, sequence enrollment, approve) are not retried on a 5xx or 408, because the message may already have gone out and the server doesn't store a 5xx against the key. A 503 the server returns before running anything (`idempotency_unavailable`, `licence_unavailable`) is still retried.
- Other writes are not retried.

### Errors

Non-2xx responses raise `CloudmailError` with `status`, `code`, `message`, `body` and `headers`:

| Class | When |
|---|---|
| `ValidationError` | 400, 422 |
| `AuthenticationError` | 401 |
| `PermissionDeniedError` | 403 (`code` says why, e.g. `insufficient_scope`, `self_approval`) |
| `NotFoundError` | 404 |
| `ConflictError` | 409 |
| `ApprovalChangedError` | 409 from `approve` when the held send changed; `approval` is the current version |
| `RateLimitError` | 429; `retry_after` is the server's hint in seconds, or None |
| `ServerError` | 5xx |
| `APIConnectionError` | network failure after retries |

## Verifying webhooks

Each delivery carries `X-Cloudmail-Timestamp` and `X-Cloudmail-Signature: v1=<hex hmac-sha256 of "{timestamp}.{body}">`. Older deployments don't send these headers; see the [changelog](https://github.com/cloudmail-hq/cloudmail/blob/main/CHANGELOG.md) for the release that added them. Pass the raw body bytes, not re-serialised JSON.

```python
from fastapi import FastAPI, HTTPException, Request
from cloudmail import WebhookVerificationError, verify_webhook

app = FastAPI()

@app.post("/hooks/mail")
async def mail_hook(request: Request):
    try:
        event = verify_webhook(await request.body(), request.headers, "whsec_...")
    except WebhookVerificationError:
        raise HTTPException(status_code=400)
    return {"ok": True}
```

The default tolerance is 300 seconds (`tolerance=` changes it).

## Event stream

```python
from cloudmail import StreamRevoked

try:
    for ev in cm.events.iter_sse(mailboxes=["support@example.com"], events=["message.received"], since=last_id):
        handle(ev.event)
        last_id = ev.id
except StreamRevoked:
    ...  # the token was revoked or expired
```

It reconnects with `Last-Event-ID` after a dropped connection and resumes from the last id it yielded. See [docs/realtime.md](https://github.com/cloudmail-hq/cloudmail/blob/main/docs/realtime.md) for the frames.

<p align="center">
  <a href="https://trycloudmail.com/features/agent-inboxes"><img src="https://raw.githubusercontent.com/cloudmail-hq/cloudmail/main/docs/images/shot-approvals.webp" alt="A send from an AI agent waiting for a person's approval in cloudmail" width="720"></a>
</p>

## More ways in

- **MCP server.** Every deployment serves one at `https://<your-host>/mcp` for Claude, Cursor, Codex and other MCP clients: [trycloudmail.com/features/email-mcp-server](https://trycloudmail.com/features/email-mcp-server).
- **Agent Skill.** Instructions that teach a coding agent to use your mailbox: [github.com/cloudmail-hq/skills](https://github.com/cloudmail-hq/skills).
- **CLI.** The `cloudmail` command for macOS, Linux and Windows: [releases](https://github.com/cloudmail-hq/cloudmail/releases).
- **REST API and webhooks.** [trycloudmail.com/features/email-api](https://trycloudmail.com/features/email-api).

## Licence

Fair source, under the Fair Core License (FCL-1.0-ALv2). The text is in the `LICENSE` file of this package. The source is in [cloudmail-hq/cloudmail](https://github.com/cloudmail-hq/cloudmail), and issues go to its [issue tracker](https://github.com/cloudmail-hq/cloudmail/issues).

## Development

From `sdk/python` in a checkout of [cloudmail-hq/cloudmail](https://github.com/cloudmail-hq/cloudmail):

```bash
uv venv && uv pip install -e '.[dev]'
uv run pytest
```

The version is in `pyproject.toml` and in `src/cloudmail/_version.py`; keep them the same.
