# Send Email with Python: A Complete API Tutorial

> Send email with Python using requests and an email API: HTML, templates, attachments, batch sending and safe retries, with working code. No smtplib needed.

Canonical: https://www.cresca.xyz/blog/send-email-python
Author: Lalit Kumar Jangid
Published: 2026-10-27
Last updated: 2026-10-30

If you need to **send email with Python** from an application, an HTTP email API is less work than `smtplib`: one `requests.post()` call, no SMTP login and no connection to keep alive. Cresca accepts the message, returns an id and delivers it from your verified domain within seconds. This tutorial starts with a script you can run from the terminal and ends with a module ready for production use, covering templates, attachments, batches, retries that never send twice and a FastAPI endpoint.

**TL;DR**

- One call: `requests.post("https://api.cresca.xyz/api/v1/emails", json=...)` with your key as a bearer token.
- Required fields are `from`, `to`, `subject`, and `html` or `text`. Build the payload as a dict, since `from` is a Python keyword.
- Always pass `timeout=`. Without it, `requests` can hang indefinitely.
- Use an `Idempotency-Key` for retries and `/emails/batch` for up to 100 emails per call.

## Before you start

- Python 3.8 or later, with `requests` installed in your virtualenv (`pip install requests`).
- A domain, a sender and a key in Cresca. Verify the domain on [Sending Domains](https://app.cresca.xyz/sending-domains), add a sender on it such as `hello@acme.com`, and create a *Sending access* key on [API keys](https://app.cresca.xyz/api-keys). The [email API quickstart](https://www.cresca.xyz/docs/quickstart) covers each step.
- The key exported as `CRESCA_API_KEY`. It begins with `cr_live_` and is displayed once. The code reads it with `os.environ['CRESCA_API_KEY']`, which raises `KeyError` straight away if the variable is missing, instead of sending a request with an empty token.

## Send email with Python: the basic request

```python
import os
import requests

res = requests.post(
    "https://api.cresca.xyz/api/v1/emails",
    headers={"Authorization": f"Bearer {os.environ['CRESCA_API_KEY']}"},
    json={
        "from": "Acme <hello@acme.com>",
        "to": "ana@example.com",
        "subject": "Welcome to Acme",
        "html": "<p>Hi Ana, your account is ready.</p>",
    },
    timeout=10,
)
body = res.json()
if not res.ok:
    raise RuntimeError(f"{body['name']}: {body['message']}")
print(body["id"])
```

`requests` does not raise an exception for a 4xx or 5xx response. You either call `res.raise_for_status()` or check `res.ok`, and checking `res.ok` lets you read Cresca's error body first. A successful send returns `200 OK` and the new email's id:

```json
{ "id": "4ef9a417-02e9-4d39-ad75-9611e0fcc33c" }
```

`json=` serializes the dict and sets the `Content-Type` header for you. `to` may be a string or a list. Leave out `text` and Cresca derives the plain-text part from `html`; include it to write that part yourself. `cc`, `bcc`, `reply_to`, `tags` and `scheduled_at` are optional.

## A cresca.py module with a Session and retries

For code that runs unattended, wrap the call in a module. Three things change.

- **One `requests.Session`.** The session reuses connections between sends and carries the `Authorization` header, so each call only passes a path and a payload. Every request still gets `timeout=10`, because a session has no timeout setting of its own.
- **Retries decided by the error `name`.** Cresca's error bodies look like `{"statusCode": 422, "name": "validation_error", "message": "..."}`; `name` is stable, the message is not. `requests.RequestException` covers connection errors and timeouts. Those, 5xx responses, `429 rate_limit_exceeded` and `409 concurrent_idempotent_requests` are retried after 1, 2 and 4 seconds plus jitter, or after the `retry-after` header when there is one. A `429 monthly_quota_exceeded` or any other 4xx raises at once.
- **An `Idempotency-Key`.** If Cresca accepted the email but the response was lost, a retry with the same key returns the original result and sends nothing new. Keys last 24 hours. Use a value tied to the event, like `welcome/user-123` or `invoice/inv-2026-0042`. `uuid.uuid4()` or a timestamp would give every retry a fresh key. See [idempotency](https://www.cresca.xyz/docs/idempotency).

```python
# cresca.py: a small client for the Cresca email API.
import os
import random
import time

import requests

API_URL = "https://api.cresca.xyz/api/v1"
ATTEMPTS = 4

session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['CRESCA_API_KEY']}"

class CrescaError(Exception):
    def __init__(self, status, name, message):
        super().__init__(f"{status} {name}: {message}")
        self.status = status
        self.name = name

def backoff(attempt):
    # 1s, 2s, 4s... plus up to 250 ms of jitter.
    return 2 ** (attempt - 1) + random.random() / 4

def cresca(path, payload, idempotency_key=None):
    headers = {"Idempotency-Key": idempotency_key} if idempotency_key else {}
    for attempt in range(1, ATTEMPTS + 1):
        try:
            res = session.post(API_URL + path, json=payload, headers=headers, timeout=10)
        except requests.RequestException:
            # Network error or timeout: the idempotency key makes a retry safe.
            if attempt == ATTEMPTS:
                raise
            time.sleep(backoff(attempt))
            continue

        try:
            body = res.json()
        except ValueError:
            body = {}
        if res.ok:
            return body

        name = body.get("name", "unknown_error")
        retryable = (
            res.status_code >= 500
            or (res.status_code == 429 and name != "monthly_quota_exceeded")
            or name == "concurrent_idempotent_requests"
        )
        if not retryable or attempt == ATTEMPTS:
            raise CrescaError(res.status_code, name, body.get("message", res.reason))
        retry_after = res.headers.get("retry-after")
        time.sleep(float(retry_after) if retry_after else backoff(attempt))
```

A body that is not JSON (an error page from a proxy, say) makes `res.json()` raise a `ValueError`; the helper treats that as an empty body, so the status code still decides what happens. Sending is now one function call:

```python
from html import escape
from cresca import cresca

sent = cresca(
    "/emails",
    {
        "from": "Acme <hello@acme.com>",
        "to": user.email,
        "subject": "Welcome to Acme",
        "html": f"<p>Hi {escape(user.first_name)}, your account is ready.</p>",
    },
    idempotency_key=f"welcome/{user.id}",
)
print(sent["id"])
```

`html.escape` stops a first name like `<b>Ana</b>` from turning into markup. Templates do the escaping for you.

## Send a template instead of an f-string

F-strings and Jinja2 are fine for short HTML, but a branded email is easier to maintain in Cresca's template editor. Mark the values your code supplies with triple braces, such as `{{{RESET_LINK}}}`, publish, and pass a `template` dict with the alias and `variables`:

```python
cresca(
    "/emails",
    {
        "to": user.email,
        "template": {
            "id": "password-reset",  # the template's alias or id
            "variables": {"NAME": user.first_name, "RESET_LINK": reset_url},
        },
    },
    idempotency_key=f"password-reset/{reset_request.id}",
)
```

Cresca always renders the *published* version, so drafts never reach live mail. Variables are HTML-escaped. A variable with no value and no fallback gets you `422 validation_error` with its name in the message. `from` and `subject` are taken from the template unless you pass them. See [templates and variables](https://www.cresca.xyz/docs/templates).

## Add attachments with base64

`Path.read_bytes()` loads the file, `base64.b64encode()` encodes it, and `.decode()` turns the resulting `bytes` into a `str`. Skip the decode and the request fails with a `TypeError`, because bytes are not JSON serializable.

```python
import base64
from pathlib import Path

pdf = Path("invoices/inv-2026-0042.pdf").read_bytes()

cresca(
    "/emails",
    {
        "from": "Acme Billing <billing@acme.com>",
        "to": customer.email,
        "subject": "Your invoice INV-2026-0042",
        "html": "<p>Thanks for your payment. Your invoice is attached.</p>",
        "attachments": [
            {
                "filename": "inv-2026-0042.pdf",
                "content": base64.b64encode(pdf).decode(),
                "content_type": "application/pdf",
            }
        ],
    },
    idempotency_key="invoice/inv-2026-0042",
)
```

Per email you can attach up to 20 files, 7 MB in total. Each entry has `filename`, `content` and an optional `content_type`; add `content_id` to show an inline image with `<img src="cid:logo">`. Cresca refuses executable types such as .exe and .js and does not support attaching by URL yet.

## Send a batch of up to 100 emails

```python
emails = [
    {
        "from": "Acme <hello@acme.com>",
        "to": user.email,
        "subject": "Your weekly summary",
        "html": render_summary(user),
    }
    for user in users
]

for i in range(0, len(emails), 100):
    result = cresca(
        "/emails/batch",
        emails[i : i + 100],
        idempotency_key=f"weekly-summary/2026-10-27/{i // 100}",
    )
    print(f"Batch {i // 100}: {len(result['data'])} emails accepted")
```

The list comprehension builds every payload, and `range(0, len(emails), 100)` walks it in slices that fit `POST /emails/batch`. `i // 100` numbers the chunks, which gives each one its own idempotency key. If the script dies halfway, run it again within 24 hours: chunks that already went out return their earlier result instead of sending twice.

Batch rules: items take the same fields as a single send apart from `attachments` and `scheduled_at`. Validation is all or nothing, so one bad item stops the whole batch and the error message gives its zero-based index. The reply is `{"data": [{"id": "..."}, ...]}` in input order. A batch is one request for rate-limit purposes, which is how you reach thousands of emails per minute. Each email can also carry up to 50 recipients across `to`, `cc` and `bcc`, and every recipient counts as one email against your monthly allowance.

## Send email from FastAPI or Flask without blocking

`cresca()` is synchronous on purpose, which is right for scripts and for Celery or RQ workers. In a web endpoint you want the response to go out first. FastAPI's `BackgroundTasks` runs the function after the response is sent, and because `cresca` is a plain `def`, FastAPI runs it in its threadpool instead of on the event loop:

```python
from fastapi import BackgroundTasks, FastAPI
from pydantic import BaseModel

from cresca import cresca

app = FastAPI()

class Signup(BaseModel):
    email: str
    first_name: str

@app.post("/signup", status_code=201)
def signup(data: Signup, background_tasks: BackgroundTasks):
    user = create_user(data)  # your own code
    background_tasks.add_task(
        cresca,
        "/emails",
        {"to": user.email, "template": {"id": "welcome", "variables": {"NAME": user.first_name}}},
        idempotency_key=f"welcome/{user.id}",
    )
    return {"id": user.id}
```

Background tasks run inside the web process, so a crash or a deploy can drop one. For emails you cannot afford to lose, use a worker queue. Flask has no built-in equivalent, so queue the send as a Celery or RQ task and call `cresca()` from the worker. On Django, the [Django tutorial](https://www.cresca.xyz/blog/send-email-django) wires Cresca into `send_mail()` itself.

## smtplib or an email API?

The standard library's `smtplib` works, and for a cron script talking to your own mail server it is enough. In an application it brings its own chores: `starttls()` and `login()` on each connection, MIME messages built with the `email` package, and reconnecting when the server drops you. An API call is a dict in and JSON out, with stable error names and idempotency keys for retries. Cresca has no SMTP relay yet, so with Cresca you send through the API.

## Exceptions cresca() raises

When retries run out, or the error is permanent, `cresca()` raises `CrescaError` with the HTTP status in `.status` and the API's error name in `.name`. Network failures re-raise the original `requests` exception after the fourth attempt, so catch both where it matters. The common codes are below; the [errors page](https://www.cresca.xyz/docs/errors) lists all of them.

| .status | .name | Cause | When it is raised |
| --- | --- | --- | --- |
| 403 | `invalid_from_address` | The `from` address is not an active sender on a verified domain. | Immediately |
| 422 | `validation_error` | Invalid field, or a template variable is missing. | Immediately |
| 422 | `missing_required_field` | No `to`, `from` or `subject`, and no template that supplies them. | Immediately |
| 429 | `rate_limit_exceeded` | Too many requests per second for your plan. | Only if the 4th attempt still fails |
| 429 | `monthly_quota_exceeded` | The plan's email allowance for the month is spent. | Immediately |
| 409 | `concurrent_idempotent_requests` | The same key is still being processed. | Only if the 4th attempt still fails |
| 5xx | `application_error` | A problem on Cresca's side. | Only if the 4th attempt still fails |

Suppressed addresses (past hard bounces, complaints and unsubscribes) raise nothing: Cresca skips them and the request still succeeds. See [suppression](https://www.cresca.xyz/docs/suppression).

## Look up the delivery status

A `200` is an acceptance receipt, not proof of delivery. Keep the returned id with the record that caused the email. You can follow it in the app under [Transactional](https://app.cresca.xyz/transactional), or request the email with a full-access key (sending-access keys cannot read logs):

```bash
curl https://api.cresca.xyz/api/v1/emails/4ef9a417-02e9-4d39-ad75-9611e0fcc33c \
  -H "Authorization: Bearer $CRESCA_API_KEY"
```

In the response, `last_event` starts at `queued`, moves to `sent`, and ends at `delivered` or `bounced`. The rest are described in [email lifecycle](https://www.cresca.xyz/docs/email-lifecycle).

## Frequently asked questions

### Can I send email asynchronously with httpx or aiohttp?

Yes. Swap the session for an `httpx.AsyncClient`, make `cresca()` an `async def`, and replace `time.sleep()` with `await asyncio.sleep()` so the backoff does not block the event loop. The retry rules and idempotency keys stay the same.

### Why not use urllib3's Retry with an HTTPAdapter?

Two reasons. By default `Retry` does not retry `POST`, because it cannot know a POST is safe to repeat; here, the idempotency key is what makes it safe. And it decides by status code alone, so it cannot tell `rate_limit_exceeded` (wait and retry) from `monthly_quota_exceeded` (stop), which share the 429 status.

### Is there an official Cresca SDK for Python?

No, and you do not need one. The API is HTTPS and JSON, so `requests`, `httpx` or whatever client you already use will work. `cresca.py` is short enough to keep in your project and change as you like.

## The same tutorial in other languages

[Node.js](https://www.cresca.xyz/blog/send-email-nodejs) · [PHP](https://www.cresca.xyz/blog/send-email-php) · [Go](https://www.cresca.xyz/blog/send-email-golang) · [Ruby](https://www.cresca.xyz/blog/send-email-ruby) · [Java](https://www.cresca.xyz/blog/send-email-java) · [C# and .NET](https://www.cresca.xyz/blog/send-email-csharp) · [Next.js](https://www.cresca.xyz/blog/send-email-nextjs) · [Laravel](https://www.cresca.xyz/blog/send-email-laravel) · [Django](https://www.cresca.xyz/blog/send-email-django) · [Ruby on Rails](https://www.cresca.xyz/blog/send-email-rails)

For the API reference side, the [send email API guide](https://www.cresca.xyz/blog/send-email-api) goes through each field with cURL examples. The [transactional email API overview](https://www.cresca.xyz/blog/transactional-email-api) is the place to start for the wider view, and [SMTP vs API](https://www.cresca.xyz/blog/smtp-vs-api-sending) weighs the two approaches.

## Start sending

Cresca is free for 30 days: 250 contacts, 1,000 emails and 20 AI emails, no credit card. API sends share the plan's email allowance with campaigns. **[Create an account](https://app.cresca.xyz/signup)**, export your key and run the first script above. The [quickstart](https://www.cresca.xyz/docs/quickstart) and the [API docs](https://www.cresca.xyz/docs) have everything else.
