How to Send Email from Python with an API: Scripts, FastAPI and Django
Send email from Python without an SMTP server: an email API for HTML, attachments, FastAPI and Django, with replies in the same inbox.

You want to send email from Python: a receipt after checkout, a sign-in code, a nightly report, a reply from your app or your agent. The standard library’s smtplib can do it, but only once you have an SMTP server, a username and password, the right port and a TLS setting that matches. If what you want is “call a function, an email goes out”, an email API is the shorter path.
This tutorial shows how to send email with Python using Mailcycle’s Python SDK, the mailcycle package. You’ll send plain text, HTML and attachments from a script, then wire the same client into a FastAPI endpoint and Django’s send_mail. Then comes the part a send-only API can’t do: the customer’s reply lands back in the same address, and your Python code reads it and answers in the thread.
Every snippet below is checked against the SDK’s source with mypy, so the method names and arguments are the real ones.
Quick answer: how to send email in Python
To send email from Python without an SMTP server, install the mailcycle package, put an API key in an environment variable, and call mc.messages.send() with a from_address on your account, one recipient, a subject and a text body. The call makes one HTTPS request and returns the sent message’s Message-ID.
pip install mailcycle
import os
from mailcycle import Mailcycle
mc = Mailcycle.with_api_key(os.environ["MAILCYCLE_API_KEY"])
result = mc.messages.send(
from_address=os.environ["MAILCYCLE_FROM"], # an address on your account
to="customer@example.com",
subject="Your order has shipped",
text="Good news: order 1042 is on its way.",
)
print(result.message_id)
That is the whole send. The rest of this guide covers what you’ll need in a real app: HTML, attachments, frameworks, async code, replies and errors.
Prerequisites
- Python 3.10 or later. Check with
python3 --version. - A Mailcycle account on the Scale plan, or the free 7-day Scale trial. Sending with an API key is a Scale feature. Start the trial under Plans & Billing in the web app, with no card.
- An address to send from. Every message goes out from an address on your account. Create one in the app, or with the SDK as shown in step 2.
- FastAPI or Django 5.2+, only if you want to follow those sections.
Step 1: Install the Python email library
Install the package into your project’s virtual environment with pip, uv or Poetry:
pip install mailcycle
# or: uv add mailcycle
# or: poetry add mailcycle
Version 0.8.0 is current at the time of writing. It depends on httpx for HTTP and cryptography for the encryption it does on your machine. If you want replies pushed to your code over a WebSocket (covered later), install the events extra instead:
pip install 'mailcycle[events]'
The package ships type hints (py.typed), so your editor completes mc.messages.send( and mypy or Pyright catches a misspelt argument before it runs.
Step 2: Create an API key and an address to send from
In the app, open API, then the Keys tab, name the key and choose Create key. The token starts with mak_ and is shown once, so copy it straight into your environment or secret store:
export MAILCYCLE_API_KEY="mak_..."
export MAILCYCLE_FROM="orders-x7k2@example-pool.email" # an address on your account
Keep the key out of your code and out of Git. In production, set it the way you set any other secret: your platform’s environment settings, a .env file that is never committed, or a secret manager.
To see the addresses the key can send from:
import os
from mailcycle import Mailcycle
with Mailcycle.with_api_key(os.environ["MAILCYCLE_API_KEY"]) as mc:
for address in mc.addresses.list():
print(address.email_address, address.id)
Mailcycle is a context manager, so the with block closes its HTTP connections when it ends. That is handy for one-off scripts.
To create a new address from Python, the client needs your recovery phrase as well as the key. The address’s encryption key is derived from the phrase on your machine, and only the public half is uploaded, so the mail server can seal what arrives:
import os
from mailcycle import Mailcycle
mc = Mailcycle.with_api_key(
os.environ["MAILCYCLE_API_KEY"],
phrase=os.environ["MAILCYCLE_PHRASE"],
)
address = mc.addresses.create(prefix="orders", label="Order notifications")
print(address.email_address) # orders-x7k2@...
prefix="orders" gives you orders- followed by a random ending on a shared domain. On Scale you can also pick an exact name, or use your own domain.
Step 3: Send your first email from a Python script
Save the quick-answer snippet as send.py and run it:
python send.py
It prints something like <…@…>: the Message-ID header the email went out with. send() takes keyword arguments only, which keeps calls readable:
| Argument | Required | What it does |
|---|---|---|
from_address |
Yes | An address on your account. Any other is refused with not_your_address. |
to |
Yes | One recipient per call. |
subject |
Yes | The subject line. |
text |
Yes | The plain-text body. |
html |
No | An HTML body, sent alongside the text. |
from_name |
No | A display name for the From line, like Acme Support. |
reply_to |
No | A received Message you are answering. Fills in the threading headers. |
attachments |
No | A list of OutgoingAttachment files. |
The return value is a frozen dataclass, SendResult, with two fields:
message_id: theMessage-IDheader, worth storing next to the order or ticket it belongs to.sent_copy_id: the id of the copy filed in the address’s Sent folder, whichmc.messages.get()takes. It isNonefor an address that keeps no copy.
The same send as a raw HTTP request (cURL)
Under the hood the client makes one POST to https://api.mailcycle.email/messages/send. Here is the same call with cURL, which is handy for checking a key from the terminal:
curl https://api.mailcycle.email/messages/send \
-H "Authorization: Bearer $MAILCYCLE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"from": "orders-x7k2@example-pool.email",
"to": "customer@example.com",
"subject": "Your order has shipped",
"text": "Good news: order 1042 is on its way."
}'
{ "sent": true, "messageId": "<…>", "sentCopyId": "msg_…" }
You could call this endpoint with httpx or requests yourself. The SDK adds typed arguments, base64 encoding for attachments, threading headers from a Message, errors as exceptions with a stable code, and, most usefully, the decryption you need to read replies. The full field list is in Sending mail.
Step 4: Share one client across your app
In a script, building a client inline is fine. In an app, build it once per process and reuse it, so every send doesn’t open a new connection. A small mailer.py module with functools.cache does it without globals you have to remember to initialise:
# mailer.py
import os
from functools import cache
from mailcycle import Mailcycle
@cache
def client() -> Mailcycle:
"""One client per process, built on first use."""
return Mailcycle.with_api_key(
os.environ["MAILCYCLE_API_KEY"],
phrase=os.environ.get("MAILCYCLE_PHRASE"), # only needed to read replies
timeout=15.0,
)
FROM_ADDRESS = os.environ.get("MAILCYCLE_FROM", "orders-x7k2@example-pool.email")
timeout is in seconds and defaults to 30. The phrase is optional: without it the client can send and manage addresses, but it can’t open mail. When you pass it, the client checks the phrase belongs to the key’s account before it opens anything. The rest of this tutorial imports client and FROM_ADDRESS from this module.
Is the Python SDK sync or async?
It is synchronous. Each call blocks until the API answers, and it is built on an httpx.Client. That suits scripts, Django views, management commands, Celery tasks and FastAPI’s def routes, which all run in threads. In async def code, hand the call to a thread so the event loop keeps serving other requests:
import asyncio
from mailer import FROM_ADDRESS, client
async def notify(to: str, subject: str, text: str) -> str:
result = await asyncio.to_thread(
client().messages.send, from_address=FROM_ADDRESS, to=to, subject=subject, text=text
)
return result.message_id
async def main() -> None:
message_id = await notify("ops@example.com", "Nightly export finished", "4,210 rows exported.")
print(message_id)
asyncio.run(main())
asyncio.to_thread passes keyword arguments through, so the call reads almost the same as the synchronous one.
Send HTML email in Python (with a plain-text part)
text is always required, and html is optional. Send both: the HTML is what most people see, and the plain text is what shows in previews, in text-only clients and for screen readers that prefer it.
Attachments work the same way whatever the body. You pass raw bytes, and the client base64-encodes them. A short helper that guesses the MIME type from the file name with the standard library’s mimetypes keeps calls tidy:
import mimetypes
from pathlib import Path
from mailcycle import OutgoingAttachment
from mailer import FROM_ADDRESS, client
def attach(path: Path, content_id: str | None = None) -> OutgoingAttachment:
mime_type, _ = mimetypes.guess_type(path.name)
return OutgoingAttachment(
path.name,
path.read_bytes(),
mime_type=mime_type or "application/octet-stream",
content_id=content_id,
)
html = """
<img src="cid:logo" alt="Acme" width="120">
<h1>Invoice 1042</h1>
<p>Thanks for your order. Your invoice is attached.</p>
"""
client().messages.send(
from_address=FROM_ADDRESS,
from_name="Acme Billing",
to="customer@example.com",
subject="Invoice 1042",
text="Thanks for your order. Your invoice is attached.",
html=html,
attachments=[
attach(Path("invoices/1042.pdf")),
attach(Path("static/logo.png"), content_id="logo"),
],
)
Three things to note:
from_namesets the display name, so the inbox shows “Acme Billing” rather than the bare address.- Inline images use
content_id. The logo above hascontent_id="logo", and the HTML shows it with<img src="cid:logo">. It travels inside the message, so it doesn’t depend on a remote image the recipient’s client may block. - Templates are up to you. Render the HTML with Jinja2, Django’s template engine or an f-string, and pass the result as a string.
Python: send email with an attachment
The example above already attaches a PDF. A few details matter once real files are involved:
OutgoingAttachment(filename, content, mime_type=None, content_id=None)is a frozen dataclass.contentmust bebytes: read files withPath.read_bytes(), or pass the bytes of a PDF or CSV you generated in memory, such asbuffer.getvalue()from anio.BytesIO.- Without
mime_type, the file goes out asapplication/octet-stream. Set it so the recipient’s client knows to preview a PDF or an image. - A message can carry up to ten files, 3.5 MB between them. The client refuses more before sending, with the same error code the API would use,
too_many_attachmentsorattachments_too_large, so you find out without a round trip. - Program and script files, like
.exeand.js, are refused withattachment_blocked.
For anything larger, such as a big export, put the file behind a link in your app and email the link.
FastAPI: send email from an endpoint
FastAPI gives you three good places to send from, and which you pick decides whether the request waits for the email.
# main.py
import json
import os
from typing import Annotated
from fastapi import BackgroundTasks, FastAPI, Header, HTTPException, Request
from fastapi.concurrency import run_in_threadpool
from mailcycle import APIError, verify_webhook_signature
from pydantic import BaseModel, EmailStr
from mailer import FROM_ADDRESS, client
app = FastAPI()
WEBHOOK_SECRET = os.environ.get("MAILCYCLE_WEBHOOK_SECRET", "")
class SignUp(BaseModel):
email: EmailStr
name: str
def send_welcome(email: str, name: str) -> None:
client().messages.send(
from_address=FROM_ADDRESS,
from_name="Acme",
to=email,
subject=f"Welcome to Acme, {name}",
text=f"Hi {name},\n\nYour account is ready.",
html=f"<p>Hi {name},</p><p>Your account is ready.</p>",
)
@app.post("/signup", status_code=202)
def signup(body: SignUp, background: BackgroundTasks) -> dict[str, str]:
# ...create the user...
background.add_task(send_welcome, body.email, body.name)
return {"status": "ok"}
@app.post("/receipts/{order_id}")
async def send_receipt(order_id: str, to: EmailStr) -> dict[str, str]:
try:
result = await run_in_threadpool(
client().messages.send,
from_address=FROM_ADDRESS,
to=to,
subject=f"Receipt for order {order_id}",
text=f"Thanks for order {order_id}.",
)
except APIError as error:
status = 429 if error.status == 429 else 502
raise HTTPException(status, detail=error.code) from error
return {"message_id": result.message_id}
Run it with fastapi dev main.py (or uvicorn main:app --reload). EmailStr needs the email-validator package, which pip install 'fastapi[standard]' includes.
What each route shows:
/signupsends after responding.BackgroundTasksrunssend_welcomeonce the response has gone, so a slow network never slows sign-up. Becausesend_welcomeis a plaindef, FastAPI runs it in its threadpool. This is the right default for welcome mail and notifications./receipts/{order_id}waits for the result. It’s anasync defroute, so the blocking call goes throughrun_in_threadpool. Use this when the caller needs themessage_id, or needs to know the send failed. Theexceptturns the SDK’s error into an HTTP status for the caller, keeping the API’scodeas the detail.- A plain
defroute could also callclient().messages.send(...)directly, since FastAPI runs those in the threadpool too. Just don’t make a blocking call straight from anasync defroute, or every other request waits behind it.
For heavy or retried work, the same send_welcome function drops into a Celery, RQ or Dramatiq task unchanged.
Django: send email through send_mail without SMTP
Django sends mail through whatever EMAIL_BACKEND names, and it ships an SMTP backend that needs EMAIL_HOST, EMAIL_PORT, EMAIL_USE_TLS, EMAIL_HOST_USER and EMAIL_HOST_PASSWORD. Swap in a backend that calls the Mailcycle API, and every send_mail(), EmailMessage and EmailMultiAlternatives in your project, including Django’s own password-reset emails, sends over HTTPS instead. Nothing else in your code changes.
# myapp/mail_backend.py
import os
from collections.abc import Sequence
from email.utils import parseaddr
from typing import Any
from django.core.mail import EmailMessage, EmailMultiAlternatives
from django.core.mail.backends.base import BaseEmailBackend
from django.core.mail.message import EmailAttachment
from mailcycle import APIError, Mailcycle, OutgoingAttachment
class MailcycleBackend(BaseEmailBackend):
"""Sends Django mail through the Mailcycle API, one recipient per send."""
def __init__(self, fail_silently: bool = False, **kwargs: Any) -> None:
super().__init__(fail_silently=fail_silently, **kwargs)
self.client: Mailcycle | None = None
def open(self) -> bool:
if self.client is not None:
return False
self.client = Mailcycle.with_api_key(os.environ["MAILCYCLE_API_KEY"])
return True
def close(self) -> None:
if self.client is not None:
self.client.close()
self.client = None
def send_messages(self, email_messages: Sequence[EmailMessage]) -> int:
opened_here = self.open()
assert self.client is not None
sent = 0
try:
for message in email_messages:
sent += self._send(self.client, message)
finally:
if opened_here:
self.close()
return sent
def _send(self, client: Mailcycle, message: EmailMessage) -> int:
from_name, from_address = parseaddr(message.from_email) # "Acme <orders@...>" works too
html = None
if isinstance(message, EmailMultiAlternatives):
html = next((str(content) for content, mime in message.alternatives if mime == "text/html"), None)
files = []
for item in message.attachments:
if not isinstance(item, EmailAttachment):
continue # hand-built MIME parts are left out
content = item.content.encode() if isinstance(item.content, str) else item.content
if isinstance(content, bytes):
files.append(OutgoingAttachment(item.filename or "attachment", content, mime_type=item.mimetype))
sent = 0
for recipient in message.recipients(): # to, cc and bcc, each its own send
try:
client.messages.send(
from_address=from_address,
from_name=from_name or None,
to=recipient,
subject=str(message.subject),
text=str(message.body),
html=html,
attachments=files,
)
sent += 1
except APIError:
if not self.fail_silently:
raise
return sent
Then point Django at it:
# settings.py
EMAIL_BACKEND = "myapp.mail_backend.MailcycleBackend"
DEFAULT_FROM_EMAIL = "orders-x7k2@example-pool.email" # an address on your Mailcycle account
How it maps Django’s message onto the API:
- From.
parseaddrsplits"Acme <orders@…>"into a display name and an address, soDEFAULT_FROM_EMAILcan carry a name. The address must be on your account. - Recipients. Each send has one recipient, so the backend sends once per address in
to,ccandbcc, and returns how many went. Each recipient gets their own copy, and each counts as one send. - HTML.
send_mail(html_message=...)andattach_alternative(html, "text/html")both become thehtmlbody. - Files. Attachments added with
attach()orattach_file()are passed through as bytes.EmailAttachmentis the named tuple Django 5.2 and later use for them. fail_silently. Honoured the way Django’s own backends honour it.
Now an ordinary Django view sends through Mailcycle:
# myapp/views.py
from django.conf import settings
from django.core.mail import send_mail
from django.http import HttpRequest, JsonResponse
from django.views.decorators.http import require_POST
@require_POST
def resend_verification(request: HttpRequest) -> JsonResponse:
email = request.POST["email"]
code = "482913" # from your own verification flow
send_mail(
subject="Your Acme sign-in code",
message=f"Your code is {code}. It expires in 10 minutes.",
from_email=settings.DEFAULT_FROM_EMAIL,
recipient_list=[email],
html_message=f"<p>Your code is <strong>{code}</strong>. It expires in 10 minutes.</p>",
)
return JsonResponse({"sent": True})
A Django management command that sends email
For scheduled jobs, such as a daily digest run from cron, a management command can use the SDK directly. That way it gets the message_id and the error code:
# myapp/management/commands/send_digest.py
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from mailcycle import APIError
from mailer import client
class Command(BaseCommand):
help = "Email today's order digest to the operations inbox."
def add_arguments(self, parser):
parser.add_argument("to")
def handle(self, *args, **options):
try:
result = client().messages.send(
from_address=settings.DEFAULT_FROM_EMAIL,
to=options["to"],
subject="Order digest",
text="12 orders today, 0 refunds.",
)
except APIError as error:
raise CommandError(f"Mailcycle refused the send: {error.code}") from error
self.stdout.write(self.style.SUCCESS(f"Sent {result.message_id}"))
python manage.py send_digest ops@example.com
CommandError exits with a non-zero status, so cron, systemd or your CI notices when a send fails.
Receive the reply in Python
This is where Mailcycle differs from a send-only email API. The address you send from is a real inbox: when the customer hits Reply, their answer arrives at that address, and the same Python client reads it.
Mail is sealed the moment it arrives, with keys derived from your recovery phrase, so reading it needs the phrase on the machine that reads. That’s the phrase= argument in mailer.py. The phrase never leaves that machine: the client derives the keys locally and opens each message in your process. Without it, messages still list, but come back with opened=False and empty content rather than raising.
Wait for a reply
mc.messages.wait_for() blocks until a matching message arrives and returns it opened. Take the time before you send, and pass it as since, so a fast reply can’t slip in before the wait starts:
from datetime import datetime, timezone
from mailcycle import APIError
from mailer import FROM_ADDRESS, client
mc = client()
sent_at = datetime.now(timezone.utc) # take the time before sending
mc.messages.send(
from_address=FROM_ADDRESS,
to="customer@example.com",
subject="Can you confirm your delivery slot?",
text="Reply with a day that suits you.",
)
address = next(a for a in mc.addresses.list() if a.email_address == FROM_ADDRESS)
try:
reply = mc.messages.wait_for(
address_id=address.id,
from_address="customer@example.com",
since=sent_at,
timeout=600,
)
except APIError as error:
if error.code != "timeout":
raise
print("No reply in ten minutes.")
else:
print(reply.from_address, reply.subject)
print(reply.text)
for attachment in reply.attachments:
if attachment.stored:
data = mc.messages.attachment(reply, attachment.index)
print(attachment.filename, len(data), "bytes")
mc.messages.send(
from_address=FROM_ADDRESS,
to=reply.reply_to,
subject=f"Re: {reply.subject}",
text="Thanks, that slot is booked.",
reply_to=reply, # fills in inReplyTo and the Message-ID header
)
How the wait works:
- With the
eventsextra installed,wait_forlistens on the live event stream. Without it, it checks the address every five seconds. Either way you get the sameMessageback. from_addressandsubjectfilter by text the sender or subject contains, ignoring case.address_idlimits the wait to one address.- If nothing matches before
timeoutseconds, it raisesAPIErrorwithcode="timeout", which thetryabove handles.
This is also how to test email flows in pytest: create an address in a fixture, sign up with it in the app under test, and wait_for the verification email.
Blocking for ten minutes is fine in a script, a worker or a test. In a web request, it isn’t: use a webhook instead.
Read what’s in the inbox
To work through mail that has already arrived, iterate() pages through a folder for you:
from mailer import client
mc = client()
for message in mc.messages.iterate("ibx_k3v9x2mq7a"):
if not message.read:
print(message.received_at, message.from_address, message.subject)
mc.messages.mark_read(message.id)
Each Message is a frozen dataclass with the sender (from_address, from_name), reply_to, subject, text, html, safe_html, attachments and the original message_id. If you show a message’s HTML anywhere, render safe_html: it has remote images and trackers removed, the way the Mailcycle apps show mail, and message.blocked lists what was taken out. More in Reading mail.
Reply to an email in Python, in the same thread
The last call in the wait example is a threaded reply. Pass the received Message as reply_to= and the client sets two fields on the request:
inReplyTo, the Mailcycle id of the message you’re answering.inReplyToHeader, the original’sMessage-ID, so Gmail, Outlook and Apple Mail file your reply under the original conversation.
Send it to=reply.reply_to, not reply.from_address. reply_to is where the sender asked replies to go: the Reply-To header if they set one, and their From address otherwise. That’s the whole loop that support tools, booking confirmations and AI agents need: send, receive, answer in the thread, all from one address your code owns.
If the replier is an AI agent rather than your own code, Mailcycle also runs as an MCP server. See Give Claude Code its own email address and the AI agents guide.
Get replies pushed to your Python app
Polling doesn’t scale to a web app. Mailcycle offers two push options, and both carry ids, never content: your code fetches the message by id and opens it locally.
Webhooks call an HTTPS URL of yours when mail arrives. They are retried for about a day and a half if your server is down. Add one in the app under API, on the Webhooks tab, and store its whsec_ signing secret as MAILCYCLE_WEBHOOK_SECRET. Then add this route to the FastAPI app above:
def handle_reply(message_id: str) -> None:
message = client().messages.get(message_id) # opened here, with the phrase
print("reply from", message.from_address, ":", message.subject)
@app.post("/hooks/mailcycle", status_code=204)
async def mailcycle_webhook(
request: Request,
background: BackgroundTasks,
signature: Annotated[str | None, Header(alias="Mailcycle-Signature")] = None,
) -> None:
raw = await request.body() # the exact bytes, before any parsing
if not verify_webhook_signature(WEBHOOK_SECRET, raw, signature):
raise HTTPException(401)
event = json.loads(raw)
if event["type"] == "message.received":
background.add_task(handle_reply, event["payload"]["messageId"])
Check the signature against the raw body, before any JSON parsing, because a re-serialised body won’t match. verify_webhook_signature also refuses a timestamp more than five minutes old. Answer quickly, and do the fetch in a background task. Events can arrive more than once, so deduplicate on the Mailcycle-Event-Id header if handling one twice would matter. In Flask, read the raw body with request.get_data(). In Django, use request.body and request.headers["Mailcycle-Signature"]. The full event list is in Webhooks.
The event stream suits a worker that’s already running and has no public URL. It’s a WebSocket, and it needs pip install 'mailcycle[events]':
from mailer import client
mc = client()
with mc.events.stream() as events:
for event in events:
if event.type == "message.received":
message = mc.messages.get(event.payload["messageId"])
print(message.from_address, message.subject)
The stream reconnects after a drop, but events that happen while it’s down aren’t replayed. Pass on_reconnect= to refetch what you need, or use webhooks when every event matters. See Event stream.
Handle email errors in Python by error code
Everything the package raises is a subclass of MailcycleError. A failed API call is an APIError with three attributes:
status, the HTTP status. It is0when no answer came back, such as a network failure or await_fortimeout.code, the API’s stable, machine-readable code, likeplan_required. Match on this, never on the message.message, a human-readable explanation, fine for logs.
The codes you’ll meet when sending:
| Code | Status | What it means | What to do |
|---|---|---|---|
plan_required |
403 | Sending with an API key needs Scale or above. | Upgrade, or start the trial. |
not_your_address |
403 | from_address isn’t on this account. |
Fix the configured From address. |
invalid_address |
400 | The recipient isn’t a valid single address. | Validate input. Don’t retry. |
too_many_attachments, attachment_blocked |
400 | Over ten files, or a program or script file. | Change the message. |
attachments_too_large, message_too_large |
413 | The files or the whole message are too big. | Send a link instead. |
rate_limited |
429 | Too many requests in a short time. | Back off and retry. |
daily_send_limit |
429 | Today’s sends for the plan are used. | Sending resumes at 00:00 UTC. |
network_error |
0 | The request never got an answer. | Retry with backoff. |
internal, send_failed, provider_error |
5xx | A failure on our side or at a provider. | Retry with backoff. |
A 401 means the key is missing, wrong or revoked. The complete list is in Errors.
A retry helper that backs off on the temporary errors and gives up cleanly on the rest:
import logging
import random
import time
from mailcycle import APIError, SendResult
from mailer import FROM_ADDRESS, client
log = logging.getLogger(__name__)
RETRYABLE = {"rate_limited", "network_error", "internal", "send_failed", "provider_error",
"provider_unavailable", "storage_unavailable", "maintenance"}
def send_with_retry(to: str, subject: str, text: str, *, attempts: int = 4) -> SendResult | None:
for attempt in range(attempts):
try:
return client().messages.send(from_address=FROM_ADDRESS, to=to, subject=subject, text=text)
except APIError as error:
if error.code in RETRYABLE and attempt < attempts - 1:
delay = 2 ** attempt + random.random()
log.warning("send failed with %s, retrying in %.1fs", error.code, delay)
time.sleep(delay)
continue
if error.code == "daily_send_limit":
log.error("Today's sends are used up; sending resumes at 00:00 UTC.")
return None
if error.code in ("plan_required", "plan_capability_required"):
raise RuntimeError("Sending with an API key needs the Scale plan or above.") from error
if error.code == "not_your_address":
raise RuntimeError(f"{FROM_ADDRESS} is not an address on this account.") from error
raise # invalid_address, attachment_blocked, message_too_large and the rest
return None
The API sends a Retry-After header with a 429. The Python exception doesn’t expose it, so exponential backoff with a little jitter, as above, is the simple approach. The rate limits reference has the numbers, and mc.usage() returns what your account has used so far.
smtplib vs an email API: which should you use?
For comparison, here is the same HTML email with the standard library: smtplib for transport and email.message.EmailMessage to build the MIME message.
import os
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg["From"] = "orders@example.com"
msg["To"] = "customer@example.com"
msg["Subject"] = "Your order has shipped"
msg.set_content("Good news: order 1042 is on its way.")
msg.add_alternative("<p>Good news: order <b>1042</b> is on its way.</p>", subtype="html")
with smtplib.SMTP("smtp.example.com", 587) as smtp:
smtp.starttls()
smtp.login(os.environ["SMTP_USER"], os.environ["SMTP_PASSWORD"])
smtp.send_message(msg)
That’s good code, and EmailMessage is a pleasant API. What it needs around it is the SMTP side: a server that will relay your mail, an account on it, the right port (587 with STARTTLS, or 465 with smtplib.SMTP_SSL), and, with many providers, an app password or OAuth rather than your normal password. Django’s built-in backend needs the same five settings: EMAIL_HOST, EMAIL_PORT, EMAIL_USE_TLS, EMAIL_HOST_USER and EMAIL_HOST_PASSWORD.
smtplib + email.message |
Mailcycle Python SDK | |
|---|---|---|
| Install | Standard library | pip install mailcycle |
| What you configure | SMTP host, port, TLS mode, username, password | One API key in an environment variable |
| Transport | SMTP, ports 587 or 465 | HTTPS to api.mailcycle.email |
| HTML plus text | set_content() and add_alternative() |
text= and html= |
| Attachments | add_attachment() with MIME types |
OutgoingAttachment(name, bytes, mime_type=...) |
| Recipients per message | Many, with CC and BCC | One per send() call |
| Async | aiosmtplib, a separate package |
Sync client, wrapped with asyncio.to_thread |
| Errors | SMTPException subclasses and SMTP reply codes |
APIError with a stable code |
| Receiving replies | A separate mailbox, read with imaplib, with MIME parsing by hand |
Same address, same client: wait_for() and iterate() |
| Threading a reply | Set In-Reply-To and References yourself |
reply_to=message |
| Mail at rest | Depends on the mailbox provider | Sealed with keys from your recovery phrase |
Choose smtplib when you already have an SMTP relay you trust, you need many recipients in one message, or you can’t add dependencies. Choose an API client when you’d rather not configure SMTP, your app needs to read the replies, or you want the same address to work for both sending and receiving.
Send email from your own domain
Shared-domain addresses are fine for testing and internal mail. For customer-facing mail you’ll usually want orders@yourcompany.com. The Scale plan includes up to 10 of your own domains. You add a domain, prove you own it with a TXT record, and point its nameservers as the setup steps describe. After that, create addresses on it from Python with an exact name, using a client built with the phrase:
address = mc.addresses.create(domain="yourcompany.com", local_part="orders")
Until sending is switched on for a new domain, which usually follows receiving within minutes, sends from it return domain_not_sending. The steps are in Your own domains.
Production checklist
- Keep the API key in the environment. Never commit it, and never ship it inside software you distribute: anyone who extracts it can send as you. Revoke it in the app if it leaks.
- Treat the recovery phrase as the most sensitive secret you have. It opens your mail and can’t be reset. Give it only to processes that read mail. A service that only sends needs the API key alone.
- One client per process. Build it once, as in
mailer.py, and reuse it. - Don’t block requests. Send from background tasks or a queue, and learn about replies by webhook rather than waiting in a request.
- Store
message_id. It ties a support ticket or order to the exact email, and helps when a customer says they didn’t get it. - Send what people expect from you. Mailcycle is built for mail from addresses you own: receipts, sign-in codes, notifications, and replies from your app or agent. Each call sends to one recipient.
Next steps
- Read the full Python SDK guide for addresses, sessions, webhooks and device pairing.
- Start from the quickstart, and see authentication and API keys for what a key can and can’t do.
- Working in more than one language? The hub post shows how to send email from any language, with the same flow in TypeScript, Go, Ruby and PHP.
- See everything that’s on offer for developers on the developers page, and compare plans on pricing.
FAQ
How do I send an email using Python?
Install a client with pip install mailcycle, build it with Mailcycle.with_api_key(os.environ["MAILCYCLE_API_KEY"]), and call mc.messages.send() with from_address, to, subject and text. The from_address must be an address on your account. The call returns a SendResult with the Message-ID the mail went out with.
How do I send email in Python without an SMTP server?
Use an email API instead of smtplib. With Mailcycle, one HTTPS request sends the message, so there is no SMTP host, port, STARTTLS step or mailbox password to configure. Your code holds an API key, kept in an environment variable, and the Python client handles the request and the encoding of attachments.
Can I send email asynchronously in FastAPI?
Yes. The mailcycle client is synchronous, so in an async def route wrap the call with await run_in_threadpool(...) from fastapi.concurrency, or use asyncio.to_thread in plain asyncio code. A plain def route or a BackgroundTasks task already runs in FastAPI's threadpool, so it can call mc.messages.send() directly.
How do I send an email with an attachment in Python?
Pass attachments=[OutgoingAttachment(filename, data, mime_type=...)] to mc.messages.send(), where data is the file's raw bytes, for example Path("invoice.pdf").read_bytes(). The client base64-encodes them for you. Give an image a content_id to show it inline where your HTML says cid: and that id.
Can Django's send_mail work without an SMTP server?
Yes. Django picks its transport from EMAIL_BACKEND, so a small backend class that calls the Mailcycle API lets existing send_mail() and EmailMultiAlternatives code send over HTTPS with no SMTP settings. This tutorial includes a working backend you can drop into an app.
How do I receive email replies in Python?
Build the client with your recovery phrase as well as the API key, then call mc.messages.wait_for(address_id=..., since=...) to block until the reply arrives, or list the inbox with mc.messages.iterate(address_id). Replies come back already parsed and decrypted on your machine: sender, subject, text, safe HTML and attachments.
Which Mailcycle plan do I need to send email from Python?
Sending with an API key needs the Scale plan or above, and you can try it with the free 7-day Scale trial, with no card. A script signed in with the recovery phrase through Mailcycle.sign_in() can send from the Personal plan up. Free accounts receive mail only.
Is smtplib still a good way to send email in Python?
It is a solid, dependency-free choice when you already have an SMTP server and credentials, and it supports many recipients, CC and BCC in one message. An API client suits apps that would rather not run or configure SMTP, and want replies to arrive in the same inbox their code can read.
Is email sent through Mailcycle encrypted?
Sent mail passes through Mailcycle readable, so the recipient's server can read it, and it is not logged. The copy kept in your Sent folder, and every message you receive, is sealed with keys derived from your recovery phrase on your machine, so it is encrypted on arrival with your own keys. See Encryption.
Related
Send email from any language
- Send Email with an API: Code Examples in TypeScript, Python, C#, Go, Rust, PHP, Java, Ruby and Swift (Overview: every language)
- How to Send Email from C# and an ASP.NET Core Web API (C# / .NET)
- How to Send Email from Go (Golang): HTML Templates, a Mailer Package and an API (Go)
- How to Send Email from Java: A Plain Java Program, Spring Boot, HTML, Attachments and Replies (Java / Spring Boot)
- How to Send Email from PHP with an API (Laravel and Plain PHP) (PHP / Laravel)
- How to Send Email from Ruby and Rails with an Email API (Ruby / Rails)
- How to Send Email from Rust with an API: HTML, Attachments, Axum and Replies (Rust)
- How to Send Email From Swift: Vapor, iOS and Server-Side Swift (Swift / Vapor)
- How to Send Email from Node.js and TypeScript (Express and Next.js) (TypeScript / Node.js)