SPB Git

Repository Public

README.md 7.3 KB

# spmail — Python SDK for the SP Mail API

Synchronous client of the SP Mail REST API (https://mail.spboucher.ai/api/v1, contract in docs/API.md and docs/OPENAPI.yaml).

  • Python ≥ 3.10, standard library only (urllib, hmac, json): nothing to install besides the package.
  • Results are plain dictionaries typed with TypedDicts generated from the OpenAPI document (spmail.types).
  • Typed errors, automatic Idempotency-Key, safe retries, generators for pagination, wait_for_delivery, webhook signature verification.
  • No async client: wrap calls with asyncio.to_thread(...) when needed.

# Install

The package lives in this repository (it is not published to an index).

bash
uv pip install ./packages/sdk-python        # or: pip install ./packages/sdk-python
# without installing: PYTHONPATH=packages/sdk-python/src python3 your_script.py

# Quickstart

python
import os
from spmail import SPMail

mail = SPMail(api_key=os.environ["SPMAIL_API_KEY"])     # spm_xxxxxxxxxx_… ; SPMail() reads SPMAIL_API_KEY / SPMAIL_BASE_URL

sent = mail.messages.send(
    from_="notifications@example.org",                  # `from_` stands for the field `from`
    to=["owner@example.org", {"email": "ops@example.org", "name": "Ops"}],
    subject="Disk at 91 %",
    text="The /data volume is at 91 %.",
)
if sent["status"] == "pending_approval":
    ...  # external recipient + key policy "approval": NOTHING was sent; an administrator must approve in SP Mail
else:
    final = mail.wait_for_delivery(sent["id"], timeout=60)   # delivered | bounced | failed | cancelled
    print(final["status"], final["recipients"])

for m in mail.messages.iterate(folder="inbox", unread=True):
    print(m["received_at"], m["from"][0]["email"], m["subject"])

Bodies can be given as keyword arguments, as a dictionary, or both: mail.messages.send({"from": a, "to": [b], "text": "x"}).

# Options

python
SPMail(api_key, base_url="https://mail.spboucher.ai", timeout=30.0, max_retries=2, max_retry_delay=60.0,
       allow_insecure_http=False, default_headers=None, transport=None)

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.

# Resources

Resource Methods
mail.me(), mail.health() identity, scopes, usable addresses, limits · public health probe
mail.messages send, send_batch, list, iterate, get, changes, reply, forward, update, mark_read, mark_unread, move, archive, delete, wait_for_delivery
mail.messages.outbound list, iterate, get
mail.messages.scheduled list, iterate, cancel
mail.messages.attachments list(message_id), download(message_id, attachment_id) → .data (bytes), .filename, .size
mail.threads list, iterate, get
mail.drafts create, list, iterate, get, update (returns a new id), delete, send
mail.folders list, create
mail.files upload(data, filename=, content_type=, address=) — data is bytes, text, or a pathlib.Path
mail.addresses list, get, create, update, delete, get_automation, update_automation
mail.aliases list, create, update, delete
mail.webhooks create, list, get, update, delete, test, replay, deliveries.list/iterate/replay, verify_signature, construct_event, sign
mail.events list, iterate
mail.templates list, get, render
mail.request(method, path, query=, body=) escape hatch
python
from pathlib import Path

f = mail.files.upload(Path("report.pdf"), content_type="application/pdf")
mail.messages.send(from_=sender, to=[rcpt], subject="Report", text="Attached.", attachments=[{"file_id": f["id"]}])

page = mail.messages.list(folder="inbox", from_="billing", has_attachment=True, limit=20)
message = mail.messages.get(page["data"][0]["id"])            # text, sanitised html, attachments, auth
mail.messages.reply(message["id"], text="Received, thank you.")
mail.messages.mark_read(message["id"])
mail.messages.archive(message["id"])

# send by template
tpl = mail.templates.list()[0]
mail.templates.render(tpl["id"], {"first_name": "Zoé", "code": "424242"})      # nothing is sent
mail.messages.send(from_=sender, to=[rcpt], template_id=tpl["id"], variables={"first_name": "Zoé", "code": "424242"})

# Idempotency and retries

Same rules as the TypeScript SDK:

  • 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;
  • 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);
  • never retried: 429 daily_send_limit_exceeded, files.upload, drafts.update, other 4xx.

# Errors

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

python
import spmail

try:
    mail.messages.send(from_=sender, to=[rcpt], subject="x", text="x")
except spmail.PermissionDeniedError as e:
    if e.code == "from_not_allowed": ...
except spmail.RateLimitError as e:
    print(e.retry_after)
except spmail.SPMailError as e:
    print(e.status, e.code, e.message, e.request_id)

# Webhooks

Verify over the raw body, before any JSON parsing; deduplicate on the event id.

python
import os, spmail
from flask import Flask, request

app = Flask(__name__)

@app.post("/hooks/spmail")
def hook():
    try:
        event = spmail.construct_event(request.get_data(), request.headers.get("SPMail-Signature"), os.environ["SPMAIL_WEBHOOK_SECRET"])
    except spmail.SignatureVerificationError:
        return "", 400
    if event["type"] == "message.received":
        enqueue(event["id"], event["data"])      # answer fast, work asynchronously
    return "", 204

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.

# Generated types

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.

# Tests

bash
cd packages/sdk-python && python3 -m unittest discover -s tests        # unit tests (scripted transport); live tests skipped

Live tests against a real test server (they need mailboxes and keys, created and purged by the driver) — from the repository root:

bash
SPMAIL_TEST_PORT=8801 SPMAIL_TEST_DB=postgres://127.0.0.1/sp_mail_sdk_test \
  node --import tsx --test --test-concurrency=1 tests/integration/sdk-python.test.ts
Files main
Menu

Theme