Skip to main content

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.

Install

pip install capimail

Quickstart

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

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

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:

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

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

# 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

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

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

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

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:

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

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

Metadata

Release files for capimail 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for capimail 0.1.1
File Size Uploaded Provenance Actions
capimail-0.1.1.tar.gz 27.3 kB Without provenance Details for capimail-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for capimail 0.1.1
File Interpreter ABI Platform Actions
capimail-0.1.1-py3-none-any.whl Python 3 none any Details for capimail-0.1.1-py3-none-any.whl

Total release size: 48.4 kB

Release files / capimail-0.1.1.tar.gz

Download URL capimail-0.1.1.tar.gz
Size 27.3 kB
Tags Source
SHA-256 checksum
How to use checksums
c8365e5e67d5d8f700cd05d3f7a6d7837f58c406646b8c34c01c02a9f7d49cf4
BLAKE2b-256 checksum
How to use checksums
a1b717c686543f8cd69d55ab198dfdd68478552271e16c0368129b8d2451a762
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Release files / capimail-0.1.1-py3-none-any.whl

Download URL capimail-0.1.1-py3-none-any.whl
Size 21.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1c75f4df8973b6e6cd75e13a34063d912565bedd73f6d91880328c1408a765bd
BLAKE2b-256 checksum
How to use checksums
bfb4ae44762000c3681f58318933456a7b81b141a65ec223d9a5d4670cc4b015
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Security for capimail 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page