Mailkube) and an asynchronous one (AsyncMailkube), and requires Python 3.12+.
Install
Get your API key
Create a key for a verified domain in the dashboard. The key is a string that starts withmk_. See Authentication for how to send it and keep it safe.
Send your first email
Initialize the client with your key and callclient.emails.send:
from_ with a trailing underscore because from is a reserved keyword in Python. The SDK maps it to the wire from field for you.
Configure the client
Pass the key explicitly withapi_key=, or omit it and let the client read the MAILKUBE_API_KEY environment variable:
timeout= (30 seconds by default), user_agent_suffix=, and an http_client= if you want to supply your own configured httpx client for proxying or instrumentation. If you are building something on top of this SDK, such as a CLI, an internal service, or a framework integration, set user_agent_suffix to your own name/version. It is appended after the SDK’s own token, so both are visible: mailkube-python/1.7.0 my-cli/1.0.0. The API requires a User-Agent on every request; the SDK already sends one, and this identifies your layer within it.
The response
A successful send returns an object with two identifiers:email.id to correlate the message with webhook events. Use email.message_id to thread replies; see Reply threading.
Recipients and content
to, cc, and bcc each accept a single address string or a list of them. Supply html, text, or both. At least one is required for a raw send. Set a reply_to (string or list) to route replies to a different address:
tags is a list of name/value dicts, denormalized onto every event the message produces, for webhook and log-search slicing. See Tags for the naming rules. topic attributes the send to a mailing-list topic by its slug, which is what lets a recipient opt out of that stream without unsubscribing from everything.
To send a saved template, pass
template_id (and optional template_version) with a variables dict, and drop html/text. See Sending your first email for template behavior.Attachments
Attach files with a list of dicts.content accepts either raw bytes or a base64-encoded string; content_type is optional:
Reply threading
Pass the previous message’smessage_id in the In-Reply-To and References headers so replies thread correctly in the recipient’s inbox:
Idempotent sends
Pass anidempotency_key to make retries safe. A repeated request with the same key and body returns the original result, and the message is sent only once:
Scheduled sends
Passscheduled_at to transmit later. It takes an ISO-8601 string or a timezone-aware datetime. The acknowledgment reports email.is_scheduled, and until the message is due it stays manageable through client.scheduled_emails:
list returns one ScheduledEmailPage and filters on status, batch_id, scheduled_at_gte, scheduled_at_lte and page. iter_all takes the same filters and walks every page lazily, yielding items as it goes:
AsyncMailkube as well; iter_all becomes an async for. See Scheduled emails for the horizon, the listable statuses, and the plan requirement.
Your API key
client.credential.info() returns the key the client authenticates with: its domain, organization, source-IP allowlist, plan and send-quota usage.
AuthenticationError with the error name invalid_api_key, and Checking a key lists the causes. Each call counts as a use of the key, and plan and quota figures can be up to 30 seconds old. AsyncMailkube has the same method; await it.
plan is None when the organization has no subscription. A plan without a daily limit lists emails_per_month only, and remaining counts recipients, not messages. The call has a rate limit of its own for each key.
The client keeps the key it was constructed with. To use another key, construct another client.
Handling errors
Every failure raises a subclass ofMailkubeError. Catch the specific types you want to handle, then fall back to the base class. RateLimitError exposes .retry_after, and every API error carries .error_name, .message, .status_code and .request_id:
MailkubeError includes AuthenticationError, BadRequestError, InvalidRequestError, NotFoundError, ConflictError, RateLimitError, ServerError, and MailkubeConnectionError. See Errors for what each error_name means.
Quote request_id when reporting a failure to support.
Receiving webhooks
verify checks the signature over the raw request body and returns a typed event. It needs no client instance and no HTTP, and drops into any framework’s handler:
verify applies a 300-second freshness window on X-Webhook-Ts, which is what rejects a replayed delivery. Widen or narrow it with the keyword-only tolerance_seconds=.
Typed events exist for email.sent, email.delivered, email.bounced, email.delivery_delayed, email.suppressed, email.scheduled, email.failed, email.opened, email.clicked, domain.status and webhook.status. Anything newer arrives as an UnknownEvent that keeps the server’s type string and the full data dict. A receiver that logs or forwards events never loses a field.
Two narrower functions sit underneath, if you want the halves separately. verify_signature runs the signature and freshness checks and returns the payload bytes unparsed. parse_event parses bytes you have already verified. It raises on invalid JSON, not SignatureVerificationError, which only ever comes from the two verifying functions.
X-Webhook-Id is stable across retries. Deduplicate on it before acting. See Webhooks for the full event catalog.
Signing, for your tests
Production code verifies; it never signs.sign is the other half, for building a request your handler will accept without waiting on a real delivery:
verify checks it, so a fixture built this way cannot drift from the verifier the way a hand-rolled hmac.new eventually does. It takes the timestamp you give it and does not judge its freshness. Pass a stale one to assert that your handler rejects a replay.
Async
UseAsyncMailkube from an event loop. The async with block opens the client and closes it cleanly when the block exits:
Reuse a single client for the lifetime of your process.
Mailkube is thread-safe; AsyncMailkube is bound to the event loop it was created on. Close a sync client with a with Mailkube() as client: block or by calling client.close().Logging
Silent by default. Callmailkube.enable_logging() to attach a stream handler to the mailkube logger, or set MAILKUBE_LOG to a level name. Requests and responses are logged with Authorization and Idempotency-Key redacted:
MAILKUBE_LOG is a level, not a switch: MAILKUBE_LOG=WARNING suppresses debug records rather than merely turning logging on. The SDK logs through the standard logging module. Your own handler configuration on the mailkube logger works without enable_logging at all.
Use with FastAPI
FastAPI is async all the way down and pairs withAsyncMailkube. A lifespan builds one client on startup and awaits aclose() on shutdown; every request reuses the same connection pool off app.state:
main.py
except clauses narrow from most to least specific, and the last one matters: a connection failure raises MailkubeConnectionError, which carries no server envelope, so only APIError instances have .message and .error_name to quote.
Run it with uvicorn main:app --reload. AsyncMailkube is bound to the event loop it was created on, so let FastAPI own its startup and shutdown rather than constructing one inside a request handler.
Use with Flask
Flask serves a request per thread, which matches the synchronous client:Mailkube is thread-safe, so one module-level instance shares its pooled connection across every worker thread:
app.py
flask --app app run and post JSON with to, subject and html. The webhook receiver above is already written as a Flask route; mount both in the same app and one process sends and receives.
Next steps
Django
Route every
send_mail through mailkube with the dedicated email backend.API reference
Field-by-field coverage of the send endpoint, its error codes, and rate limits.