Skip to content

Python quickstart

Use HTTP with requests, or SMTP with Python’s standard library.

  1. A Comail account with an enrolled, DNS-verified sending domain. Sign up if you need an account.
  2. Your account ID (DID) and an API key for your sending domain. Open API keys in the Builders console to create a key. Save it when it appears. To replace a lost key, follow the API key guide.
  3. Python 3.8 or newer (python3 --version).
  4. A real recipient address you can check. Replace example.com in the examples below; the relay rejects IANA example domains with 422 INVALID_RECIPIENT_DOMAIN on HTTP and 556 5.1.10 on SMTP.

Install requests:

Terminal window
pip install requests

Save as send.py:

import os
import sys
import requests
DID = os.environ["COMAIL_DID"]
API_KEY = os.environ["COMAIL_API_KEY"]
resp = requests.post(
"https://smtp.atmos.email/v1/send",
headers={
"X-Atmos-DID": DID,
"Authorization": f"Bearer {API_KEY}",
},
json={
"from": "you@yourdomain.com",
"to": "alice@example.com",
"subject": "Hello from comail",
"text": "If you can read this, the API key works.",
},
timeout=15,
)
try:
result = resp.json()
except ValueError:
print(f"send failed: expected JSON, got HTTP {resp.status_code}", file=sys.stderr)
sys.exit(1)
if not resp.ok:
if result.get("rejected"):
print(f"send failed: HTTP {resp.status_code}", file=sys.stderr)
for r in result["rejected"]:
print(f" {r['recipient']}: {r['error']}", file=sys.stderr)
else:
code = result.get("code", "UNKNOWN")
message = result.get("error", "no error details")
print(f"send failed: {resp.status_code} {code}: {message}", file=sys.stderr)
sys.exit(1)
print(f"accepted: {len(result['accepted'])}")
print(f"rejected: {len(result.get('rejected', []))}")
for r in result["accepted"]:
print(f" -> {r['recipient']} (messageId: {r['messageId']})")

In send.py, replace you@yourdomain.com with your sending address and alice@example.com with your own recipient address. Set your DID and API key in the shell, then run the example.

Terminal window
export COMAIL_DID=did:plc:your-did-here
export COMAIL_API_KEY=atmos_your-api-key
python3 send.py

Expected output when the relay accepts the message:

accepted: 1
rejected: 0
-> alice@example.com (messageId: 12345)

Look for your recipient and a messageId in accepted. This means the relay has queued the message. Check your account or the Events API for delivery status. If the domain is in its first 14 days of sending, check the spam folder too.

smtplib and email ship in the Python standard library, so no package install is needed.

Replace you@yourdomain.com and alice@example.com with your enrolled sender address and a real recipient address, and run with COMAIL_DID and COMAIL_API_KEY set in your environment:

import os
import smtplib
import ssl
from email.message import EmailMessage
# Pass username and password as separate arguments to login().
# Do not embed a DID in a URL because URL parsers split on the ":" in did:plc:...
DID = os.environ["COMAIL_DID"]
API_KEY = os.environ["COMAIL_API_KEY"]
msg = EmailMessage()
msg["From"] = "you@yourdomain.com"
msg["To"] = "alice@example.com"
msg["Subject"] = "Hello from comail (SMTP)"
msg.set_content("If you can read this, SMTP submission works.")
with smtplib.SMTP("smtp.atmos.email", 587, timeout=15) as server:
server.starttls(context=ssl.create_default_context())
server.login(DID, API_KEY)
server.send_message(msg)
print("sent")

The example prints sent when the relay accepts the message for delivery.

Details for the SMTP path:

  • Use port 587 with STARTTLS. Port 465 (implicit TLS) is not available.
  • smtplib negotiates SASL PLAIN automatically when you call login() after starttls().
  • The username for login() can be either your DID (did:plc:…) or your enrolled sending domain (yourdomain.com). If a library or URL config cannot handle colons in a username, use the sending domain.

