Python SDK

Python SDK

Install the Mailset Python SDK, send email, verify webhooks and handle errors, with examples that run.

  • Every public command238 commands, each a typed method
  • Typed throughoutTypedDicts throughout, checked by mypy
  • Sync and asyncMailset and AsyncMailset
  • Retries built inTwo more tries, and a send never doubles
  • Timeouts per try30 seconds a try, then tried again
  • Idempotency keysA send repeated with its key goes once
On this page
  1. Requirements
  2. Install
  3. Create a client
  4. Send
  5. Send many
  6. Promotional email
  7. Idempotency
  8. Check the key
  9. Delivery search
  10. Webhooks
  11. Errors
  12. Build the message yourself
  13. Names
  14. Version and licence

Requirements

Runs onPython 3.9+httpx 0.23+cryptography 3.4+typing_extensions 4.7+

Install

Add the SDK to your project.

pip install mailset

Create a client

One client holds one MAILSET_KEY. Make it when your server starts and use it for every call.

Pass the key in

Where your app keeps its secrets elsewhere, hand the key to the client yourself. A token goes the same way.

Options

Everything has a default. Name a credential, an org, how long a try may take and how often a call is tried again, only where yours differ.

Authentication

Python
from mailset import Mailset

# One client for the whole server, from MAILSET_KEY.
# Nothing is sent until you call send.
mailset = Mailset()
Pass the key in
from mailset import Mailset

# From your secret store or config, never in the code.
# Or token= with an API token.
mailset = Mailset(key=settings.mailset_key)
Options
import os

from mailset import Approval, Mailset


def approve(approval: Approval) -> None:
    url = approval["url"]
    print(f"Approve it with your passkey: {url}")


