# Use the Python SDK

Read, page through and send mail from Python scripts and async applications.

Source: https://cherami.to/docs/python



Use `Cherami` for synchronous scripts and `AsyncCherami` for async applications. Both provide the same typed HTTP operations, pagination and file helpers.

[Python SDK on GitHub](https://github.com/cherami-mail/cherami-python) includes the source, runnable examples, and issue tracker.

## Install and connect [#install-and-connect]

The SDK requires Python 3.11 or later. Install `cherami` from PyPI:

```bash
pip install cherami
```

Or add it to a uv project:

```bash
uv add cherami
```

Create a key in [Account → API keys](https://cherami.to/account/api-keys) and supply it privately as `CHERAMI_API_KEY`; we show it only once. It works for every inbox on your account. An agent working for you can get its own instead: choose **Get the message** under **Connect an agent** on your [Account home](https://cherami.to/account) and paste the message to your agent, which exchanges it for a key over HTTP ([how](https://cherami.to/docs/quickstart#ask-your-human-for-approval)).

```python
import os
from cherami import Cherami

with Cherami(os.environ["CHERAMI_API_KEY"]) as client:
    for inbox in client.list_inboxes().data["inboxes"]:
        print(inbox["id"], inbox["address"])
```

The examples below continue from this script and read the inbox ID from `CHERAMI_INBOX_ID`; set it to one of the IDs printed above.

Methods return an envelope with `.data`, `.status`, `.headers` and `.request_id`. Inputs and data are dictionaries using HTTP field names: IDs and query fields at the top level, JSON input in `body`. Omit optional fields unless you mean to send them; `None` is explicit JSON null where allowed. Timestamps stay strings. Named types live in `cherami.models`, including each operation's parameter and result types.

## Read and paginate [#read-and-paginate]

```python
with Cherami(os.environ["CHERAMI_API_KEY"]) as client:
    for message in client.iterate("list_messages", {
        "inbox_id": os.environ["CHERAMI_INBOX_ID"],
        "labels_none": ["handled"], "limit": 50,
    }, max_pages=5):
        detail = client.get_message({"message_id": message["id"]}).data
        if detail["processing_status"] == "ready":
            content = detail["content"]
            text = content["reply_text"] if content["reply_text"] is not None else content["text"]
            # Process text; inspect originals for inline answers or forwards.
```

Only `ready` messages have `content` ([what to do with the others](https://cherami.to/docs/guides/receiving#wait-for-content-not-just-receipt)). `reply_text` holds a reply's new text, or `None` when none could be extracted; an empty string is a real result.

`iterate` yields items; `pages` yields whole responses, including `data["next_cursor"]` to resume later. Pass `max_pages` to stop early; omit it to follow every page. Both also work for `list_sent_messages`, `list_drafts`, `list_labels`, `list_threads`, `get_thread` and `list_trash`.

Conversation pages from `get_thread` come newest first, but each page lists its messages oldest to newest; sort by `timestamp` after collecting several pages. See [search](https://cherami.to/docs/guides/search) and [conversations](https://cherami.to/docs/guides/conversations).

## Use async I/O [#use-async-io]

```python
import asyncio
import os
from cherami import AsyncCherami

async def main():
    async with AsyncCherami(os.environ["CHERAMI_API_KEY"]) as client:
        async for message in client.iterate("list_messages", {
            "inbox_id": os.environ["CHERAMI_INBOX_ID"], "limit": 20,
        }, max_pages=1):
            detail = (await client.get_message({"message_id": message["id"]})).data
            print(detail["id"], detail["processing_status"])

asyncio.run(main())
```

Use a context manager, or call `close()` / `await aclose()` on a long-lived client.

## Save an intended send before submitting [#save-an-intended-send-before-submitting]

Prepare the send once and save the record, then submit it. If a response is lost, submit the same record again; it won't send twice.

Set `intent_path` to where you'll save this send's record, replace the example recipient and prepare once:

```python
from pathlib import Path
from cherami import prepare_send

intent_path = Path("review-ready-send.json")
intent = prepare_send("send_message", {
    "inbox_id": os.environ["CHERAMI_INBOX_ID"],
    "body": {
        "to": [{"address": "recipient@example.com", "name": "Alex"}],
        "subject": "Review ready",
        "text": "The change is ready for review.",
    },
})
intent_path.write_text(intent.to_json(), encoding="utf-8")
```

To submit, load the saved record:

```python
from cherami import restore_send

saved = restore_send(intent_path.read_text(encoding="utf-8"))
with Cherami(os.environ["CHERAMI_API_KEY"]) as client:
    result = client.submit(saved)
    print(result.data["message"]["id"], result.data["message"]["status"], result.data["outcome_persisted"])
```

`submit` makes one request and doesn't retry. `rejected` and `unknown` come back as outcomes, not exceptions; the [sending guide](https://cherami.to/docs/guides/sending#inspect-the-outcome) covers what each means. If `outcome_persisted` is false, keep this receipt: later reads may not show its outcome.

`submit` accepts a record for 23 hours and 59 minutes after you prepare it, then raises `SendRecoveryExpiredError`; if the email isn't in `list_sent_messages`, prepare it again.

`prepare_send` also covers `reply_message`, `reply_all_message` and `forward_message`, with their own body fields. Calling `client.send_message` or those methods directly sends without a saved record or a generated key; if you do, supply and keep your own `idempotency_key`.

Drafts have no such window: `client.send_draft({"draft_id": draft_id, "body": {}})` can be repeated safely. See [draft workflows](https://cherami.to/docs/guides/drafts).

## Handle files and failures [#handle-files-and-failures]

[Python attachment examples](https://cherami.to/docs/guides/attachments#download-with-python) cover downloads and uploads. Download methods return an unconsumed `httpx.Response` in `.data`; close it after reading, including on failure. Use `read()` / `iter_bytes()` with sync clients and `await aread()` / `aiter_bytes()` with async ones.

```python
from cherami import CheramiApiError

with Cherami(os.environ["CHERAMI_API_KEY"]) as client:
    try:
        client.get_outbound_quota()
    except CheramiApiError as error:
        print(error.status, error.code, error.request_id)
        raise
```

`CheramiApiError` keeps the HTTP status, headers, parsed `body` with any refusal details, `code`, `request_id` and `retry_after`. Network failures and unusable responses raise `CheramiTransportError`.

The default timeout is 60 seconds of HTTPX inactivity per connect, read, write or pool operation, not a total request deadline. A client or method accepts a positive `timeout` in seconds, or `None` to disable it. Clients never follow redirects or retry, and they ignore proxy environment variables; to use a proxy, pass an HTTPX `transport` configured for it, which must not retry either.

See the [HTTP reference](https://cherami.to/docs/api) for every parameter and response.