For a project where you send from multiple places, read COMAIL_DID and COMAIL_API_KEY from the environment once:

comail.py
import os
import requests
class ComailError(Exception):
def __init__(self, status, code, message, rejected=None):
super().__init__(f"{code}: {message}")
self.status = status
self.code = code
self.rejected = rejected or []
_DID = os.environ.get("COMAIL_DID")
_KEY = os.environ.get("COMAIL_API_KEY")
if not (_DID and _KEY):
raise RuntimeError("Set COMAIL_DID and COMAIL_API_KEY in the environment.")
_SESSION = requests.Session()
_SESSION.headers.update({
"X-Atmos-DID": _DID,
"Authorization": f"Bearer {_KEY}",
})
def send(*, sender, to, subject, text=None, html=None, reply_to=None,
category=None, headers=None, timeout=15):
"""Send via comail. Returns the parsed JSON response on success;
raises ComailError on a 4xx/5xx.
`sender` is the From: address (not `from` because Python keyword).
`to` may be a string or a list, up to 50 recipients.
"""
body = {
"from": sender,
"to": to,
"subject": subject,
}
if text is not None:
body["text"] = text
if html is not None:
body["html"] = html
if reply_to is not None:
body["replyTo"] = reply_to
if category is not None:
body["category"] = category
if headers:
body["headers"] = headers
resp = _SESSION.post(
"https://smtp.atmos.email/v1/send",
json=body,
timeout=timeout,
)
try:
result = resp.json()
except ValueError as exc:
raise ComailError(resp.status_code, "UNKNOWN", "expected a JSON response") from exc
if not resp.ok:
rejected = result.get("rejected", [])
fallback = "all recipients rejected" if rejected else "no error details"
message = result.get("error", fallback)
raise ComailError(resp.status_code, result.get("code", "UNKNOWN"), message, rejected)
return result

Usage:

from comail import send, ComailError
try:
result = send(
sender="auth@yourdomain.com",
to=["alice@example.com", "bob@example.com"],
subject="Sign-in link",
text="https://your-app.com/auth?token=abc123",
category="login-link",
)
print(f"accepted: {len(result['accepted'])}, rejected: {len(result.get('rejected', []))}")
except ComailError as e:
if e.code == "RATE_LIMITED":
# back off and retry
pass
elif e.code in ("SUSPENDED", "PENDING"):
# account-level issue; check /account
pass
else:
raise

See HTTP Send API for the full error code table.

to accepts a list of up to 50 addresses. In a multi-recipient request, an HTTP 200 response lists the queued recipients in accepted. It includes rejected only when at least one address failed. If every recipient fails and the response has a list of failures, the helper puts that list on the ComailError as rejected.

Check each rejection before retrying. Send again only to addresses that failed temporarily.

result = send(
sender="news@yourdomain.com",
to=["alice@example.com", "bob@example.com"],
subject="Acme weekly",
html="<p>Latest updates...</p>",
category="bulk",
)
for r in result["accepted"]:
print(f"OK {r['recipient']}: {r['messageId']}")
for r in result.get("rejected", []):
print(f"ERR {r['recipient']}: {r['error']}")

Both frameworks include SMTP backends. Point them at smtp.atmos.email:587 and load your API key from the environment:

# Django settings.py
import os
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.atmos.email"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = "yourdomain.com" # your enrolled domain (or COMAIL_DID)
EMAIL_HOST_PASSWORD = os.environ["COMAIL_API_KEY"]
DEFAULT_FROM_EMAIL = "you@yourdomain.com"
# Flask-Mail config
import os
MAIL_SERVER = "smtp.atmos.email"
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = "yourdomain.com" # your enrolled domain (or COMAIL_DID)
MAIL_PASSWORD = os.environ["COMAIL_API_KEY"]

Without an X-Atmos-Category header, SMTP messages are treated as untagged: the relay enforces the suppression list and does not add List-Unsubscribe headers. Set X-Atmos-Category per message through the framework’s custom headers option; see Message categories.

Back to docs