Python SDK
The sendfern package is the official client for Python. It covers every resource in the API, retries safely, and verifies webhook signatures.
Requirements
- Python 3.10 or later.
- No dependencies: it uses only the standard library.
- Fully typed. The package ships a
py.typedmarker, so mypy and Pyright read its annotations. - The client is synchronous. Responses are plain dicts with the API's field names.
Install
pip install sendfern # or uv add sendfern # or poetry add sendfern
Configure the client
Create one client and reuse it. The first argument is your API key. Leave it out and the client reads SENDFERN_API_KEY; with neither, the constructor raises ValueError.
from sendfern import Sendfern
# Reads SENDFERN_API_KEY when you leave the key out.
sendfern = Sendfern()
# Or pass everything yourself.
custom = Sendfern(
"sk_live_...",
base_url="https://api.sendfern.com",
timeout=10,
max_retries=3,
)Arguments
api_keystr | None- Your
sk_live_orsk_test_key. Defaults toSENDFERN_API_KEY. base_urlstr | None- The API address. Defaults to
SENDFERN_BASE_URL, thenhttps://api.sendfern.com. A trailing slash is removed. timeoutfloat- Time limit for each attempt, in seconds. Keyword only. Default 30.
max_retriesint- Retries after the first attempt. Keyword only. Default 2, so a call makes at most 3 attempts. See Retries.
A test key (sk_test_) accepts the same calls but sends nothing. Domains, templates, audiences, contacts, webhooks and suppressions are shared between modes, and a test key can read them but not change them: creating, updating or deleting one with a test key fails with 403 permission_denied. A send-only key can call only emails.send and emails.batch. See Authentication.
Send an email
import os
from sendfern import Sendfern
sendfern = Sendfern(os.environ["SENDFERN_API_KEY"])
email = sendfern.emails.send(
from_="Acme <onboarding@acme.com>", # from is a Python keyword
to="user@example.com",
subject="Welcome to Acme",
html="<p>Thanks for signing up.</p>",
text="Thanks for signing up.",
)
print(email["id"]) # em_...You get the email object back at once, with status queued; sending happens in the background. The From address must be on a verified domain when you use a live key. Every field is described in Send an email.
Resources
Each resource is an attribute of the client. Methods take the API's field names as keyword arguments, with from_ for from on emails.send and broadcasts.create. They return the response as a dict, and a remove or revoke returns None. List methods take the API's query parameters as keyword arguments. For every field of every object, see the API reference.
Emails
from datetime import datetime, timezone
# Send up to 100 emails in one request. Nothing is queued if any item is invalid.
result = sendfern.emails.batch([
{"from": "Acme <hello@acme.com>", "to": "a@example.com", "subject": "Hi", "text": "Hello"},
{"from": "Acme <hello@acme.com>", "to": "b@example.com", "subject": "Hi", "text": "Hello"},
])
print([e["id"] for e in result["data"]])
# Schedule one for later, then change your mind. A datetime is sent as ISO 8601.
later = sendfern.emails.send(
from_="Acme <hello@acme.com>",
to="user@example.com",
subject="Your trial ends tomorrow",
text="Upgrade any time.",
scheduled_at=datetime(2026, 12, 1, 9, 0, tzinfo=timezone.utc),
)
sendfern.emails.cancel(later["id"])
# Read one with its body and timeline, list with filters, send a copy.
email = sendfern.emails.get("em_VNqV5JEIqYYeYbZRhbPrJ6")
bounced = sendfern.emails.list(status="bounced", limit=50)
copy = sendfern.emails.resend("em_VNqV5JEIqYYeYbZRhbPrJ6")| Method | What it does |
|---|---|
emails.send(idempotency_key=None, **email) | Send one email. |
emails.batch(emails, idempotency_key=None) | Send 1 to 100 emails (a list of dicts) in one request. Each dict may use from or from_. Returns {"data": [...]}. |
emails.get(id) | One email with html, text, body_cleared_at and its events. |
emails.list(**params) | Filters: status, to, tag (name:value), broadcast_id, created_after, created_before, q (subject contains), limit. |
emails.cancel(id) | Cancel a scheduled email. |
emails.resend(id) | Send a new copy now, with a new id. Not for broadcast emails. |
Domains
domain = sendfern.domains.create(name="acme.com")
for r in domain["records"]:
print(r["type"], r["name"], r["value"])
# After you add the DNS records:
checked = sendfern.domains.verify(domain["id"])
print(checked["status"]) # "pending", "verified" or "failed"
sendfern.domains.update(domain["id"], track_opens=False, tracking_domain="links.acme.com")| Method | What it does |
|---|---|
domains.create(name=...) | Add a domain. The response lists the DNS records to create. |
domains.list(**params) | All domains. |
domains.get(id) | One domain. |
domains.verify(id) | Check the DNS records now and return the updated domain. |
domains.update(id, **tracking) | Change track_opens, track_clicks or tracking_domain. |
domains.remove(id) | Delete the domain. |
See Domains and DNS and Open and click tracking.
Templates
template = sendfern.templates.create(
name="Welcome",
subject="Welcome, {{ first_name }}",
html='<p>Hi {{ first_name }}, <a href="{{ action_url }}">finish setting up</a>.</p>',
)
# Preview with sample values. Missing variables are left as written.
preview = sendfern.templates.render(template["id"], {"first_name": "Jane"})
# Send with it: no subject, html or text.
sendfern.emails.send(
from_="Acme <hello@acme.com>",
to="user@example.com",
template_id="tpl_...",
variables={"first_name": "Jane", "action_url": "https://acme.com/setup"},
)| Method | What it does |
|---|---|
templates.create(**template) | name, subject, and html or text. The response lists its variables. |
templates.list(**params) | All templates. |
templates.get(id) | One template. |
templates.update(id, **template) | Change any of name, subject, html, text. |
templates.remove(id) | Delete it. Emails already created from it don't change. |
templates.render(id, variables=None) | Returns subject, html and text for a preview. |
When you send with template_id, every variable the template uses must be in variables, or the send fails with 400. See Templates.
Audiences and contacts
audience = sendfern.audiences.create(name="Newsletter") # Upsert by email: creates the contact or updates the one with that address. sendfern.contacts.upsert(audience["id"], email="user@example.com", first_name="Jane") unsubscribed = sendfern.contacts.list(audience["id"], status="unsubscribed")
| Method | What it does |
|---|---|
audiences.create(name=...) | Create an audience. |
audiences.list(**params) | All audiences, with contact_count and subscribed_count. |
audiences.get(id) | One audience. |
audiences.update(id, **audience) | Rename it (name). |
audiences.remove(id) | Delete it and its contacts. Fails if a broadcast uses it. |
contacts.upsert(audience_id, **contact) | Create or update by email, with first_name, last_name, unsubscribed. |
contacts.list(audience_id, **params) | Filters: email (contains), status (subscribed or unsubscribed), limit. |
contacts.get(id) | One contact. |
contacts.update(id, **contact) | Change names or unsubscribed. |
contacts.remove(id) | Delete the contact. |
The SDK has no method for CSV import; use the dashboard or the API. See Audiences and contacts.
Broadcasts
from datetime import datetime, timezone
broadcast = sendfern.broadcasts.create(
name="December update",
audience_id="aud_...",
from_="Acme <news@acme.com>",
subject="What's coming in December",
html='<p>Hi {{first_name}}, here is a first look.</p><p><a href="{{unsubscribe_url}}">Unsubscribe</a></p>',
text="Hi {{first_name}}, here is a first look.\n\nUnsubscribe: {{unsubscribe_url}}",
)
result = sendfern.broadcasts.checks(broadcast["id"])
for check in result["checks"]:
print(check["id"], check["ok"], check["level"])
sendfern.broadcasts.test(broadcast["id"], "me@acme.com")
# Send now, or pass scheduled_at (a datetime or an ISO string, up to 30 days ahead).
sendfern.broadcasts.send(broadcast["id"], scheduled_at=datetime(2026, 12, 1, 9, 0, tzinfo=timezone.utc))
sendfern.broadcasts.cancel(broadcast["id"]) # back to draft| Method | What it does |
|---|---|
broadcasts.create(**broadcast) | name, audience_id, from_, subject, html and text (or blocks), optional reply_to and preview_text. |
broadcasts.list(**params) | Filters: status, audience_id, q, limit. |
broadcasts.get(id) | One broadcast, with stats. |
broadcasts.update(id, **broadcast) | Edit a draft. |
broadcasts.remove(id) | Delete it. |
broadcasts.checks(id) | The before-you-send checks and the recipient count. |
broadcasts.test(id, to) | Send one test copy to an address. |
broadcasts.send(id, scheduled_at=None) | Send now, or schedule up to 30 days ahead. |
broadcasts.cancel(id) | Unschedule. The broadcast goes back to draft. |
Sending is refused while an error-level check fails, for example a missing plain-text version. See Broadcasts.
Suppressions
sendfern.suppressions.create("user@example.com")
page = sendfern.suppressions.list(email="user@example.com")
if page["data"]:
sendfern.suppressions.remove(page["data"][0]["id"])| Method | What it does |
|---|---|
suppressions.create(email) | Stop sending to an address. |
suppressions.list(**params) | Filter with email. |
suppressions.remove(id) | Allow the address again. |
Webhooks
endpoint = sendfern.webhooks.create(
url="https://acme.com/webhooks/sendfern",
events=["email.delivered", "email.bounced", "email.complained"],
)
print(endpoint["secret"]) # whsec_..., returned only now
sendfern.webhooks.test(endpoint["id"])
deliveries = sendfern.webhooks.deliveries(endpoint["id"], limit=10)
sendfern.webhooks.retry(endpoint["id"], deliveries["data"][0]["id"])| Method | What it does |
|---|---|
webhooks.create(**webhook) | Add an endpoint: url, optional events and enabled. No events means all. The secret is in this response only. |
webhooks.list(**params) | All endpoints. |
webhooks.get(id) | One endpoint. |
webhooks.update(id, **webhook) | Change url, events or enabled. |
webhooks.remove(id) | Delete the endpoint. |
webhooks.deliveries(id, **params) | The delivery log, newest first. |
webhooks.test(id) | Send a sample email.delivered event now. |
webhooks.retry(id, delivery_id) | Try a failed delivery once more. |
API keys
keys = sendfern.api_keys.list()
sendfern.api_keys.revoke("key_...")| Method | What it does |
|---|---|
api_keys.list(**params) | Your keys, without their secrets. |
api_keys.revoke(id) | Revoke a key. It stops working at once. A key cannot revoke itself. |
You create keys in the dashboard; the API does not create keys with an API key.
Stats and usage
These two are methods on the client itself, not resources. Because from is a keyword, pass the start of the date range as from_, as you do when sending.
# "from" is a Python keyword, so pass the date range as a dict. stats = sendfern.stats(from_="2026-11-01", to="2026-11-25", tag="type:welcome") print(stats["totals"]["delivery_rate"]) usage = sendfern.usage() print(usage["used"], "of", usage["quota"] or "unlimited", "this month")
| Method | What it does |
|---|---|
stats(**params) | Totals and a daily series. Params: from_, to (UTC dates, at most 90 days), interval, broadcast_id, tag. |
usage() | Live emails this calendar month: period_start, period_end, used, quota. |
Other endpoints
sendfern.request(method, path, body=None) calls any endpoint with the same authentication, retries and errors.
# Any endpoint, with the same auth, retries and errors.
page = sendfern.request("GET", "/v1/emails?status=delivered&limit=5")Idempotency keys
Pass idempotency_key to emails.send or emails.batch. If the same key arrives again with the same body within 24 hours, the API returns the first response instead of sending again. The same key with a different body is a 409. Use something that identifies the action, like an order id.
sendfern.emails.send(
from_="Acme <hello@acme.com>",
to="user@example.com",
subject="Your receipt",
html="<p>Thanks for your order.</p>",
idempotency_key=f"receipt-{order.id}",
)A key also lets the SDK retry a send after a server or network error. See Idempotency.
Pagination
List methods return one page: a dict with data, has_more and next, newest first, 20 items by default and up to 100 with limit. paginate takes a list method and its filters, yields every item of every page, and keeps your filters.
from functools import partial
# Every bounced email, page after page.
for email in sendfern.paginate(sendfern.emails.list, status="bounced", limit=100):
print(email["to"])
# Lists that take an id first: bind it with partial.
for contact in sendfern.paginate(partial(sendfern.contacts.list, "aud_...")):
print(contact["email"])Errors
A failed call raises SendfernError. It carries the API's error object and the HTTP status.
statusint- The HTTP status.
0when Sendfern could not be reached (network error or timeout). typestr- For example
invalid_request_errororrate_limit_error. codestr- For example
invalid_parameter,domain_not_verified, ornetwork_errorwhen status is 0. paramstr | None- The request field the error is about, when there is one.
messagestr- A sentence you can log or show to a developer.
from sendfern import SendfernError
try:
sendfern.emails.send(from_="Acme <hello@acme.com>", to="not-an-address", subject="Hi", text="Hello")
except SendfernError as err:
print(err.status, err.type, err.code, err.param, err.message)
# 400 invalid_request_error invalid_parameter to 'not-an-address' is not a valid email address.The full list of types and codes is in Errors.
Retries
The SDK retries a failed attempt up to max_retries times (default 2):
- 429 Too Many Requests is retried for every method, because the request was not processed.
- 5xx responses, network errors and timeouts are retried only when a repeat is safe: for every method except POST (GET, PATCH and DELETE), and for a POST that has an
idempotency_key.
Before a retry the SDK waits for the number of seconds in the Retry-After header when the response has one. Otherwise it backs off: about 0.5 s, then 1 s, doubling up to 8 s, with random jitter. When the retries run out, the last error is raised.
Verify webhooks
Every webhook request has an X-Sendfern-Signature header. verify_webhook(secret, header, raw_body) returns True when the signature matches your endpoint's secret (whsec_...) and the timestamp is within 5 minutes. Change the window with the tolerance_seconds keyword.
Pass the body exactly as it arrived, as bytes or str. A body that was parsed and serialized again will not match.
import json
import os
from flask import Flask, request
from sendfern import verify_webhook
app = Flask(__name__)
SECRET = os.environ["SENDFERN_WEBHOOK_SECRET"]
@app.post("/webhooks/sendfern")
def sendfern_webhook():
raw_body = request.get_data() # the bytes exactly as received
if not verify_webhook(SECRET, request.headers.get("X-Sendfern-Signature"), raw_body):
return "", 400
event = json.loads(raw_body)
if event["type"] == "email.bounced":
...
return "", 200In Django, use request.body and exempt the view from CSRF, since Sendfern cannot send a CSRF token:
import json
import os
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from sendfern import verify_webhook
@csrf_exempt
@require_POST
def sendfern_webhook(request):
if not verify_webhook(
os.environ["SENDFERN_WEBHOOK_SECRET"],
request.headers.get("X-Sendfern-Signature"),
request.body,
):
return HttpResponse(status=400)
event = json.loads(request.body)
...
return HttpResponse(status=200)Answer with a 2xx quickly and do slow work afterwards. Events can arrive more than once, so use the event id to skip duplicates. See Webhooks.
Versioning
The SDK follows semantic versioning. While it is at 0.x, a minor release (0.1 to 0.2) may contain breaking changes, so pin the minor version, for example sendfern~=0.1.0. The package is sendfern on PyPI. The Node.js SDK has a matching API.