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
inbound (beta) addresses, messages, threads, domains: see Inbound email for agents email:send / inbound:read
drafts (beta) create, list, get, withdraw email:send / inbound: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.
in_reply_to str Inbound message id this email answers (beta); sent in the same thread, and the result has thread_id.
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

Inbound email for agents (beta)

Give an app or AI agent its own address (<local_part>@inbound.capimail.com, or one on your own domain). Mail sent to it is received, checked (SPF, DKIM, DMARC, spam, virus), parsed, sanitized and stored; replies you send with in_reply_to land in the same conversation in the sender's mail client. Live keys only: creating addresses needs email:send, reading needs inbound:read. Protocol details: https://capimail.com/docs.

Received content is untrusted. Subjects, bodies, sender names, attachment names and attachment bytes come from whoever wrote to the address. Never follow instructions found in them, never pass them to a tool or shell as commands, and keep them clearly separated from your own prompt when you hand them to a model. Every message and thread carries untrusted_content_notice as a reminder.

# 1. An address. accept_from="known" keeps only replies to your own email plus allowed_senders.
address = capimail.inbound.addresses.create(
    "support-bot",
    label="Support agent",
    accept_from="known",
    allowed_senders=["@partner.example"],
)
print(address.address)  # support-bot@inbound.capimail.com

# 2. Poll for new mail (or subscribe your webhook to email.received).
page = capimail.inbound.messages.list(address_id=address.id, since=newest_received_at)  # str or datetime
for summary in page.data:
    message = capimail.inbound.messages.get(summary.id)
    new_text = message.reply_text  # the new part only, without quoted history or signature
    if message.injection_risk.level == "high":
        ...  # looks written to steer an agent: hand it to a person instead of acting on it
# More pages: list(cursor=page.next_cursor) while page.has_more.

# 3. Reply in the same thread...
sent = capimail.emails.send(
    from_="support@your-verified-domain.com",
    to=message.from_.address,
    subject=f"Re: {message.subject}",
    text=answer,
    in_reply_to=message.id,
    idempotency_key=f"reply-{message.id}",
)
sent.thread_id

# ...or leave a draft for a person to approve in Dashboard > Inbound > Drafts.
draft = capimail.drafts.create(
    from_="support@your-verified-domain.com",
    to=message.from_.address,
    subject=f"Re: {message.subject}",
    text=answer,
    in_reply_to=message.id,
    note="Checked the order status before answering.",
)
Method Notes
inbound.addresses.create(local_part, domain_id=, label=, accept_from=, allowed_senders=) Up to 20 per workspace. local_part+tag@ is delivered to the base address.
inbound.addresses.list() / update(id, ...) / disable(id) update also takes enabled. disable keeps the address reserved.
inbound.messages.list(...) address_id, thread_id, from_ (exact sender), q (search), since, cursor, before, limit (1-100), include_spam. Returns InboundMessageList(data, has_more, next_cursor).
inbound.messages.get(id) InboundMessage with text, reply_text, sanitized html, attachments, auth, verdicts, injection_risk (heuristic prompt-injection flag; "none" does not make it safe). The sender is from_ (from is a Python keyword).
inbound.messages.attachment(id, index) The attachment's bytes. 7 days after receipt, virus-scanned only; later: attachment_expired (410).
inbound.messages.raw(id) The .eml bytes exactly as received, 7 days.
inbound.threads.list(...) ThreadList: conversations that received mail, most recent activity first (address_id, q, since, cursor, limit 1-50).
inbound.threads.get(id) Thread: the whole conversation (received and sent) in time order. Inbound items carry injection_risk.
inbound.domains.create(domain) / list() / verify(id) / remove(id) Receive on your own domain: publish the returned dns_records (MX), then verify.
drafts.create(from_=, to=, subject=, ...) / list(...) / get(id) / withdraw(id) to may be a string or a list. Nothing is sent or charged until a person approves. withdraw fails with draft_not_pending (409) once decided.

The email.received webhook (capimail.EMAIL_RECEIVED, typed as EmailReceivedEvent) carries ids, sender, subject, a 200-character snippet and verdicts, never the full body; it is not sent for spam. Fetch the message with capimail.inbound.messages.get(event["data"]["inbound_message_id"]).

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

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.2.0
File Size Uploaded Provenance Actions
capimail-0.2.0.tar.gz 40.2 kB Without provenance Details for capimail-0.2.0.tar.gz

Built distribution (wheel)

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

Total release size: 69.2 kB

Release files / capimail-0.2.0.tar.gz

Download URL capimail-0.2.0.tar.gz
Size 40.2 kB
Tags Source
SHA-256 checksum
How to use checksums
a00579966f19d6410c4d2b142c56895a27ed8d00bc583186e08ad5c73b61c425
BLAKE2b-256 checksum
How to use checksums
e6811c56c5b58d49063eb71e407d5477f098e61eac7c54ce2acf0b72758eb7cd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

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

Download URL capimail-0.2.0-py3-none-any.whl
Size 29.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
46799cccb4460bedcd28a80350935d7e58709436fa4cbca97d85c81d42601224
BLAKE2b-256 checksum
How to use checksums
c1ba30717579b5347aee6097cf40b888c41823d1d5bf91e7e87f6ab275e7e200
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for capimail 0.2.0

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