Metadata-Version: 2.4
Name: capimail
Version: 0.1.1
Summary: Official Python client for the CapiMail API: transactional email, suppressions, credits, Email Validation, OTP, Domain Health and webhook verification.
Project-URL: Homepage, https://capimail.com
Project-URL: Documentation, https://capimail.com/docs
Project-URL: Repository, https://github.com/lelianto/capimail
Project-URL: Changelog, https://github.com/lelianto/capimail/blob/main/sdk-python/CHANGELOG.md
Author: CapiMail
License-Expression: MIT
Keywords: capimail,email,email-validation,indonesia,otp,transactional-email,webhooks
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Communications :: Email
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown

# capimail

Official Python client for the **CapiMail** API: transactional email, suppressions, credits, the Email Validation, OTP and Domain Health add-ons, and webhook signature verification. Zero dependencies (standard library `urllib`, `json`, `hmac`), fully type-hinted, Python 3.9+.

> Send the email your product depends on - verification links, OTP codes, password resets, receipts - from your own verified domain.

## What's inside

| Resource | Methods | Scope |
| --- | --- | --- |
| `emails` | `send`, `get` | `email:send` / `email:read` |
| `account` | `credits` | `email:read` |
| `suppressions` | `list`, `get`, `add`, `remove` | `email:read` / `email:send` |
| `validation` | `check`, `jobs.create`, `jobs.get`, `jobs.list`, `jobs.results`, `jobs.iter_results` | `email:send` / `email:read` |
| `otp` | `send`, `verify` | `email:send` |
| `domains` | `check`, `monitors.create`, `monitors.list`, `monitors.delete` | `email:send` / `email:read` |
| `capimail.webhooks` | `verify_signature`, `construct_event` | none (uses your endpoint secret) |

Methods return frozen `dataclasses` with snake_case fields (for example `SendEmailResult.message_id`, `ValidationJob.credits_charged`) and a `request_id` you can quote to support. Webhook events are plain dicts. Full API reference: https://capimail.com/docs (add-ons: https://capimail.com/docs#addons). Release notes: [CHANGELOG.md](./CHANGELOG.md).

## Install

```bash
pip install capimail
```

## Quickstart

```python
import os
from capimail import CapiMail

# Start with a cm_test_ key: it runs the full simulated lifecycle without
# sending, reserving credits, or touching live data. Swap to cm_live_ later.
capimail = CapiMail(os.environ["CAPIMAIL_API_KEY"])

result = capimail.emails.send(
    from_="hello@your-verified-domain.com",
    to="customer@example.com",
    subject="Welcome to Acme",
    html="<h1>Welcome</h1><p>Your account is ready.</p>",
    idempotency_key="welcome-user-123",  # required; makes retries safe
)

print(result.message_id, result.status)  # e.g. "…uuid…" "queued"
```

Keep your key **server-side**. Never ship it in client code or a public repo.

## Sending

`emails.send(...)` takes keyword arguments:

| Argument | Type | Notes |
| --- | --- | --- |
| `from_` | `str` | Verified sender. Bare address or `"Acme <hello@acme.com>"`. (`from` is a Python keyword.) |
| `to` | `str \| list[str]` | 1–50 unique recipients. |
| `idempotency_key` | `str` | **Required.** 8–128 of `A–Z a–z 0–9 . _ : -`. Reuse returns the original message; reuse with a different payload is a 409. |
| `subject` | `str` | Required unless provided by a template. |
| `html` / `text` | `str` | At least one is required (unless templated). |
| `reply_to` | `str` | Optional Reply-To address. |
| `headers` | `dict[str, str]` | Optional allow-listed headers. |
| `tags` | `dict[str, str]` | Optional metadata. |
| `attachments` | `list[Attachment \| dict]` | `filename`, `content_type`, `content` (base64), `content_id?`, `disposition?`. |
| `template` | `{"key", "locale"?, "variables"?}` | Send from a stored template instead of inline content. |

### Template send

```python
capimail.emails.send(
    from_="accounts@your-verified-domain.com",
    to=user.email,
    template={"key": "email-verification", "locale": "id", "variables": {"name": user.name, "verify_url": link}},
    idempotency_key=f"verify-{user.id}",
)
```

