# Send Email with Django Using an Email API

> Send email with Django through an email API: a custom EMAIL_BACKEND so send_mail and password resets use Cresca, plus templates, idempotency and Celery.

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

Django comes with a complete mail API: `send_mail()`, `EmailMessage`, password reset emails and error reports to `ADMINS`. To **send email with Django** in production, all you have to decide is how those messages leave your server. This tutorial swaps the SMTP settings for a small custom email backend that posts each message to the Cresca email API. Every email your project sends, Django's own included, then goes out from your verified domain, and the code that sends it stays as it is. After that, it covers the cases where calling the API directly is the better choice: idempotent sends and Cresca templates.

**TL;DR**

- Add a `CrescaEmailBackend` of about 60 lines and point `EMAIL_BACKEND` at it.
- Existing `send_mail()` and `EmailMultiAlternatives` calls, and the password reset flow, then go through Cresca unchanged.
- For emails that must never be duplicated, or that use a Cresca template, call the API client directly with an `Idempotency-Key`.
- Queue sends in Celery from `transaction.on_commit` so requests never wait on email.

## Before you start

- Django 4.2 or later, plus `requests` (`pip install requests`).
- In Cresca: a verified domain on [Sending Domains](https://app.cresca.xyz/sending-domains), a sender on it that will become your `DEFAULT_FROM_EMAIL`, and a *Sending access* key from [API keys](https://app.cresca.xyz/api-keys). The [email API quickstart](https://www.cresca.xyz/docs/quickstart) has the details.
- The key in the server's environment as `CRESCA_API_KEY`. It starts with `cr_live_` and is shown once. Keep it out of `settings.py` and out of version control; the client below reads it from `os.environ`.

## Step 1: a small API client

The backend needs something to make the HTTP call. This is the client from the [Python tutorial](https://www.cresca.xyz/blog/send-email-python) with the backoff written inline: a shared `requests.Session`, a 10-second timeout, and retries for network errors, `429` and `5xx` responses. Put it in your project package so the backend and your Celery tasks can both import it.

```python
# myproject/cresca.py
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 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:
            if attempt == ATTEMPTS:
                raise
            time.sleep(2 ** (attempt - 1) + random.random() / 4)
            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 2 ** (attempt - 1) + random.random() / 4)
```

Failures raise `CrescaError`, whose `.name` holds Cresca's stable error name, such as `validation_error`. A `429 monthly_quota_exceeded` and other 4xx errors are raised right away, since retrying would not help.

## Step 2: send email with Django through a custom backend

Django loads the class named in `EMAIL_BACKEND` whenever it needs a mail connection and passes a list of messages to its `send_messages()`. The contract is small: subclass `BaseEmailBackend`, return how many messages were sent, and respect `fail_silently`. This backend maps each `EmailMessage` to an API payload:

- `from_email`, `to`, `cc`, `bcc` and `reply_to` go to the matching API fields.
- The body becomes `html` when `content_subtype` is `"html"`, and `text` otherwise. A `text/html` alternative from `attach_alternative()` becomes `html`, so you send both parts.
- Files added with `attach()` or `attach_file()` are base64-encoded. Attachments passed as `MIMEBase` objects are skipped.

```python
# myproject/cresca_backend.py
import base64

from django.core.mail.backends.base import BaseEmailBackend

from .cresca import cresca

class CrescaEmailBackend(BaseEmailBackend):
    """Sends Django email through the Cresca API."""

    def send_messages(self, email_messages):
        sent = 0
        for message in email_messages:
            try:
                cresca("/emails", self._payload(message))
                sent += 1
            except Exception:
                if not self.fail_silently:
                    raise
        return sent

    def _payload(self, message):
        payload = {
            "from": message.from_email,
            "to": message.to,
            "subject": message.subject,
        }
        if message.cc:
            payload["cc"] = message.cc
        if message.bcc:
            payload["bcc"] = message.bcc
        if message.reply_to:
            payload["reply_to"] = message.reply_to

        if message.content_subtype == "html":
            payload["html"] = message.body
        else:
            payload["text"] = message.body
        for content, mimetype in getattr(message, "alternatives", []):
            if mimetype == "text/html":
                payload["html"] = content

        attachments = []
        for attachment in message.attachments:
            if not isinstance(attachment, tuple):
                continue  # MIMEBase attachments are not supported here
            filename, content, mimetype = attachment
            if isinstance(content, str):
                content = content.encode()
            attachments.append({
                "filename": filename,
                "content": base64.b64encode(content).decode(),
                "content_type": mimetype or "application/octet-stream",
            })
        if attachments:
            payload["attachments"] = attachments
        return payload
```

Then switch it on in settings:

```python
# settings.py
EMAIL_BACKEND = "myproject.cresca_backend.CrescaEmailBackend"
DEFAULT_FROM_EMAIL = "Acme <hello@acme.com>"  # an active sender on your verified domain
SERVER_EMAIL = "Acme Errors <errors@acme.com>"  # sender for admin error emails
```

Both addresses must be active senders on your verified domain, or the API answers `403 invalid_from_address`. For local development, set `EMAIL_BACKEND` to `django.core.mail.backends.console.EmailBackend` so emails print to the terminal instead of going out. The test runner switches to the locmem backend on its own, so `mail.outbox` keeps working in your tests.

## Step 3: keep calling send\_mail()

Code that already sends email does not change. Both of these now go through Cresca:

```python
from django.core.mail import EmailMultiAlternatives, send_mail
from django.template.loader import render_to_string

send_mail(
    "Welcome to Acme",
    "Hi Ana, your account is ready.",
    None,  # uses DEFAULT_FROM_EMAIL
    ["ana@example.com"],
)

context = {"user": user, "order": order}
message = EmailMultiAlternatives(
    subject=f"Your order #{order.number} is confirmed",
    body=render_to_string("emails/order_confirmed.txt", context),
    to=[user.email],
    reply_to=["support@acme.com"],
)
message.attach_alternative(render_to_string("emails/order_confirmed.html", context), "text/html")
message.attach(f"receipt-{order.number}.pdf", order.receipt_pdf_bytes(), "application/pdf")
message.send()
```

The second example renders a text and an HTML version with `render_to_string`, adds the HTML as an alternative and attaches a PDF. The backend turns all of that into one API request with `text`, `html` and a base64 attachment. Django's template engine auto-escapes variables, so a customer's name in the HTML template cannot break the markup. Django's built-in mail uses the backend too: `PasswordResetView`, `mail_admins()` and the error emails sent to `ADMINS`.

## When to call the API directly

Django's mail API has no way to express two Cresca features, so for these, skip the backend and use the client:

- **Idempotency.** `send_mail()` cannot pass an `Idempotency-Key`. Receipts and other emails that must go out exactly once should be sent with a key derived from the event, such as the order number. Cresca keeps keys for 24 hours and answers a repeat with the first result. See [idempotency](https://www.cresca.xyz/docs/idempotency).
- **Cresca templates.** The email's design lives in Cresca, and Django sends only the alias and the variables.

```python
from myproject.cresca import cresca

cresca(
    "/emails",
    {
        "to": user.email,
        "template": {
            "id": "order-confirmed",  # the template's alias or id
            "variables": {"NAME": user.first_name, "ORDER_NUMBER": order.number},
        },
    },
    idempotency_key=f"order-confirmed/{order.number}",
)
```

Templates are built in Cresca's editor, with the values Django supplies marked in triple braces such as `{{{ORDER_NUMBER}}}`. That is Cresca's syntax, not a Django template tag; Cresca fills in the values when it sends. Only the *published* version goes out, so drafts are safe to edit. Values are HTML-escaped. A missing variable without a fallback gets a `422 validation_error` that names it. See [templates and variables](https://www.cresca.xyz/docs/templates).

## Send from a Celery task

The backend and the client both block while the request is in flight. That is fine in a worker and wasteful in a view, so queue the send:

```python
# myproject/tasks.py
from celery import shared_task

from .cresca import cresca

@shared_task(autoretry_for=(Exception,), retry_backoff=True, max_retries=5)
def send_welcome_email(user_id, email, first_name):
    cresca(
        "/emails",
        {"to": email, "template": {"id": "welcome", "variables": {"NAME": first_name}}},
        idempotency_key=f"welcome/{user_id}",
    )

# In a view, after the user is saved:
# transaction.on_commit(lambda: send_welcome_email.delay(user.id, user.email, user.first_name))
```

Three pieces work together. `transaction.on_commit` only queues the task once the user row is committed, so a signup that rolls back never gets a welcome email. `autoretry_for` with `retry_backoff=True` has Celery retry with growing delays, up to five times, if Cresca is still unreachable after the client's own retries. The idempotency key means none of those retries can deliver a second email. That is why the task calls `cresca()` and not `send_mail()`: through the backend there is no key, so a retry after a lost response could send twice. Note that `autoretry_for=(Exception,)` also retries a `422`; narrow it if you only want temporary errors retried.

## Attachments and batches

Attachments need no extra code, because the backend base64-encodes anything added with `message.attach()`. Cresca's limits still apply: up to 20 files and 7 MB in total per email, and executable types such as .exe and .js are refused. Files cannot be attached by URL yet. Inline images use a `content_id` and `<img src="cid:logo">`; the backend does not set that field, so send those emails through the client.

`send_mass_mail()` works with the backend but makes one API request per message. For a large send, use the batch endpoint through the client. `POST /emails/batch` accepts up to 100 emails, each with the fields of a single send except `attachments` and `scheduled_at`. It is all or nothing, and a validation error names the failing email by its zero-based index. The response lists ids in your order as `{"data": [{"id": "..."}, ...]}`, and the whole batch counts as one request against your rate limit. From a Celery task, call `cresca("/emails/batch", chunk, idempotency_key=...)` for each chunk of 100; the [Python tutorial](https://www.cresca.xyz/blog/send-email-python) shows the loop.

## Errors and fail\_silently

With the backend in place, a Cresca error surfaces as a `CrescaError` raised from `send_mail()` or `message.send()`. Pass `fail_silently=True` and the backend swallows it instead; `send_mail()` then returns the number of messages actually sent, so a 0 tells you it failed. The most common codes are below, and the [errors page](https://www.cresca.xyz/docs/errors) has the rest.

| Status | name | Likely cause in a Django project | Retried by the client? |
| --- | --- | --- | --- |
| 403 | `invalid_from_address` | `DEFAULT_FROM_EMAIL`, `SERVER_EMAIL` or a `from_email` is not an active sender on a verified domain. | No |
| 422 | `validation_error` | A field is invalid, or a Cresca template variable is missing. | No |
| 422 | `missing_required_field` | No to, from or subject, and no template that provides them. | No |
| 429 | `rate_limit_exceeded` | More requests per second than your plan allows, for example from a `send_mass_mail()` loop. | Yes, after `retry-after` |
| 429 | `monthly_quota_exceeded` | The plan's monthly allowance is used up. | No |
| 409 | `concurrent_idempotent_requests` | The same key is still being processed. | Yes |
| 5xx | `application_error` | A problem on Cresca's side. | Yes, with backoff |

If a recipient is on your suppression list because of an earlier hard bounce, complaint or unsubscribe, Cresca skips them and the call still succeeds, so `send_mail()` counts the message as sent. See [suppression](https://www.cresca.xyz/docs/suppression).

## Confirm delivery

`send_mail()` returning 1 means Cresca accepted the message, not that it reached an inbox. The backend does not keep the email id, so for mail sent through Django's API the easiest place to follow it is [Transactional](https://app.cresca.xyz/transactional) in the app. For emails sent through the client you have the id, and you can look it up with a full-access key:

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

`last_event` moves from `queued` to `sent`, then to `delivered` or `bounced`. See [email lifecycle](https://www.cresca.xyz/docs/email-lifecycle) for the full list.

## Frequently asked questions

### Can I keep using send\_mail()?

Yes, that is what the backend is for. `send_mail()`, `EmailMessage`, `EmailMultiAlternatives` and `mail_admins()` keep working, and only `EMAIL_BACKEND` changes. Switch to the client when you need an idempotency key or a Cresca template.

### Do password reset emails go through the backend?

Yes. `PasswordResetView` sends through whichever `EMAIL_BACKEND` is configured, including the HTML version if you set `html_email_template_name`. Make sure `DEFAULT_FROM_EMAIL` is an active sender on your verified domain.

### Can I use django-anymail instead?

django-anymail supports many email providers, but Cresca is not one of them, so you would still need a backend like this one. It is short enough to live in your project and change as you need.

## The same tutorial in other languages

[Node.js](https://www.cresca.xyz/blog/send-email-nodejs) · [Python](https://www.cresca.xyz/blog/send-email-python) · [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) · [Ruby on Rails](https://www.cresca.xyz/blog/send-email-rails)

If you want the raw API rather than a Django backend, the [send email API guide](https://www.cresca.xyz/blog/send-email-api) covers every field with cURL examples. The [transactional email API overview](https://www.cresca.xyz/blog/transactional-email-api) explains how it all fits, and [SMTP vs API](https://www.cresca.xyz/blog/smtp-vs-api-sending) helps if you are still deciding between the two.

## Start sending

Set `CRESCA_API_KEY`, add the two files and point `EMAIL_BACKEND` at the backend, and your next `send_mail()` goes through Cresca. Cresca is free for 30 days: 250 contacts, 1,000 emails and 20 AI emails, no credit card. **[Create an account](https://app.cresca.xyz/signup)**, then follow the [quickstart](https://www.cresca.xyz/docs/quickstart) or see the [API docs](https://www.cresca.xyz/docs).
