MailChannels Python SDK

Built and tested against MailChannels Email API 1.7.0.
mailchannels is a typed Python SDK for the MailChannels Email API. It keeps
the first send small, then opens up the production features that matter when
email is part of a real product: queued delivery through /send-async,
MailChannels-hosted DKIM, domain validation, templates, unsubscribe behavior,
custom headers, metrics, suppressions, and webhooks.
MailChannels is especially strong for multi-tenant sending. Parent accounts can
create isolated sub-accounts, issue separate credentials, set granular limits,
inspect usage, and keep one customer's bad traffic from endangering the parent
account or other tenants.
The SDK accepts familiar dictionary payloads for quick scripts and Pydantic
models for codebases that prefer explicit runtime validation. Use the
module-level resources when you want Resend-style convenience; create explicit
Client instances when each tenant, account, or service needs its own
credentials.
Start Here
- Official documentation: Python quickstart and Email API overview.
- New to the SDK: start with Five-Minute Quickstart.
- Using Django or FastAPI: see Framework Recipes for typed sender payloads, application configuration and client lifecycle.
- Building a sending workflow: use Common Sending Recipes.
- Building a multi-tenant product: read Account And Domain Operations.
- Operating at scale: jump to Production Operations.
- Using an AI coding agent: see Using This SDK With An AI Agent.
- Looking for details: see API Reference And Further Reading.
Five-Minute Quickstart
Install
Install the SDK with uv:
uv add mailchannels
The synchronous client uses requests. Async HTTP support is optional:
uv add "mailchannels[async]"
Configure
For small applications and scripts, set the module-level API key once and use
the top-level resources.
import mailchannels
mailchannels.api_key = "YOUR-API-KEY"
The SDK also reads MAILCHANNELS_API_KEY and MAILCHANNELS_API_URL from the
environment. Environment variables are the cleanest option for deployed
services because the same code can run in development, staging, and production
without committing credentials or hostnames.
export MAILCHANNELS_API_KEY="YOUR-API-KEY"
For services that send on behalf of multiple accounts, create explicit clients.
Each client carries its own API key.
import mailchannels
parent_client = mailchannels.Client(api_key="PARENT-ACCOUNT-API-KEY")
sub_account_client = mailchannels.Client(api_key="SUB-ACCOUNT-API-KEY")
If you build a plugin, integration or product on the SDK, name it with
user_agent. Requests send User-Agent: my-app/1.2.0 mailchannels-python/<version>,
so MailChannels can tell your traffic apart from other SDK users.
import mailchannels
client = mailchannels.Client(api_key="YOUR-API-KEY", user_agent="my-app/1.2.0")
Send
Use Emails.send() when you want immediate validation feedback from the regular
send endpoint.
import mailchannels
mailchannels.api_key = "YOUR-API-KEY"
email = mailchannels.Emails.send(
{
"from": {"email": "sender@example.com", "name": "Priya Patel"},
"to": [{"email": "recipient@example.net", "name": "Sakura Tanaka"}],
"subject": "Testing Email API",
"text": "Hi Sakura. This is just a test from Priya.",
}
)
print(email)
Use Emails.queue() for /send-async when your application should hand the
message to MailChannels quickly and continue without waiting for the regular
send path.
queued = mailchannels.Emails.queue(
{
"from": {"email": "sender@example.com"},
"to": [{"email": "recipient@example.net"}],
"subject": "Queued message",
"html": "<strong>Hello</strong>",
}
)
This is usually the better default for high-throughput web applications, job
workers, or any path where email should not slow down the user-facing request.
Send vs Queue, And The Two Meanings Of "Async"
The SDK exposes four sending methods, and the names can be confusing because
"async" means two different things:
| Method |
API endpoint |
Python execution |
Emails.send() |
/send |
synchronous (blocks the calling thread) |
Emails.send_async() |
/send |
asyncio (await-able) |
Emails.queue() |
/send-async |
synchronous (blocks the calling thread) |
Emails.queue_async() |
/send-async |
asyncio (await-able) |
send vs queue is a server-side distinction: both endpoints run the
same request validation and have the same delivery semantics, but
/send-async defers some per-recipient processing into the background so the
request returns faster. The _async suffix is a separate, client-side
Python asyncio distinction — it's the same suffix used on every other resource
(e.g. client.webhooks.list_async()).
Rule of thumb: prefer queue when request latency matters, and especially
for sends with a large number of recipients — the per-recipient work on
the /send path can be slow enough that the request times out. Pick send
only when you specifically need the regular (non-deferred) path. Add _async
if you're calling from asyncio code.
Core Concepts
API Coverage
The SDK covers the MailChannels Email API surfaces that production senders need
most often:
| Need |
SDK surface |
Send now with /send |
mailchannels.Emails.send() |
Queue for processing with /send-async |
mailchannels.Emails.queue() |
| Validate sender DNS and Domain Lockdown |
mailchannels.CheckDomain.check() |
| Manage hosted DKIM keys |
mailchannels.Dkim |
| Isolate tenants |
mailchannels.SubAccounts |
| Cap tenant volume |
mailchannels.SubAccounts.Limits |
| Inspect traffic health |
mailchannels.Metrics |
| Manage suppressions |
mailchannels.Suppressions |
| Receive delivery events |
mailchannels.Webhooks |
Generated reports provide the deeper detail:
- API coverage report summarizes endpoint coverage,
contract-test coverage, online-test coverage, the OpenAPI spec hash, and the
SDK version used for the report.
- API reference lists public exports, classes, methods,
parameters, return types, model fields, and compact examples from the SDK
source.
Choose An Entry Point
| Use this |
When it fits |
mailchannels.Emails.send() |
You want synchronous validation from /send. |
mailchannels.Emails.queue() |
You want fast handoff to /send-async; this is usually best for web requests and workers. |
mailchannels.CheckDomain.check() |
You are onboarding or troubleshooting a sending domain. |
mailchannels.Dkim |
You need MailChannels to create, store, rotate, or validate hosted DKIM keys. |
mailchannels.SubAccounts |
You send for multiple tenants and need isolation, credentials, usage, or limits per tenant. |
Explicit mailchannels.Client(...) |
You need different API keys, base URLs, or HTTP transports in the same process. |
Path Variables
Pass raw identifiers to SDK methods. The SDK URL-encodes path variables such as
sub-account handles, DKIM domains/selectors, suppression recipients, metric
sender groups, and webhook batch IDs before building request URLs. Do not
pre-encode those values yourself; a literal % is encoded as %25.
Redirects
The built-in synchronous and asynchronous transports do not follow HTTP
redirects, including redirects to the same host. This prevents forwarding
X-Api-Key and replaying send or management requests at a redirect target.
A redirect raises ApiError through Client, with the original status and
response headers. Direct transport calls return the original SDKResponse.
Configure the intended API base URL explicitly; do not automatically retry a
redirect or copy its Location into a new request. Custom transports should
also disable redirect following. Response bodies are still read normally;
this policy does not impose a response-size limit or a total elapsed deadline.
Read Responses
SDK responses behave like ordinary dictionaries, but they also support
attribute access. HTTP response headers are preserved under http_headers for
diagnostics and request IDs.
queued = mailchannels.Emails.queue(message)
print(queued["id"])
print(queued.id)
print(queued.http_headers)
Set strict_responses=True when you want modeled endpoints to return Pydantic
response objects instead. See Advanced Usage for strict
response models, custom transports, API compatibility metadata, and client
lifecycle details.
Use Typed Models
Dictionary payloads are convenient, but long-lived applications often benefit
from explicit types. EmailParams, EmailAddress, Content, and
Personalization are Pydantic models that validate the request before it reaches
the HTTP layer.
params = mailchannels.EmailParams(
from_=mailchannels.EmailAddress(email="sender@example.com"),
personalizations=[
mailchannels.Personalization(
to=[mailchannels.EmailAddress(email="recipient@example.net")]
)
],
subject="Typed message",
content=[
mailchannels.Content(type="text/plain", value="Hello from typed models.")
],
)
mailchannels.Emails.send(params)
Use typed models when you are constructing messages across several functions or
want validation errors to appear close to the code that builds the payload.
Common Sending Recipes
Add Attachments
MailChannels expects attachment content to be Base64 encoded. The SDK's
Attachment.from_bytes() helper handles that encoding, infers a MIME type
from the filename, and preserves the MailChannels fields in the final send
payload. Read the file or fetch the URL yourself and pass the bytes in — the
SDK does not read files or make outbound HTTP requests on your behalf.
from pathlib import Path
invoice = mailchannels.Attachment.from_bytes(
Path("invoice.pdf").read_bytes(),
filename="invoice.pdf",
)
mailchannels.Emails.queue(
{
"from": {"email": "billing@example.com"},
"to": [{"email": "recipient@example.net"}],
"subject": "Your invoice",
"text": "Your invoice is attached.",
"attachments": [invoice],
}
)
Preview With Dry Run
MailChannels supports dry-run validation on the send endpoint. Pass
dry_run=True to send the request for validation and rendering checks without
delivering the message.
preview = mailchannels.Emails.send(
{
"from": {"email": "sender@example.com"},
"to": [{"email": "recipient@example.net"}],
"subject": "Dry run",
"text": "Validate this message without delivering it.",
},
dry_run=True,
)
Send A Template Email
MailChannels templates are part of the send payload rather than a separate
template CRUD API. Mark each templated content part with
template_type: "mustache" and provide recipient-specific values in
dynamic_template_data.
preview = mailchannels.Emails.send(
{
"from": {"email": "sender@example.com"},
"personalizations": [
{
"to": [{"email": "jane@example.net"}],
"dynamic_template_data": {"name": "Jane Doe"},
}
],
"subject": "Template Example",
"content": [
{
"type": "text/plain",
"value": "Hello {{name}}",
"template_type": "mustache",
}
],
},
dry_run=True,
)
Manage DKIM Keys
MailChannels can generate and store DKIM private keys for your account. Create a
key pair, publish the returned public DNS record in your own DNS zone, and then
reference the selector when sending.
key = mailchannels.Dkim.create(
"example.com",
selector="mcdkim",
algorithm="rsa",
key_length=2048,
)
for record in key.get("dkim_dns_records", []):
print(record["name"], record["type"], record["value"])
After the DNS record is published, send mail with the selector.
mailchannels.Emails.queue(
{
"from": {"email": "sender@example.com"},
"to": [{"email": "recipient@example.net"}],
"subject": "DKIM signed message",
"text": "This message is signed by a MailChannels-hosted DKIM key.",
"dkim_domain": "example.com",
"dkim_selector": "mcdkim",
}
)
See DKIM And DNS for key rotation, customer-managed private
keys, and a Cloudflare DNS publication example.
Custom Tracking Domains
By default, MailChannels rewrites click/open tracking links and unsubscribe
URLs to use shared MailChannels domains. Register your own hostname instead
to keep those links on your brand.
The hostname needs a CNAME record pointing to links.mailchannels.net
before registration can complete. If DNS ownership hasn't been verified
yet, create() returns TXT record instructions instead of an active
domain — add the TXT and CNAME records, then call create() again:
domain = mailchannels.CustomTrackingDomains.create(
name="newsletter-clicks",
hostname="click.example.com",
scope="click", # "click" | "open" | "unsubscribe"
)
if domain.get("status") != "active":
print(domain.get("instructions"))
print(domain.get("txt_record_name"), domain.get("txt_record_value"))
Once a domain is active, select it by name at send time:
mailchannels.Emails.queue(
{
"from": {"email": "sender@example.com"},
"to": "recipient@example.net",
"subject": "Newsletter",
"text": "Hello",
"tracking_settings": {
"click_tracking": {"enable": True, "custom_domain_name": "newsletter-clicks"},
},
"unsubscribe_settings": {"custom_domain_name": "newsletter-unsubscribe"},
}
)
CustomTrackingDomains.list(), update() (rename or toggle active/
disabled), and delete() round out the resource. See
Custom Tracking Domains
for the full DNS verification flow.