Email API

/

Python

Email API in Python

This guide shows you how to send email from Python using a email API. Install requests or httpx, point them at the SDK host, and go live — sync or async, with webhooks for inbound messages. No SMTP relay, no per-email bill, no SDK lock-in.

Install + auth

Two packages cover the same wire contract — requests for sync code, httpx for asyncio. Pick whichever your service already uses. The API key comes from /dashboard/developers/api-keys and is bound to one of your domains.

requirements.txtbash
# Sync client (requests)
pip install requests

# Async client (httpx) — same wire contract, non-blocking
pip install httpx

Send with requests (sync)

POST /api/v1/messages with a JSON body. The from address must land on the domain the API key is bound to — the SDK backend rejects cross-domain sends with a 422 from_domain_mismatch.

send.pypython
import os
import requests

API_KEY = os.environ["FLOWMAILS_API_KEY"]   # fm_…
ENDPOINT = "https://sdk.flowmails.net/api/v1/messages"

resp = requests.post(
    ENDPOINT,
    headers={
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
    },
    json={
        "from": "hello@yourdomain.com",
        "to": "customer@example.com",
        "subject": "Order #1234 confirmed",
        "text": "Thanks for your order — we will ship it tomorrow.",
        # One key per logical mail. A retry with the same key replays
        # the first answer instead of sending a second message.
        "idempotencyKey": "order-1234",
    },
    timeout=15,
)
resp.raise_for_status()
print(resp.json())
# {"id": "8421", "status": "sent", "messageId": "<CAF8…@yourdomain.com>",
#  "sendFeedback": None, "error": None, "recipients": [...]}

Send async with httpx

Same wire contract, async I/O — drop this into a FastAPI handler, a Celery worker, or any asyncio app. The to field accepts a single address or a list.

send_async.pypython
import asyncio
import httpx

async def send():
    async with httpx.AsyncClient(timeout=15) as client:
        r = await client.post(
            "https://sdk.flowmails.net/api/v1/messages",
            headers={
                "Authorization": f"Bearer {os.environ['FLOWMAILS_API_KEY']}",
                "Content-Type": "application/json",
            },
            json={
                "from": "support@yourdomain.com",
                "to": ["customer@example.com", "team@yourdomain.com"],
                "subject": "Weekly digest",
                "html": "<h1>This week</h1><p>Three new signups.</p>",
            },
        )
        r.raise_for_status()
        return r.json()

asyncio.run(send())

Receive inbound webhooks

Flowmails POSTs a signed event to the URL you register in Settings → Webhooks, and stores the message so you can read it back through the API. Verify the HMAC, then fetch the body with the id the payload names. Filter spam, persist to your DB, fan out to your CRM — the message-id / threading bookkeeping is already done for you.

webhook.pypython
# FastAPI webhook receiver — drop into your service
import hashlib
import hmac
import json
import os
import time

from fastapi import FastAPI, Request, HTTPException

app = FastAPI()
WEBHOOK_SECRET = os.environ["WEBHOOK_SECRET"]  # the endpoint's own secret
TOLERANCE_SECONDS = 300  # how far a sender's clock may drift

def signature_is_valid(timestamp: str | None, body: bytes, header: str | None) -> bool:
    """HMAC-SHA256 over `<timestamp>.<body>`, sent as `sha256=<hex>`.

    The timestamp is INSIDE the signed material, so a captured request
    cannot be replayed with a fresh timestamp. Sign the raw bytes
    exactly as received — re-serialising the JSON changes them and the
    signature stops matching.

    `compare_digest` is constant-time: a byte-by-byte `==` leaks how
    much of the signature matched, which is enough to forge one.
    """
    if not header or not header.startswith("sha256="):
        return False
    if not timestamp or not timestamp.isdigit():
        return False
    if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        return False  # replayed, or the sender's clock is badly wrong
    signed = timestamp.encode() + b"." + body
    expected = hmac.new(WEBHOOK_SECRET.encode(), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, header.removeprefix("sha256="))

@app.post("/webhooks/inbound")
async def inbound(request: Request):
    # Flowmails posts a signed JSON event to the endpoint you register
    # in the dashboard. Verify BEFORE trusting anything in the body.
    body = await request.body()
    if not signature_is_valid(
        request.headers.get("x-flowmails-timestamp"),
        body,
        request.headers.get("x-flowmails-signature"),
    ):
        raise HTTPException(status_code=401, detail="bad signature")

    # The payload carries routing facts and the subject — never the
    # body; fetch that through the API with data["messageId"].
    event = json.loads(body)
    # event["event"] == "message.received"
    payload = event["data"]
    if payload.get("subject") and "spam" in payload["subject"].lower():
        return {"ok": True, "filtered": True}
    # … persist to your DB, fan out to CRM, etc.
    return {"ok": True}

Send your first email from Python in under five minutes.

Start free