### Attachments

```python
from capimail import Attachment

with open("invoice.pdf", "rb") as fh:
    invoice = Attachment.from_bytes("invoice.pdf", fh.read(), "application/pdf")

capimail.emails.send(from_=..., to=..., subject="Invoice", text="Attached.", attachments=[invoice], idempotency_key="invoice-1001")
```

## Checking status

A `202` means the send is durably queued - not delivered. Poll for the real state:

```python
status = capimail.emails.get(result.message_id)
print(status.email.status)  # queued | processing | provider_accepted | delivered | hard_bounced | …
for event in status.email.events:
    print(event.event_type, event.occurred_at)
```

## Credits and suppressions

```python
available = capimail.account.credits().available

capimail.suppressions.get("user@example.com").suppressed   # True / False
capimail.suppressions.add("user@example.com", "unsubscribe")
capimail.suppressions.remove("user@example.com")          # False if it was not suppressed

page = capimail.suppressions.list(limit=100)
while True:
    for s in page.suppressions:
        print(s.email_hash, s.reason)  # the plaintext address is never returned
    if not page.next_cursor:
        break
    page = capimail.suppressions.list(limit=100, cursor=page.next_cursor)
```

## Add-ons

Add-ons are paid from the same credit balance and need a live key (`cm_live_`), except OTP which also works with test keys. Prices: https://capimail.com/docs#addons.

### Email Validation

```python
# Up to 100 addresses, answered immediately. 2 credits per address with a verdict.
check = capimail.validation.check(["budi@perusahaan.co.id"], idempotency_key="signup-123")
check.results[0].verdict  # "valid" | "risky" | "invalid" | "unknown"
check.results[0].reasons  # e.g. ["role_address"]

# Up to 10,000 addresses in the background. Subscribe your webhook to
# validation.completed, or poll jobs.get(job.id).
job = capimail.validation.jobs.create(
    emails,
    suppress_invalid=True,              # invalid addresses join your suppression list
    metadata={"list_id": "march"},      # echoed in the webhook
    idempotency_key="list-march",       # a retry returns the same job
)

# Later: iterate every result across pages (a generator; fetches lazily).
for result in capimail.validation.jobs.iter_results(job.id, verdict="invalid"):
    mark_invalid(result.email)
```

`jobs.results(job_id, verdict=None, after=None, limit=None)` returns one page if you want to drive pagination yourself (`page.next_after`), and `jobs.list(limit=None, before=None)` pages through your jobs.

### OTP

```python
otp = capimail.otp.send("user@example.com", purpose="login")
# store otp.id with the login attempt; never store the code

check = capimail.otp.verify(otp.id, code_typed_by_user)
if not check.valid:
    # check.status: "invalid_code" | "locked" | "expired" | "already_verified" | "not_found"
    ...
```

Sender, template, language, code length, validity and attempts come from **Dashboard > Add-ons > OTP** (per sending domain) and can be overridden per call (`template_key`, `locale`, `code_length`, `ttl_seconds`, `max_attempts`, `domain`, `variables`). Your template receives `{{code}}`, `{{expires_minutes}}` and `{{purpose}}`. With a `cm_test_` key nothing is delivered and the result includes `test_code`.

### Domain Health

```python
health = capimail.domains.check("client.co.id", dkim_selectors=["google"])
health.status   # "pass" | "warn" | "fail"
health.issues   # [DomainIssue(check="dmarc", code="dmarc_policy_none"), ...]
health.checks   # raw {"mx": {...}, "spf": {...}, "dkim": {...}, "dmarc": {...}}

# Daily monitoring; domain.health_changed fires when the status changes.
monitor = capimail.domains.monitors.create("client.co.id")
capimail.domains.monitors.list()
capimail.domains.monitors.delete(monitor.id)  # False if it no longer exists
```

## Webhooks

CapiMail signs every webhook with `X-CapiMail-Signature: t=<unix>,v1=<hex>`. Verify it against the **raw** request body (bytes or str, never a re-serialized dict). `construct_event` raises `capimail.WebhookSignatureError` (a `ValueError`) when the signature is missing, stale (default tolerance 300 s) or wrong; `verify_signature` returns a bool instead.

