Python SDK

Send email from Python with the exx-sh package, sync or async. Install, configure, send, handle errors and retries, SMTP and webhooks.

exx-sh is the official Python client for the exx.sh API, imported as exx. It needs Python 3.11+ and has a sync client (Exx) and an async one (AsyncExx), both on httpx. MIT licensed.

Install

pip install exx-sh

Send an email

from exx import Exx, ExxError

exx = Exx()  # reads EXX_API_KEY

try:
    sent = exx.emails.send(
        {
            "from": "Acme <hello@acme.com>",
            "to": ["delivered@example.com"],
            "subject": "Your sign-in link",
            "html": "<p>Click the link to sign in.</p>",
            "text": "Click the link to sign in.",
            "tags": [{"name": "category", "value": "sign_in"}],
        }
    )
except ExxError as e:
    # e.name is the API's error name, e.g. "validation_error" or "rate_limit_exceeded".
    raise SystemExit(f"{e.name}: {e.message}") from e
print(sent.id)

emails.send and batch.send also take idempotency_key= and stream= ("transactional" or "distributional"). The sending guide explains every field.

Configure the client

Exx(api_key=None, *, base_url=None, retries=2, timeout=30.0) reads the key from EXX_API_KEY and the base URL from EXX_BASE_URL when you pass none. timeout applies to each phase of an attempt (connect, read, write), as httpx does.

AsyncExx takes the same arguments and has the same methods as coroutines:

import asyncio

from exx import AsyncExx


async def main() -> None:
    async with AsyncExx() as exx:
        sent = await exx.emails.send(
            {
                "from": "Acme <hello@acme.com>",
                "to": ["delivered@example.com"],
                "subject": "Hello",
                "text": "It works.",
            }
        )
        print(sent.id)


asyncio.run(main())

Handle errors

An API error raises exx.ExxError with name (for a server error too), message and status_code; branch on name as the errors guide describes. An answer that did not come from the API (a proxy's error page) is application_error with its status; no answer at all is application_error with status_code None.

Retries

The client retries rate-limited requests, except a spent daily or monthly quota. It retries server errors and lost answers only when sending again cannot act twice: any request but a POST without an Idempotency-Key. While retries are on, each send gets a key made for you. A send the server is still processing (409 concurrent_idempotent_requests) is asked again until it has the answer. retries sets how many retries follow the first attempt.

Resources

ResourceMethods
emailssend, get, list, update, cancel, attempts and transcript (exx only)
emails.attachmentslist and get the attachments of a sent email
emails.receivinglist and get received mail; emails.receiving.attachments: list and get its attachments (receiving email)
emails.verifyan address's syntax, DNS and list findings (exx only, verify addresses)
eventssend (Resend's shape), create and list_names (exx only) (application events)
workflowscreate, get, list, update, remove, publish, pause, resume, duplicate, rotate_signing_secret and schema (exx only, workflows)
workflows.versionslist and get a workflow's published versions
workflows.runsstart (takes idempotency_key=), list, get, cancel and cancel_all
batchsend
domainscreate, get, list, update, delete and verify domains; update takes dmarc_reports=, dmarc_summary, dmarc_reports (exx only)
api_keyscreate, list and revoke keys
webhookscreate, get, list, update, delete webhooks and rotate their secret; create and update take domains= (exx only)
webhooks.deliverieslist, get and replay a webhook's deliveries (exx only)
templatescreate, get, list, update, publish, duplicate, remove; check (exx only)
suppressionslist, add and remove suppressed addresses
metricsget (the series), providers, reputation (exx only)

SMTP

ExxSmtp sends the same email shape over SMTP with the standard library's smtplib.

from exx import ExxError, ExxSmtp

smtp = ExxSmtp()  # reads EXX_API_KEY; smtp.exx.sh, port 465 (TLS)

try:
    sent = smtp.send(
        {
            "from": "Acme <hello@acme.com>",
            "to": ["delivered@example.com"],
            "subject": "Your sign-in link",
            "html": "<p>Click the link to sign in.</p>",
            "text": "Click the link to sign in.",
        },
        idempotency_key="sign-in/123",
    )
except ExxError as e:
    # "smtp_error" (e.smtp_code) for a refusal, "validation_error" for what SMTP cannot
    # carry (tags, scheduling, attachment paths).
    raise SystemExit(f"{e.name}: {e.message}") from e
print(sent.id)  # the same id the API and webhooks use

ExxSmtp(api_key=None, *, host=None, port=None, timeout=30.0, ssl_context=None, implicit_tls=None) connects to EXX_SMTP_HOST and EXX_SMTP_PORT by default, then smtp.exx.sh and 465. Port 465 is TLS from the start and any other port uses STARTTLS; TLS is always required. A refusal raises exx.SmtpError (name smtp_error, with smtp_code). Tags, scheduling and attachment paths need the API.

Webhooks

Verify each webhook delivery against the raw body before you use it (webhooks guide):

import os

from exx import Exx, WebhookVerificationError

exx = Exx()


def handle(body: bytes, headers: dict[str, str]) -> int:
    """Your framework's handler: the raw body and the request headers. Returns the status."""
    try:
        event = exx.webhooks.verify(body, headers, os.environ["EXX_WEBHOOK_SECRET"])
    except WebhookVerificationError:
        return 400
    print(event["type"], event["data"])
    return 204

On this page