mailset = Mailset(
    # Or token=os.environ["MAILSET_TOKEN"].
    key=os.environ["MAILSET_KEY"],
    # The org commands are about, for a person in
    # more than one.
    org="org_7c2e9a4f",
    # Each try may take 10 seconds. A network failure,
    # a timeout or a 5xx is tried 3 more times,

Send

Send one message and get its receipt. A message Mailset refuses is an error with a code, never a silent drop.

Give sign-in codes a deadlineHonor unsubscribes and complaintsHandle skipped recipientsGuide for Python

Python
from mailset import Mailset

# Reads MAILSET_KEY from the environment.
mailset = Mailset()

sent = mailset.send(
    {
        "from": "Acme <moc.elpmaxe@olleh>",
        "to": "gro.elpmaxe@ana",
        "subject": "Your Acme code",
        "text": "Your code is 123456.",
        "html": "<p>Your code is <b>123456</b>.</p>",
        "deliver_by": "10m",
    }
)

print(sent["id"], sent["status"])

Send many

Send several messages in one call and get one result per message, in the same order. A refused message never stops the rest.

Send many messages at once

Python
from mailset import Mailset

# Reads MAILSET_KEY from the environment.
mailset = Mailset()

results = mailset.send(
    [
        {
            "from": "Acme <moc.elpmaxe@olleh>",
            "to": "gro.elpmaxe@ana",
            "subject": "Your invoice",
            "text": "Invoice 8842 is ready.",
        },
        {
            "from": "Acme <moc.elpmaxe@olleh>",
            "to": "gro.elpmaxe@neb",
            "subject": "Your invoice",
            "text": "Invoice 8843 is ready.",
        },
    ]
)

for result in results:
    if result["ok"]:
        print(result["id"], result["status"])
    else:
        print(result["message_id"], result["error"].code)

Promotional email

Send a newsletter or an offer with mode: 'promotional'. {{mailset_unsubscribe}} is a placeholder Mailset fills in for each message, with a signed one-click unsubscribe link unique to that recipient and that message. You never generate the link, and Mailset adds the matching List-Unsubscribe and List-Unsubscribe-Post headers itself.

Honor unsubscribes and complaintsHandle skipped recipients

Python
from mailset import Mailset

# Reads MAILSET_KEY from the environment.
mailset = Mailset()

text = (
    "Three new things this month.\n"
    "\n"
    "Leave this list: {{mailset_unsubscribe}}"
)
html = (
    "<p>Three new things this month.</p>\n"
    '<a href="{{mailset_unsubscribe}}">'
    "Leave this list</a>"
)
What Ana receives
Headers Mailset adds
List-Unsubscribe: <https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc>
List-Unsubscribe-Post: List-Unsubscribe=One-Click
Text part
Three new things this month.

Leave this list: https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc
HTML part

Three new things this month.

Leave this list

A sample link. Mailset makes a new one for every message.

What Ana receives without the placeholder
Text part
Three new things this month.

Unsubscribe: https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc
HTML part

Three new things this month.

Unsubscribe

Mailset adds the last line of each part. The headers are the same.

Idempotency

Name a send with idempotency_key, and sending it again after a timeout or a crash can’t send it twice.

Retry without sending twice

Python
from mailset import Mailset, SendInput

# Reads MAILSET_KEY from the environment.
mailset = Mailset()

receipt: SendInput = {
    "from": "Acme <moc.elpmaxe@olleh>",
    "to": "gro.elpmaxe@ana",
    "subject": "Your receipt",
    "text": "Thanks for your order.",
    "idempotency_key": "receipt-8842",
}

first = mailset.send(receipt)
# After a timeout or a crash, send it again.
# The same key answers the first receipt,
# and nothing goes out twice.
again = mailset.send(receipt)

print(first["id"] == again["id"])

Check the key

Ask what the key may do now. Call it when your server starts and once a day: each call keeps the key alive.

Keep a key alive

Python
from datetime import datetime, timezone

from mailset import Mailset

# Reads MAILSET_KEY from the environment.
mailset = Mailset()

# When the server starts, and once a day.
status = mailset.key.check()

if status["paused"]:
    print("Paused:", status["paused"])
ends = status["expires_at"] / 1000
until = datetime.fromtimestamp(ends, timezone.utc)
print("Works until", until)
# A mailbox key sends as its mailbox.
for box in status["mailboxes"]:
    if box["sending"] != "ready":

Delivery search

Look up what became of the mail this key sent, one line per recipient. For a support question or a nightly check.

Handle bounces

Python
from datetime import date

from mailset import Mailset

# Reads MAILSET_KEY from the environment.
mailset = Mailset()

# Did Ana get her receipt?
page = mailset.delivery.search(
    {
        "recipient": "gro.elpmaxe@ana",
        "since": date(2026, 11, 30),
    }
)

for line in page["lines"]:
    print(line["status"], line["reason"])
# Pass "next" back as "cursor" for the page after.
print(page["next"])

Webhooks

Check that a request came from Mailset and read its events. It needs no key and no client, so a service that only receives events uses it alone.

In a web framework

The signature covers the body exactly as it arrived. Read the raw body before anything parses it, and hand that to the check: a body parsed as JSON and written out again no longer matches.

WebhooksHandle bouncesGuide for FastAPIGuide for DjangoGuide for Flask

Python
import os
from typing import Mapping

from mailset import MailsetError, webhooks

SECRET = os.environ["MAILSET_HOOK_SECRET"]


def handle(
    body: bytes, headers: Mapping[str, str]
) -> int:
    """Your hook's endpoint: the body as it came,
    and its headers. Answers the HTTP status."""
    try:
        events = webhooks.verify(body, headers, SECRET)
    except MailsetError as error:
        print(error.code)
        return 401
    for event in events:
        if event["type"] != "bounced":
            continue
        if event["bounce"]["kind"] == "hard":
            print("Stop writing to", event["recipient"])
    # 2xx once the events are kept.
    # Until then Mailset posts the batch again.
    return 204
In a web framework
# A FastAPI endpoint for your hook.
import os

from fastapi import FastAPI, Request, Response

from mailset import MailsetError, webhooks

app = FastAPI()
SECRET = os.environ["MAILSET_HOOK_SECRET"]


@app.post("/mailset/events")
async def mailset_events(request: Request) -> Response:
    # The signature covers the body as it came: read
    # its bytes. A pydantic body or request.json()
    # loses what it was made over.
    body = await request.body()
    headers = request.headers

Errors

Every refusal is one kind of error. Branch on its code, which never changes, and show its message to people.

Retries and timeouts

A network failure or a 5xx answer is tried again, twice unless you set max_retries, waiting longer each time. One try may take 30 seconds unless you set timeout. A refusal is never tried again: the same request gets the same answer.

Errors and limits

Python
from datetime import datetime, timezone

from mailset import Mailset, MailsetError, RateLimitError

# Reads MAILSET_KEY from the environment.
mailset = Mailset()

try:
    mailset.send(
        {
            "from": "Acme <moc.elpmaxe@olleh>",
            "to": "gro.elpmaxe@ana",
            "subject": "Your Acme code",
            "text": "Your code is 123456.",
            "deliver_by": "10m",
        }
    )
except RateLimitError as error:

Build the message yourself

Get the message a send would build, without sending it: for a queue of your own, or a call to the API from another service.

messages.submit

Python
import base64

from mailset import build_message

built = build_message(
    {
        "from": "Acme <moc.elpmaxe@olleh>",
        "to": "gro.elpmaxe@ana",
        "subject": "Your Acme code",
        "text": "Your code is 123456.",
    }
)

# The `data` that messages.submit takes.
data = base64.b64encode(built["raw"]).decode()

print(built["message_id"], len(data))

Names

A field keeps its name in every SDK, in each language’s own case. The commands write idempotencyKey, and Python writes idempotency_key.

A method is named for its command. Python can’t spell these, so each has a name that says what it does:

CommandIn PythonWhy
contacts.importimport_contactsimport is a hard keyword in Python: contacts.import(…) doesn’t parse.
rules.importimport_rulesimport is a hard keyword in Python.

Version and licence

This page is for version 0.7.0 of the Python SDK.

You may use the SDK and change it in your own apps and services, to call Mailset. You may not publish it or pass it on, by itself or inside another library.

Something missing, or not working as this page says? Ask us.