Email API Python

How to Send Transactional Email with Python (in 10 Lines)

By Nimana · Last updated December 4, 2026 · 4 min read

Send password resets, receipts and alerts from Python with one HTTP request. Step-by-step code, error handling and a reusable helper.

Every app sends email: welcome messages, password resets, receipts, alerts. Running your own mail server for that is a headache. Deliverability, DNS records and bounce handling all take time you'd rather spend on your product.

This guide shows how to send transactional email from Python with a single HTTP request to SendAPI. You'll go from zero to a reusable send_email() helper in about ten minutes.

Why This Matters

Transactional emails are the messages customers are waiting for. A password reset that arrives late or lands in spam turns into a support ticket or a lost sign-up. A receipt that never arrives leaves a paying customer wondering if the payment went through. Getting these right comes down to reliable sending, and that's what this guide covers.

What you need

  • Python 3.10 or newer
  • A SendAPI account (the free trial works)
  • Your API key from the dashboard. It starts with sk_live_

Step 1: Install requests and store your key

pip install requests
export SENDAPI_KEY="your_api_key_here"

Never paste the key into your code or commit it to Git. Read it from the environment. (More on this in How to Manage API Keys Safely.)

Step 2: Send your first email

import os
import requests

response = requests.post(
    "https://sendapi.co/v1/email/send",
    headers={
        "Authorization": f"Bearer {os.environ['SENDAPI_KEY']}",
        "Content-Type": "application/json",
    },
    json={
        "to": "you@example.com",
        "subject": "My first SendAPI email",
        "text": "It works.",
    },
    timeout=10,
)

print(response.status_code)
print(response.json())

Run it. A successful send returns HTTP 201 Created, and the JSON body has "success": true plus a data object with the message id and "status": "sent". Keep that id. It's how you match delivery events from webhooks later.

If you leave out from, the email goes out from hello@sendapi.co. That's fine for testing. For production, send from your own domain (Step 4). Using a domain you haven't verified returns 422 invalid_from_domain.

Step 3: Wrap it in a reusable helper

Don't scatter HTTP calls around your codebase. One function keeps auth, timeouts and errors in one place.

import os
import uuid
import requests

SENDAPI_URL = "https://sendapi.co/v1/email/send"


class EmailError(Exception):
    pass


def send_email(to: str, subject: str, text: str, html: str | None = None,
               idempotency_key: str | None = None) -> str:
    """Send a transactional email. Returns the SendAPI message id."""
    payload = {"to": to, "subject": subject, "text": text}
    if html:
        payload["html"] = html

    try:
        response = requests.post(
            SENDAPI_URL,
            headers={
                "Authorization": f"Bearer {os.environ['SENDAPI_KEY']}",
                # Reuse the same key when retrying, so the email is sent only once
                "Idempotency-Key": idempotency_key or str(uuid.uuid4()),
            },
            json=payload,
            timeout=10,
        )
    except requests.RequestException as exc:
        raise EmailError(f"Network error: {exc}") from exc

    if response.status_code != 201:
        raise EmailError(f"SendAPI returned {response.status_code}: {response.text}")

    return response.json()["data"]["id"]

Now a password reset is one line:

send_email(
    to=user.email,
    subject="Reset your password",
    text=f"Use this link to reset your password: {reset_link}\nIt expires in 30 minutes.",
)

Step 4: Get into the inbox, not spam

Before you go live, send from your own domain and set up SPF, DKIM and DMARC. Without them, Gmail and Outlook are far more likely to file your emails as spam. The full walkthrough is in How to Stop Your Transactional Emails Going to Spam.

Step 5: Handle errors and retries properly

In a web app, send email from a background job (Celery, RQ or a simple queue), not inside the request. A slow email provider should never make your sign-up page slow.

Using Django or Flask?

The send_email() helper works as-is in both. Put it in a notifications.py module and call it from your views or task queue.

Next steps

The same API key also sends SMS, WhatsApp and OTP codes, so you won't need a second provider when you add them.