Frameworks
More ways to use this page
Django
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, which you create on the server’s API keys tab in the dashboard. A test server’s key works before Sendora approves your account, and it delivers nothing.
- A verified sending domain for the From address. A test server checks the domain too.
Install
pip install sendora
The samples sit in an app named support, which python manage makes. Add "support" to INSTALLED_, and include the app’s URLs in the project’s urls, as in path(.
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 below shows.
export SENDORA_API_TOKEN=sk_…
export SENDORA_WEBHOOK_SECRET=whsec_…
Then add these lines to the project’s settings:
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_is the server key. Without it, Django stops as it starts rather than at the first send. A step that sends nothing, such asAPI_ TOKEN collectstaticin an image build, still needs a value, such asSENDORA_.API_ TOKEN=unused SENDORA_is the webhook’s signing secret. Django starts without it, and the webhook’s view then fails each delivery, as Webhooks says.WEBHOOK_ SECRET - With
APP_set toENV production, the check refuses a test key, as Develop against a test server explains.
Make the client once, in support/. It is safe across threads, so every view shares it:
from django.conf import settings
from sendora import Sendora
sendora = Sendora(settings.SENDORA_API_TOKEN)
In support/, route the views that the sections below write:
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/ sends a contact form’s message to your support address:
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/:
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’smessage_, which the log and the webhooks use.id - The tag sets the form’s mail apart in the log and in every webhook. Add metadata for ids of your own, such as an order’s.
- If Sendora refuses the mail,
send()raises aSendoraErrorwith the error code. Django then answers 500, as for any error in a view. support/is a template of your own. It renders the form withcontact .html {% csrf_, and the thanks that the view adds through Django’s messages framework.token %} - In an async view, make the client with
AsyncSendora, andawaititssend(). - When a job may send the same mail twice, pass an idempotency key of your own, as in
sendora. A retry with the same key returns the first answer and sends nothing..email .send( ..., idempotency_ key="order-1042-shipped")
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 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.
- Add the view,
support/. This one logs a hard bounce, and files each received mail as Received mail explains. If the app receives no mail, leave out thewebhooks .py InboundEventbranch and the imports it needs:
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)
- Create a webhook under the server’s Webhooks tab, with the view’s address and its last slash, such as
https://example. If the app receives mail, create it through the API instead, as Received mail says..se/ sendora/ webhook/ - Put its secret in
SENDORA_, and deploy.WEBHOOK_ SECRET
request hands the view the body as Sendora sent it, and verify_ 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 says when Sendora sends each event, and Webhook events lists their fields.
csrf_lets Sendora’s posts past Django’s CSRF check, since Sendora sends no CSRF token.exempt require_answers 405 to any other method.POST - 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 gives.
- Sendora waits only as long as Limits 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_raises awebhook WebhookVerificationErrorwithinvalid_orsignature stale_. Without the secret, it raises asignature ValueError, and Django answers 500. - A delivery can arrive more than once. Key your handling on
event, the delivery’s id, which stays the same on each attempt..id - Without the last slash, Django answers a post with a redirect, or with an error while
DEBUGis on. Either fails the attempt, as any redirect does. requesttakes a body of any size, where.read() requestrefuses one over.body DATA_, 2.5 MB by default. AnUPLOAD_ MAX_ MEMORY_ SIZE inboundevent that carries the whole mail can be larger, as Limits shows.- So cap the body’s size at your proxy, such as with nginx’s
client_. Its default of 1 MB is enough for a webhook that takes received mail by reference, as the next section creates it.max_ body_ size - If the app has
LoginRequiredMiddleware, add@login_, fromnot_ required django, to the view. Its redirect to the sign-in page would fail every attempt..contrib .auth .decorators - To roll the secret, create the new one and set
SENDORA_to it. Sendora signs each delivery with both until you delete the old one.WEBHOOK_ SECRET
Received mail
The view above files each received mail. An inbound event has the message’s inbound_, and support/ fetches the mail by it:
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_set tocontent reference. A webhook from the dashboard carries the whole mail in eachinboundevent, as Inbound explains. - Create it once, such as from
python manage, with the client that.py shell support/makes:sendora_ client .py sendora. The answer’s.webhooks .create( url=url, inbound_ content="reference") secretgoes inSENDORA_, and Sendora shows it only then.WEBHOOK_ SECRET - Without
events, the webhook takes every event butopenedandclicked, as Webhooks says. - Only a DMARC
passproves 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 says. After that,
mailis.text 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_.
- Create a test server under Servers › New server, with Testserver ticked, and a key on its API keys tab.
- Put the key in
SENDORA_on your machine, and in CI. Keep a live server’s key in production.API_ TOKEN - Send to the simulator’s addresses, such as
hardbounce@, to act out a bounce or a complaint. The message’s events show in the dashboard’s message log, as Messages and events explains.simulator .sendora .se
settings above refuses a test key where mail must arrive. With APP_ set to production, Django stops as it starts, with an ImproperlyConfigured error. Without APP_, 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 describes. support/ posts a hard bounce to the view:
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. override_ 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_, which settings reads as Django starts. assertLogs checks that the view logged the bounce.