Skip to main content

cloudmail

cloudmail

The Python SDK for cloudmail: send and read email, run AI agent inboxes with human approval, verify webhooks and follow realtime events.

cloudmail 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 · Live demo · API docs · For AI agents · Pricing · GitHub · Agent Skill

Install

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 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, or look around the live demo first. The SDK guide has more examples.

Usage

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. On mail.forward the body is your note and is optional: the server sends the original under it, and include_original=False sends only what you pass (cloudmail 1.4.0 or later; earlier deployments send only your body). 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.

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

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:

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 for the release that added them. Pass the raw body bytes, not re-serialised JSON.

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

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 for the frames.

A send from an AI agent waiting for a person's approval in cloudmail

More ways in

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, and issues go to its issue tracker.

Development

From sdk/python in a checkout of cloudmail-hq/cloudmail:

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

Release

The version is in pyproject.toml and in src/cloudmail/_version.py; the release workflow refuses to publish when they differ. Change both and merge: .github/workflows/release-sdks.yml in cloudmail-hq/cloudmail publishes any version PyPI does not have yet, through PyPI trusted publishing, with attestations.

Metadata

Release files for cloudmail 1.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cloudmail 1.1.0
File Size Uploaded Provenance Actions
cloudmail-1.1.0.tar.gz 37.2 kB With provenance Details for cloudmail-1.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cloudmail 1.1.0
File Interpreter ABI Platform Actions
cloudmail-1.1.0-py3-none-any.whl Python 3 none any Details for cloudmail-1.1.0-py3-none-any.whl

Total release size: 70.6 kB

Release files / cloudmail-1.1.0.tar.gz

Download URL cloudmail-1.1.0.tar.gz
Size 37.2 kB
Tags Source
SHA-256 checksum
How to use checksums
d4adac3651ed81abbda29cd62b03f309847677592fdfe064bd2b9b7a3ebc9ea8
BLAKE2b-256 checksum
How to use checksums
49f515a450861b3da4ccf57a81390bab5cdfaa9ed420170104a2373fc5fb6c58
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Release files / cloudmail-1.1.0-py3-none-any.whl

Download URL cloudmail-1.1.0-py3-none-any.whl
Size 33.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3a94d61fb4b2190525dd78674ef733ecf52ce1cf55c8f6fd9f58a0ce65920a60
BLAKE2b-256 checksum
How to use checksums
ba5dea7309d4808c62af5427a18b45e67061936ed4c04470b850421c7fc4ee7f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Security for cloudmail 1.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for cloudmail-1.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page