How to send email with Python

Send email from Python with the REST API and the standard library, or over SMTP with smtplib: attachments, safe retries, errors and delivery checks.

What you need

Send with the REST API

One POST to /v1/emails sends a message. Save this as send.py and run it with python3 send.py:

import json
import os
import urllib.error
import urllib.request

body = {
    "from": "Acme <receipts@acme.example>",
    "to": "jo@acme.example",
    "subject": "Your receipt",
    "text": "Thanks for your order.",
}
request = urllib.request.Request(
    "https://api.snd.email/v1/emails",
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={
        "Authorization": "Bearer " + os.environ["SND_API_KEY"],
        "Content-Type": "application/json",
        "Idempotency-Key": "order-8812-receipt",
    },
)
try:
    with urllib.request.urlopen(request, timeout=30) as response:
        result = json.load(response)
        print(response.status, result["id"], result["messages"])
except urllib.error.HTTPError as error:
    problem = json.load(error)
    print(error.code, problem["code"], problem["detail"])
    raise

The from address must be at a verified domain that the key may send from, as an address or as Name <address>. to is one address or a list; to, cc and bcc together hold at most 50 addresses. Give text, html or both.

The answer is 202 Accepted with the id of the request and one message per recipient, each with its own id. A message's status is queued, or suppressed when the address is on your suppression list and nothing is sent to it. urlopen raises HTTPError for any status of 400 or above; its body is the error.

The same request can carry cc, bcc, reply_to, up to 5 tags, up to 10 metadata keys and custom headers. Every field is in the reference.

Send over SMTP

If your app already sends mail with smtplib, point it at the SMTP relay instead. SMTP is off until an Owner turns it on: in the dashboard, open SMTP and press Activate.

import os
import smtplib
import ssl
from email.message import EmailMessage

msg = EmailMessage()
msg["From"] = "Acme <receipts@acme.example>"
msg["To"] = "jo@acme.example"
msg["Subject"] = "Your receipt"
msg.set_content("Thanks for your order.")

with smtplib.SMTP("smtp.snd.email", 587) as smtp:
    smtp.starttls(context=ssl.create_default_context())
    smtp.login("snd", os.environ["SND_API_KEY"])
    smtp.send_message(msg)

The username can be any value; the password is the API key. Port 587 switches to TLS with STARTTLS before it logs in; pass ssl.create_default_context() to starttls(), or smtplib does not check the server's certificate. Port 2525 works the same way where a host blocks 587; port 465 is TLS from the first byte, with smtplib.SMTP_SSL. Port 25 is not offered.

Send an EmailMessage with send_message(msg). sendmail(from, to, msg.as_bytes()) sends bare LF line endings, which are refused; with sendmail, pass msg.as_bytes(policy=email.policy.SMTP).

Add an attachment

Over the REST API a file goes in the attachments list with its name, its bytes as base64 and its media type. Use base64.b64encode, which writes no line breaks:

import base64

with open("invoice.pdf", "rb") as f:
    content = base64.b64encode(f.read()).decode("ascii")

body["attachments"] = [
    {"filename": "invoice.pdf", "content": content, "content_type": "application/pdf"},
]

The whole message is at most 10,000,000 bytes, headers and attachments included, with at most 100 files. Base64 makes a file about a third larger, so the largest file a message can carry is about 7.3 MB. A larger message is refused with 413 (payload_too_large), and a blocked file type, such as a program or an Office file with macros, with 422 (attachment_forbidden). Over SMTP, add the file with msg.add_attachment(data, maintype="application", subtype="pdf", filename="invoice.pdf").

Make retries safe

A timeout can leave you not knowing whether a message was accepted. The Idempotency-Key header makes a retry safe: send the same key with the same body again, and you get the first answer back, with the header Idempotent-Replayed: true, while nothing is sent twice. Take the key from your own data, such as the order the receipt is for.

Handle errors

Every error has a status of 400 or above and a body of type application/problem+json with type, title, status, code and detail. Act on code; each code has its own page:

StatusCodeWhat to do
400invalid_requestFix the field that errors[0].pointer names.
401unauthorizedCheck the key: it is missing, unknown, revoked or malformed.
403domain_out_of_scopeThe key may not send from the from domain: use a key for that domain.
422domain_not_verified, domain_declaration_requiredFinish the domain's setup in the dashboard.
429rate_limitedToo many requests at once: wait the seconds Retry-After names, at most a minute, then retry with the same Idempotency-Key.
429send_limit_reachedYour daily or monthly sending limit is used up. Do not retry: the daily limit starts again at 00:00 UTC, the monthly one on the first day of the month (UTC) on Free and with the plan's next monthly window on a paid plan; to raise it, contact support. With limit big_mail, large mail awaiting delivery fills its budget: retry after Retry-After.

A send that retries only what a retry can fix: rate_limited (by the problem's type), a server error and a network error. It waits as Retry-After asks but never more than 60 seconds, tries 3 times at most, and keeps the same Idempotency-Key. A daily or monthly send_limit_reached is final: its Retry-After can be weeks away; a big_mail one is retried.

import json
import os
import time
import urllib.error
import urllib.request

def send(body, idempotency_key, attempts=3):
    for attempt in range(1, attempts + 1):
        request = urllib.request.Request(
            "https://api.snd.email/v1/emails",
            data=json.dumps(body).encode("utf-8"),
            method="POST",
            headers={
                "Authorization": "Bearer " + os.environ["SND_API_KEY"],
                "Content-Type": "application/json",
                "Idempotency-Key": idempotency_key,
            },
        )
        try:
            with urllib.request.urlopen(request, timeout=30) as response:
                return json.load(response)
        except urllib.error.HTTPError as error:
            try:
                problem = json.load(error)
            except ValueError:
                problem = {}
            retry = (error.code >= 500 or str(problem.get("type")).endswith("/errors/rate_limited")
                     or problem.get("limit") == "big_mail")
            if not retry or attempt == attempts:
                # Final: a daily or monthly send_limit_reached starts again at 00:00 UTC or with the next monthly window.
                raise RuntimeError("%s %s: %s" % (error.code, problem.get("code"), problem.get("detail")))
            try:
                wait = int(error.headers.get("Retry-After", "1"))
            except ValueError:
                wait = 1
        except OSError:
            # A network error: no connection, a dropped one or a read timeout (URLError is one too).
            if attempt == attempts:
                raise
            wait = 1
        time.sleep(max(1, min(wait, 60)))

result = send(
    {"from": "Acme <receipts@acme.example>", "to": "jo@acme.example", "subject": "Your receipt", "text": "Thanks for your order."},
    "order-8812-receipt",
)
print(result["id"])

All codes are in the error list.

Check delivery

GET /v1/emails/{id} with a message id returns its status and its newest 200 events. It needs a key with the emails:read scope:

message_id = "1b9e4f7a-3c2d-4e5f-8a6b-7c9d0e1f2a3b"
request = urllib.request.Request(
    "https://api.snd.email/v1/emails/" + message_id,
    headers={"Authorization": "Bearer " + os.environ["SND_READ_KEY"]},
)
with urllib.request.urlopen(request, timeout=30) as response:
    message = json.load(response)
print(message["status"], [event["type"] for event in message["events"]])

Rather than asking, let us tell you: a webhook sends each delivery, bounce, open or click to your endpoint as a signed request.

Troubleshooting

More on the API: the email API and the quick start.