Repository Public
1# spmail — Python SDK for the SP Mail API23Synchronous client of the SP Mail REST API (`https://mail.spboucher.ai/api/v1`, contract in [`docs/API.md`](../../docs/API.md) and [`docs/OPENAPI.yaml`](../../docs/OPENAPI.yaml)).45- Python ≥ 3.10, **standard library only** (`urllib`, `hmac`, `json`): nothing to install besides the package.6- Results are plain dictionaries typed with `TypedDict`s generated from the OpenAPI document (`spmail.types`).7- Typed errors, automatic `Idempotency-Key`, safe retries, generators for pagination, `wait_for_delivery`, webhook signature verification.8- No async client: wrap calls with `asyncio.to_thread(...)` when needed.910## Install1112The package lives in this repository (it is not published to an index).1314```bash15uv pip install ./packages/sdk-python # or: pip install ./packages/sdk-python16# without installing: PYTHONPATH=packages/sdk-python/src python3 your_script.py17```1819## Quickstart2021```python22import os23from spmail import SPMail2425mail = SPMail(api_key=os.environ["SPMAIL_API_KEY"]) # spm_xxxxxxxxxx_… ; SPMail() reads SPMAIL_API_KEY / SPMAIL_BASE_URL2627sent = mail.messages.send(28 from_="notifications@example.org", # `from_` stands for the field `from`29 to=["owner@example.org", {"email": "ops@example.org", "name": "Ops"}],30 subject="Disk at 91 %",31 text="The /data volume is at 91 %.",32)33if sent["status"] == "pending_approval":34 ... # external recipient + key policy "approval": NOTHING was sent; an administrator must approve in SP Mail35else:36 final = mail.wait_for_delivery(sent["id"], timeout=60) # delivered | bounced | failed | cancelled37 print(final["status"], final["recipients"])3839for m in mail.messages.iterate(folder="inbox", unread=True):40 print(m["received_at"], m["from"][0]["email"], m["subject"])41```4243Bodies can be given as keyword arguments, as a dictionary, or both: `mail.messages.send({"from": a, "to": [b], "text": "x"})`.4445### Options4647```python48SPMail(api_key, base_url="https://mail.spboucher.ai", timeout=30.0, max_retries=2, max_retry_delay=60.0,49 allow_insecure_http=False, default_headers=None, transport=None)50```5152`base_url` gets `/api/v1` appended when missing; plain `http://` is refused except on localhost. The key never appears in `repr()` of the client or in any error. The SDK logs nothing.5354## Resources5556| Resource | Methods |57|---|---|58| `mail.me()`, `mail.health()` | identity, scopes, usable addresses, limits · public health probe |59| `mail.messages` | `send`, `send_batch`, `list`, `iterate`, `get`, `changes`, `reply`, `forward`, `update`, `mark_read`, `mark_unread`, `move`, `archive`, `delete`, `wait_for_delivery` |60| `mail.messages.outbound` | `list`, `iterate`, `get` |61| `mail.messages.scheduled` | `list`, `iterate`, `cancel` |62| `mail.messages.attachments` | `list(message_id)`, `download(message_id, attachment_id)` → `.data` (bytes), `.filename`, `.size` |63| `mail.threads` | `list`, `iterate`, `get` |64| `mail.drafts` | `create`, `list`, `iterate`, `get`, `update` (returns a **new id**), `delete`, `send` |65| `mail.folders` | `list`, `create` |66| `mail.files` | `upload(data, filename=, content_type=, address=)` — `data` is bytes, text, or a `pathlib.Path` |67| `mail.addresses` | `list`, `get`, `create`, `update`, `delete`, `get_automation`, `update_automation` |68| `mail.aliases` | `list`, `create`, `update`, `delete` |69| `mail.webhooks` | `create`, `list`, `get`, `update`, `delete`, `test`, `replay`, `deliveries.list/iterate/replay`, `verify_signature`, `construct_event`, `sign` |70| `mail.events` | `list`, `iterate` |71| `mail.templates` | `list`, `get`, `render` |72| `mail.request(method, path, query=, body=)` | escape hatch |7374```python75from pathlib import Path7677f = mail.files.upload(Path("report.pdf"), content_type="application/pdf")78mail.messages.send(from_=sender, to=[rcpt], subject="Report", text="Attached.", attachments=[{"file_id": f["id"]}])7980page = mail.messages.list(folder="inbox", from_="billing", has_attachment=True, limit=20)81message = mail.messages.get(page["data"][0]["id"]) # text, sanitised html, attachments, auth82mail.messages.reply(message["id"], text="Received, thank you.")83mail.messages.mark_read(message["id"])84mail.messages.archive(message["id"])8586# send by template87tpl = mail.templates.list()[0]88mail.templates.render(tpl["id"], {"first_name": "Zoé", "code": "424242"}) # nothing is sent89mail.messages.send(from_=sender, to=[rcpt], template_id=tpl["id"], variables={"first_name": "Zoé", "code": "424242"})90```9192## Idempotency and retries9394Same rules as the TypeScript SDK:9596- creating POSTs carry an `Idempotency-Key`, generated per call and reused for every retry of that call; pass `idempotency_key="order-42"` to make a retry of your own process idempotent too;97- network errors, timeouts, `502`/`503`/`504` and `409 idempotency_in_progress` are retried with exponential backoff and jitter **only** for idempotent requests or requests carrying an idempotency key; `429 rate_limited` is retried for any request, honouring `Retry-After` (up to `max_retry_delay`);98- never retried: `429 daily_send_limit_exceeded`, `files.upload`, `drafts.update`, other 4xx.99100## Errors101102Every failure raises `spmail.SPMailError` with `status`, `code`, `message`, `details`, `request_id`, `retry_after`. Subclasses: `BadRequestError` (400), `AuthenticationError` (401), `PermissionDeniedError` (403), `NotFoundError` (404), `ConflictError` (409), `UnprocessableEntityError` (422, reserved), `RateLimitError` (429), `ServerError` (5xx), `ConnectionError` / `TimeoutError` (no answer; `wait_for_delivery` timeout with `details["last"]`), `SignatureVerificationError`.103104```python105import spmail106107try:108 mail.messages.send(from_=sender, to=[rcpt], subject="x", text="x")109except spmail.PermissionDeniedError as e:110 if e.code == "from_not_allowed": ...111except spmail.RateLimitError as e:112 print(e.retry_after)113except spmail.SPMailError as e:114 print(e.status, e.code, e.message, e.request_id)115```116117## Webhooks118119Verify over the **raw body**, before any JSON parsing; deduplicate on the event id.120121```python122import os, spmail123from flask import Flask, request124125app = Flask(__name__)126127@app.post("/hooks/spmail")128def hook():129 try:130 event = spmail.construct_event(request.get_data(), request.headers.get("SPMail-Signature"), os.environ["SPMAIL_WEBHOOK_SECRET"])131 except spmail.SignatureVerificationError:132 return "", 400133 if event["type"] == "message.received":134 enqueue(event["id"], event["data"]) # answer fast, work asynchronously135 return "", 204136```137138`spmail.verify_webhook_signature(payload, header, secret, tolerance=300)` returns a boolean; `spmail.sign_webhook_payload(payload, secret)` builds a valid header for tests of your receiver.139140## Generated types141142`python3 scripts/generate_types.py` rewrites `src/spmail/_generated.py` from `docs/OPENAPI.yaml` (a small parser for the YAML dialect written by the server; standard library only). `--check` fails when the file is stale; the unit tests run it.143144## Tests145146```bash147cd packages/sdk-python && python3 -m unittest discover -s tests # unit tests (scripted transport); live tests skipped148```149150Live tests against a real test server (they need mailboxes and keys, created and purged by the driver) — from the repository root:151152```bash153SPMAIL_TEST_PORT=8801 SPMAIL_TEST_DB=postgres://127.0.0.1/sp_mail_sdk_test \154 node --import tsx --test --test-concurrency=1 tests/integration/sdk-python.test.ts155```156