# Django

Send a Django app's mail from a view with the Python SDK, check each webhook in a view, and develop against a test server.

The Python SDK, `sendora`, sends a Django app's mail from its views, and a view checks each webhook's signature against the raw body. This guide's samples run on Django 5.2 with Python 3.11 or newer, and on Django 6.0 and 6.1 with Python 3.12 or newer.

## Before you start

- A [server key](https://sendora.se/docs/keys), which you create on the server's **API keys** tab in the dashboard. A [test server](https://sendora.se/docs/test-servers)'s key works before Sendora approves your account, and it delivers nothing.
- A [verified sending domain](https://sendora.se/docs/domains) for the From address. A test server checks the domain too.

## Install

```sh
pip install sendora
```

The samples sit in an app named `support`, which `python manage.py startapp support` makes. Add `"support"` to `INSTALLED_APPS`, and include the app's URLs in the project's `urls.py`, as in `path("", include("support.urls"))`.

## Settings

Set the server key and the webhook's secret in the environment that runs Django, and keep both out of git. You get the secret once you create the webhook, as [Webhooks](#webhooks) below shows.

```sh
export SENDORA_API_TOKEN=sk_…
export SENDORA_WEBHOOK_SECRET=whsec_…
```

Then add these lines to the project's `settings.py`:

```python
import os

from django.core.exceptions import ImproperlyConfigured
from sendora import is_test_key

SENDORA_API_TOKEN = os.environ["SENDORA_API_TOKEN"]
SENDORA_WEBHOOK_SECRET = os.environ.get(
    "SENDORA_WEBHOOK_SECRET"
)

production = os.environ.get("APP_ENV") == "production"
if production and is_test_key(SENDORA_API_TOKEN):
    message = (
        "SENDORA_API_TOKEN is a test key; "
        "nothing would be delivered"
    )
    raise ImproperlyConfigured(message)
```

- `SENDORA_API_TOKEN` is the server key. Without it, Django stops as it starts rather than at the first send. A step that sends nothing, such as `collectstatic` in an image build, still needs a value, such as `SENDORA_API_TOKEN=unused`.
- `SENDORA_WEBHOOK_SECRET` is the webhook's signing secret. Django starts without it, and the webhook's view then fails each delivery, as [Webhooks](#webhooks) says.
- With `APP_ENV` set to `production`, the check refuses a test key, as [Develop against a test server](#develop-against-a-test-server) explains.

Make the client once, in `support/sendora_client.py`. It is safe across threads, so every view shares it:

```python
from django.conf import settings
from sendora import Sendora

sendora = Sendora(settings.SENDORA_API_TOKEN)
```

In `support/urls.py`, route the views that the sections below write:

```python
from django.urls import path

from . import views, webhooks

urlpatterns = [
    path("contact/", views.contact, name="contact"),
    path(
        "sendora/webhook/",
        webhooks.receive,
        name="sendora-webhook",
    ),
]
```

## Send mail

The view in `support/views.py` sends a contact form's message to your support address:

```python
from django.contrib import messages
from django.http import HttpRequest, HttpResponse
from django.shortcuts import redirect, render

from .forms import ContactForm
from .sendora_client import sendora

def contact(request: HttpRequest) -> HttpResponse:
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            sendora.email.send(
                from_={
                    "email": "no-reply@example.se",
                    "name": "Example AB",
                },
                to=["support@example.se"],
                headers={"Reply-To": data["email"]},
                subject="A message from the contact form",
                text=data["message"],
                tag="contact-form",
            )
            messages.success(
                request, "Thanks, we will answer soon."
            )
            return redirect("contact")
    else:
        form = ContactForm()
    return render(
        request, "support/contact.html", {"form": form}
    )
```

It takes the form in `support/forms.py`:

```python
from django import forms

class ContactForm(forms.Form):
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)
```

- The view sends to your own address, and takes the visitor's only for `Reply-To`. A view that sends to an address from its request would let anyone mail anyone.
- Sendora refuses a header value that holds a line break, so the visitor's address cannot add a header of its own.
- `send()` returns the accepted message, with Sendora's `message_id`, which the log and the webhooks use.
- The tag sets the form's mail apart in the log and in every webhook. Add [metadata](https://sendora.se/docs/sending#attachments-headers-tags-and-metadata) for ids of your own, such as an order's.
- If Sendora refuses the mail, `send()` raises a `SendoraError` with the [error code](https://sendora.se/docs/errors). Django then answers 500, as for any error in a view.
- `support/contact.html` is a template of your own. It renders the form with `{% csrf_token %}`, and the thanks that the view adds through Django's messages framework.
- In an async view, make the client with `AsyncSendora`, and `await` its `send()`.
- When a job may send the same mail twice, pass an [idempotency key](https://sendora.se/docs/sending#idempotency) of your own, as in `sendora.email.send(..., idempotency_key="order-1042-shipped")`. A retry with the same key returns the first answer and sends nothing.

Django's own mail, such as its password resets and its error reports to `ADMINS`, goes through its email backend. To send that mail through Sendora too, give the backend Sendora's SMTP settings, as [Send from Django](https://sendora.se/docs/smtp#send-from-django) shows.

## Webhooks

A view checks each delivery's signature, then handles its event. A delivery is one event sent to your webhook, and each post of it is an attempt.

1. Add the view, `support/webhooks.py`. This one logs a hard bounce, and files each received mail as [Received mail](#received-mail) explains. If the app receives no mail, leave out the `InboundEvent` branch and the imports it needs:

```python
import logging

from django.conf import settings
from django.http import HttpRequest, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from sendora import (
    BouncedEvent,
    InboundEvent,
    WebhookVerificationError,
    verify_webhook,
)

from .tickets import file_ticket

logger = logging.getLogger(__name__)

@csrf_exempt
@require_POST
def receive(request: HttpRequest) -> HttpResponse:
    try:
        event = verify_webhook(
            # The body as Sendora sent it, which the
            # signature covers.
            request.read(),
            signature=request.headers.get(
                "Sendora-Signature"
            ),
            secret=settings.SENDORA_WEBHOOK_SECRET,
        )
    except WebhookVerificationError:
        return HttpResponse(status=400)

    if (
        isinstance(event, BouncedEvent)
        and event.details.hard
    ):
        logger.warning(
            "A message bounced for good %s",
            event.message_id,
        )
    elif isinstance(event, InboundEvent):
        file_ticket(event.inbound_message_id)
    return HttpResponse(status=204)
```

2. Create a webhook under the server's [Webhooks](https://app.sendora.se/servers) tab, with the view's address and its last slash, such as `https://example.se/sendora/webhook/`. If the app receives mail, create it through the API instead, as [Received mail](#received-mail) says.
3. Put its secret in `SENDORA_WEBHOOK_SECRET`, and deploy.

`request.read()` hands the view the body as Sendora sent it, and `verify_webhook` checks the signature before it parses anything. It returns the event as a class of its own, such as `BouncedEvent`, so its `details` are typed. [Webhooks](https://sendora.se/docs/webhooks#events) says when Sendora sends each event, and [Webhook events](https://sendora.se/docs/api/webhook-events) lists their fields.

- `csrf_exempt` lets Sendora's posts past Django's CSRF check, since Sendora sends no CSRF token. `require_POST` answers 405 to any other method.
- The view answers 204 once it has handled the event. If the handling raises, Django answers 500, and Sendora delivers the event again later, on the schedule that [Webhooks](https://sendora.se/docs/webhooks#retries-dead-letters-and-replay) gives.
- Sendora waits only as long as [Limits](https://sendora.se/docs/limits#webhooks) says, so queue slow work. One fetch of a received mail is quick enough to make in the view.
- A delivery whose signature is missing, wrong or more than five minutes old gets 400, since `verify_webhook` raises a `WebhookVerificationError` with `invalid_signature` or `stale_signature`. Without the secret, it raises a `ValueError`, and Django answers 500.
- A delivery can arrive more than once. Key your handling on `event.id`, the delivery's id, which stays the same on each attempt.
- Without the last slash, Django answers a post with a redirect, or with an error while `DEBUG` is on. Either fails the attempt, as any redirect does.
- `request.read()` takes a body of any size, where `request.body` refuses one over `DATA_UPLOAD_MAX_MEMORY_SIZE`, 2.5 MB by default. An `inbound` event that carries the whole mail can be larger, as [Limits](https://sendora.se/docs/limits#inbound-mail) shows.
- So cap the body's size at your proxy, such as with nginx's `client_max_body_size`. Its default of 1 MB is enough for a webhook that takes received mail by reference, as the next section creates it.
- If the app has `LoginRequiredMiddleware`, add `@login_not_required`, from `django.contrib.auth.decorators`, to the view. Its redirect to the sign-in page would fail every attempt.
- To [roll the secret](https://sendora.se/docs/webhooks#roll-the-secret), create the new one and set `SENDORA_WEBHOOK_SECRET` to it. Sendora signs each delivery with both until you delete the old one.

## Received mail

The view above files each received mail. An `inbound` event has the message's `inbound_message_id`, and `support/tickets.py` fetches the mail by it:

```python
from pathlib import Path

from django.conf import settings

from .sendora_client import sendora

def file_ticket(inbound_message_id: str) -> None:
    mail = sendora.inbound.get(inbound_message_id)

    # Only a DMARC pass proves the From domain sent it.
    folder = Path(settings.BASE_DIR) / "tickets"
    if mail.authentication.dmarc != "pass":
        folder /= "unverified"
    folder.mkdir(parents=True, exist_ok=True)
    (folder / f"{inbound_message_id}.txt").write_text(
        mail.text or "", encoding="utf-8"
    )
```

- The view fetches the mail, so create its webhook through the API with `inbound_content` set to `reference`. A webhook from the dashboard carries the whole mail in each `inbound` event, as [Inbound](https://sendora.se/docs/inbound#the-inbound-event) explains.
- Create it once, such as from `python manage.py shell`, with the client that `support/sendora_client.py` makes: `sendora.webhooks.create(url=url, inbound_content="reference")`. The answer's `secret` goes in `SENDORA_WEBHOOK_SECRET`, and Sendora shows it only then.
- Without `events`, the webhook takes every event but `opened` and `clicked`, as [Webhooks](https://sendora.se/docs/webhooks#register) says.
- Only a DMARC `pass` proves that the From domain sent the message. With any other verdict, the From address may be forged.
- Sendora keeps the mail's content for the stream's retention, as [Inbound](https://sendora.se/docs/inbound#what-sendora-keeps) says. After that, `mail.text` is `None`, so the sample files an empty ticket.
- A second delivery of the same mail writes the same file again, so it does no harm.
- This sample files the text under the project's folder, where git or a fresh deploy can reach it. Keep the mail where the app keeps its data instead, such as in a model of your own.
- A test server has no inbound stream, so receive mail on a live server.

## Develop against a test server

A test server checks and logs each mail as a live server does, and delivers none of it. Its keys start with `sk_test_`.

1. Create a test server under [Servers › New server](https://app.sendora.se/servers/new), with **Testserver** ticked, and a key on its **API keys** tab.
2. Put the key in `SENDORA_API_TOKEN` on your machine, and in CI. Keep a live server's key in production.
3. Send to the [simulator's addresses](https://sendora.se/docs/test-servers#the-simulators-addresses), such as `hardbounce@simulator.sendora.se`, to act out a bounce or a complaint. The message's events show in the dashboard's message log, as [Messages and events](https://sendora.se/docs/messages) explains.

`settings.py` above refuses a test key where mail must arrive. With `APP_ENV` set to `production`, Django stops as it starts, with an `ImproperlyConfigured` error. Without `APP_ENV`, the check lets any key through, so set it on every production machine. Leave it unset on your machine, in CI and on staging, which can then send with a test key.

Sendora posts webhooks only to a public HTTPS address, so a test server's events cannot reach your machine. Post a signed delivery in a test instead, signed as [Verify the signature](https://sendora.se/docs/webhooks#verify-the-signature) describes. `support/tests.py` posts a hard bounce to the view:

```python
import hashlib
import hmac
import json
import time
import uuid

from django.test import TestCase, override_settings
from django.urls import reverse

SECRET = "whsec_test"
BOUNCE = {
    "id": str(uuid.uuid4()),
    "attempt": 1,
    "event": "bounced",
    "messageId": str(uuid.uuid4()),
    "recipient": "hardbounce@simulator.sendora.se",
    "occurredAt": "2026-11-22T10:00:00.000Z",
    "serverId": str(uuid.uuid4()),
    "streamId": str(uuid.uuid4()),
    "broadcastId": None,
    "tag": "contact-form",
    "metadata": {},
    "test": True,
    "details": {
        "code": 550,
        "response": "5.1.1 No such user",
        "classification": "InvalidRecipient",
        "hard": True,
        "expired": False,
    },
}

@override_settings(SENDORA_WEBHOOK_SECRET=SECRET)
class SendoraWebhookTests(TestCase):
    def test_a_signed_hard_bounce_is_logged(self) -> None:
        body = json.dumps(BOUNCE).encode()
        # Signed as Sendora signs each delivery.
        t = str(int(time.time()))
        v1 = hmac.new(
            SECRET.encode(),
            f"{t}.".encode() + body,
            hashlib.sha256,
        ).hexdigest()

        with self.assertLogs("support.webhooks"):
            response = self.client.post(
                reverse("sendora-webhook"),
                body,
                content_type="application/json",
                headers={
                    "Sendora-Signature": f"t={t},v1={v1}"
                },
            )
        self.assertEqual(response.status_code, 204)
```

Run it with `python manage.py test support`. `override_settings` gives the view the test's own secret, so the test needs no webhook secret in the environment. It still needs a key in `SENDORA_API_TOKEN`, which `settings.py` reads as Django starts. `assertLogs` checks that the view logged the bounce.
