Skip to Content
Docs
Frameworks

FastAPI & Python

Send transactional emails and handle delivery webhooks in Python and FastAPI using httpx or the official emitd Python SDK.

Integrate emitd into your Python FastAPI application with async performance and typing support.

1. Install dependencies

Install the official emitd SDK:

pip install emitd

Or if using httpx directly:

pip install fastapi uvicorn httpx

2. Configure environment variables

Set your API key in .env:

EMITD_API_KEY=esk_live_...

3. Send email from a FastAPI route

main.py
import os
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, EmailStr
import httpx

app = FastAPI(title="Acme API")
EMITD_API_KEY = os.getenv("EMITD_API_KEY")

class SignupRequest(BaseModel):
    name: str
    email: EmailStr

@app.post("/api/signup")
async def signup(payload: SignupRequest):
    async with httpx.AsyncClient() as client:
        response = await client.post(
            "https://api.emitd.com/v1/email",
            headers={
                "Authorization": f"Bearer {EMITD_API_KEY}",
                "Content-Type": "application/json",
            },
            json={
                "from": "hello@yourdomain.com",
                "to": [payload.email],
                "subject": f"Welcome, {payload.name}!",
                "html_body": f"<h1>Welcome, {payload.name}!</h1><p>Your account is ready.</p>",
                "tags": {"source": "fastapi"},
                "message_stream": "outbound",
            },
            timeout=10.0,
        )

        if response.status_code != 202:
            raise HTTPException(status_code=500, detail="Failed to queue email")

        data = response.json()
        return {"status": "success", "message_id": data.get("message_id")}

4. Verify webhook events

Verify HMAC SHA-256 signatures for incoming delivery webhooks:

webhooks.py
import os
import hmac
import hashlib
from fastapi import FastAPI, Request, HTTPException

app = FastAPI()
WEBHOOK_SECRET = os.getenv("EMITD_WEBHOOK_SECRET", "")

@app.post("/webhooks/emitd")
async def handle_webhook(request: Request):
    signature = request.headers.get("emitd-signature")
    if not signature:
        raise HTTPException(status_code=401, detail="Missing signature header")

    body = await request.body()
    computed = hmac.new(
        WEBHOOK_SECRET.encode(),
        body,
        hashlib.sha256,
    ).hexdigest()

    if not hmac.compare_digest(signature, computed):
        raise HTTPException(status_code=401, detail="Invalid signature")

    event = await request.json()
    event_type = event.get("type")
    print(f"Received webhook: {event_type}")

    return {"status": "ok"}

What's next?

On this page