### FastAPI

```python
import os
from fastapi import FastAPI, Header, HTTPException, Request
from capimail.webhooks import construct_event

app = FastAPI()

@app.post("/webhooks/capimail")
async def capimail_webhook(request: Request, x_capimail_signature: str = Header(None)):
    payload = await request.body()
    try:
        event = construct_event(
            payload,
            x_capimail_signature,
            os.environ["CAPIMAIL_WEBHOOK_SECRET"],  # or [current, previous] while rotating
        )
    except ValueError:
        raise HTTPException(status_code=400, detail="invalid signature")

    if event["type"] == "email.bounced":
        ...  # event["data"]["message_id"]
    elif event["type"] == "validation.completed":
        ...  # event["data"]["job_id"], ["summary"], ["metadata"]
    elif event["type"] == "domain.health_changed":
        ...  # event["data"]["domain"], ["status"], ["issues"]
    return {"ok": True}  # any 2xx; dedupe on the X-CapiMail-Event-Id header
```

### Flask

```python
import os
from flask import Flask, abort, request
from capimail.webhooks import construct_event

app = Flask(__name__)

@app.post("/webhooks/capimail")
def capimail_webhook():
    try:
        event = construct_event(
            request.get_data(),  # raw bytes
            request.headers.get("X-CapiMail-Signature"),
            [os.environ["CAPIMAIL_WEBHOOK_SECRET"], os.environ.get("CAPIMAIL_WEBHOOK_SECRET_PREVIOUS", "")],
        )
    except ValueError:
        abort(400)
    handle(event)
    return "", 204
```

`secret` may be a `str`, `bytes`, or a list of them (current and previous while rotating); any other type raises `TypeError`. A malformed `X-CapiMail-Signature` header never raises from `verify_signature`; it returns `False` (and `construct_event` raises `WebhookSignatureError`, a `ValueError`). The replay window is `tolerance=300` seconds; a non-positive or non-finite value falls back to 300.

## Errors

Non-2xx responses raise `CapiMailError` with a stable `code`:

```python
from capimail import CapiMailConnectionError, CapiMailError

try:
    capimail.emails.send(...)
except CapiMailError as err:
    print(err.status, err.code, err.message, err.request_id)  # 402 "insufficient_credits" …
    # err.details: field-level problems for 422 validation_error.
    # Add-on codes include live_key_required, otp_rate_limited, domain_required,
    # invalid_domain and monitor_limit_reached; see https://capimail.com/docs#addons-errors
    if err.is_retryable:
        # 429 / 503 - back off and retry with the same idempotency key;
        # err.retry_after_seconds is set when the response carried Retry-After.
        ...
except CapiMailConnectionError as err:
    # Network failure or timeout (err.cause holds the underlying exception).
    ...
```

## Test mode

A `cm_test_` key simulates the full lifecycle (real `message_id`, signed webhooks) without sending. The simulated outcome is driven by the first recipient's local-part:

| Recipient | Simulated outcome |
| --- | --- |
| `bounce@…` | hard bounce |
| `complaint@…` | complaint |
| `fail@…` | failure |
| anything else | delivered |

```python
capimail = CapiMail("cm_test_…")
capimail.is_test_mode  # True
r = capimail.emails.send(from_="x@acme.com", to="bounce@example.com", subject="t", text="t", idempotency_key="test-bounce-1")
r.test     # True
r.outcome  # the simulated bounce outcome
```

## Options

```python
CapiMail(
    api_key,
    base_url="https://capimail.com",  # default
    timeout=30,                       # seconds, default
    transport=None,                   # optional callable(HttpRequest) -> HttpResponse
)
```

`timeout` must be a positive, finite number of seconds; anything else raises `ValueError`.

`transport` lets you plug in another HTTP stack or a fake in your own tests; the default uses `urllib.request`.

The default transport never follows HTTP redirects, so your API key is only ever sent to `base_url`. A 3xx response raises `CapiMailError` with `code="unexpected_redirect"` (and `status` set to the 3xx); point `base_url` at the final API origin, for example `https://capimail.com` rather than a host that redirects to it. If you write your own transport, do not follow redirects either.

## License

MIT
