Python SDK
Install the mailcraft package and send email from Python 3.9+ using only the standard library.
The official SDK for Python 3.9+. It uses only the standard library (urllib), so it installs anywhere — Django, Flask, FastAPI or a cron script — and ships full type hints.
Install
pip install mailcraft
Send your first email
from mailcraft import MailCraft
client = MailCraft() # reads MAILCRAFT_API_KEY
res = client.send(
{
"from": "Example Shop <no-reply@mail.example.com>",
"to": "customer@example.org",
"subject": "Order #10042 confirmed",
"htmlbody": "<h1>Thanks for your order</h1><p>We are getting it ready.</p>",
"textbody": "Thanks for your order. We are getting it ready.",
},
idempotency_key="order-10042-receipt",
)
print(res["message_id"], res["credits_remaining"])
Keyword arguments work too — use from_ because from is a Python keyword:
client.send(
from_="no-reply@mail.example.com",
to=["a@example.org", {"address": "b@example.org", "name": "B"}],
subject="Scheduled maintenance",
textbody="We will be down tonight 23:00–01:00 (UTC+7).",
)
Attachments
from mailcraft import Attachment
with open("INV-001.pdf", "rb") as f:
pdf = f.read()
client.send({
"from": "billing@mail.example.com",
"to": "customer@example.org",
"subject": "Receipt INV-001",
"textbody": "Your receipt is attached.",
"attachments": [Attachment("INV-001.pdf", pdf, "application/pdf")],
})
Templates, scheduling, batches and cancel
from datetime import datetime, timedelta, timezone
BANGKOK = timezone(timedelta(hours=7))
r = client.send(
from_="hello@mail.example.com",
to="somchai@example.org",
template_alias="welcome",
template_data={"name": "Somchai"},
send_at=datetime(2027, 1, 2, 9, 0, tzinfo=BANGKOK),
list_unsubscribe=True,
)
client.cancel(r["message_id"])
client.send_batch([message1, message2])
status = client.get(r["message_id"])
Naive datetime values are treated as UTC — always pass a timezone.
Errors
from mailcraft import MailCraftError, InsufficientCreditsError, RateLimitError
try:
client.send(message)
except InsufficientCreditsError as e:
print(f"Balance {e.balance}, required {e.required}")
except RateLimitError as e:
print(f"Rate limited, retry in {e.retry_after} s")
except MailCraftError as e:
print(e.status, e.code, e.field, e.message)
Subclasses: ValidationError, AuthenticationError, InsufficientCreditsError, PermissionDeniedError, NotFoundError, ConflictError, PayloadTooLargeError, RateLimitError, ServerError and APIConnectionError (network_error or timeout).
Automatic retries
Up to 2 retries on 429 / 5xx / network errors, honouring Retry-After, with an automatic Idempotency-Key on every send so nothing is delivered or charged twice.
client = MailCraft(api_key="maas_live_...", timeout=30, max_retries=2, max_retry_delay=60)
Verify webhooks
from mailcraft import parse_event
# Flask: request.get_data() · Django: request.body
event = parse_event(raw_body, request.headers.get("MailCraft-Signature"), secret)
Flask and Django examples: Verify webhook signatures.