Django

Django email with Hermaily

Django ships an SMTP email backend, so send_mail, password resets and the error emails to ADMINS go through Hermaily with a few settings. Then a webhook view tells you about deliveries, bounces and complaints.

  • SMTP smtp.hermaily.com:587
  • EMAIL_USE_TLS = True
  • Django 4.2 LTS and later

Before you start

Three things from Hermaily before the first message:

  1. An account. Create one (there is a free plan). New accounts are reviewed before they can send; you can set everything up in the meantime.
  2. A verified domain. In Domains, the assistant gives you the DKIM, SPF and DMARC records and checks they are published. You can only send from addresses on that domain or its subdomains.
  3. An API key for that domain, created in API keys. It starts with hm_ and is shown only once: keep it in your secrets manager or in the environment, never in the repository. The same key is the SMTP password; the username is apikey.

Configuration

In settings.py, with the key read from the environment:

Python · settings.py
# settings.py
import os

EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.hermaily.com"
EMAIL_PORT = 587
EMAIL_USE_TLS = True          # STARTTLS on 587
EMAIL_HOST_USER = "apikey"
EMAIL_HOST_PASSWORD = os.environ["HERMAILY_API_KEY"]
EMAIL_TIMEOUT = 10
DEFAULT_FROM_EMAIL = "Acme <hello@acme.example>"
SERVER_EMAIL = "errors@acme.example"   # sender of the error emails to ADMINS

# Port 465 instead: EMAIL_PORT = 465, EMAIL_USE_SSL = True and EMAIL_USE_TLS = False (never both).

DEFAULT_FROM_EMAIL and SERVER_EMAIL must be on your verified domain; Hermaily rejects any other sender. Keep HERMAILY_API_KEY out of the repository (environment, or your secrets manager).

Send a message

Check the settings with Django's own command, which sends a test message:

shell
python manage.py sendtestemail you@example.com

Then, in your code:

Python
from django.core.mail import EmailMultiAlternatives, send_mail

send_mail(
    "Your order is on its way",
    "Hi Lucía, order 48213 has shipped.",
    None,                      # None = DEFAULT_FROM_EMAIL
    ["lucia@example.com"],
)

# HTML and text, with extra headers:
msg = EmailMultiAlternatives(
    subject="Your order is on its way",
    body="Hi Lucía, order 48213 has shipped.",
    to=["lucia@example.com"],
    headers={"X-Entity-Ref-ID": "48213"},
)
msg.attach_alternative("<p>Hi Lucía, order <b>48213</b> has shipped.</p>", "text/html")
msg.send()

For a newsletter, add "X-Hermaily-Stream": "broadcast" to headers and send one message per recipient: Hermaily adds the one-click unsubscribe headers. Large sends are better made from a task queue (Celery, RQ, Django-Q) than inside a request.

Events and webhooks

Every message gets an id: over SMTP it comes in the server's reply to the message (250 2.0.0 Ok: queued as <id>). Accepted means queued, not delivered. To know what happened next:

  • Dashboard. Messages lists each message with its events: delivered, deferred, bounced, complaint, opened, clicked.
  • API. GET https://api.hermaily.com/v1/messages/{id} returns the current status and every event, oldest first (see looking up a message).
  • Webhooks. In Webhooks, add your URL (https and public) and the events you want. Hermaily makes one POST per event, signed with X-Hermaily-Signature: t=<unix>,v1=<hex>, where v1 is HMAC-SHA256(secret, t + "." + body) over the raw body. Answer any 2xx within 10 seconds; otherwise it is retried for about a day and a half. Delivery is at least once, so discard duplicates by the event id. The Test button sends a sample event to check your receiver.

A receiver that checks the signature:

Python · Django
# views.py
import hashlib, hmac, json, time

from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST


def verify_hermaily(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
    parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
    t = int(parts.get("t", "0") or 0)
    if abs(time.time() - t) > tolerance:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts.get("v1", ""))


@csrf_exempt
@require_POST
def hermaily_webhook(request):
    header = request.headers.get("X-Hermaily-Signature", "")
    if not verify_hermaily(request.body, header, settings.HERMAILY_WEBHOOK_SECRET):
        return HttpResponse(status=401)
    event = json.loads(request.body)
    # event["type"]: "delivery", "bounce", "complaint"...; queue the work, discard duplicates by event["id"].
    return HttpResponse(status=204)

Event types: send, delivery, delivery_delay, bounce, complaint, reject, rendering_failure, open, click and unsubscribe (opens and clicks only with tracking on). Permanent bounces, complaints and unsubscribes are suppressed automatically, so you do not need to keep your own list for that. Payload, fields and signature details are in the webhook documentation.

Route it in urls.py with path("webhooks/hermaily/", hermaily_webhook) and put the secret in HERMAILY_WEBHOOK_SECRET.

Troubleshooting

The errors you are most likely to see, with what they mean. The full list is in errors and limits.

ValueError: EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive

Turn on only one: EMAIL_USE_TLS with port 587, or EMAIL_USE_SSL with port 465. With EMAIL_USE_TLS on port 465, the connection hangs until EMAIL_TIMEOUT.

535 5.7.8: authentication failed

The password must be the whole API key (hm_...), copied without spaces and not revoked. The username can be anything; use apikey. After many failed attempts from the same IP, logins are refused for a few minutes.

The connection hangs or times out

Your host blocks outgoing SMTP. Try port 465 with implicit TLS instead of 587. If both are closed, send through the HTTP API on port 443 (see the Python guide).

550 5.7.1: the message is refused

The account cannot send right now (pending approval, paused, or new terms to accept), the key is restricted to the other stream, or the From address is not on the key's domain. Over the API this is 403 forbidden.

550 5.6.0: the message is rejected

Usually the From domain is not verified yet, there are more recipients than your plan allows (5 on Free, 50 on paid plans) or the message is too large. Over the API this is 422 validation, with the reason in the message.

451 4.7.1: try again later

The plan's per-minute limit or a new account's daily warm-up limit. It is temporary: retry later (over the API, 429 rate_limited). 552 5.3.4 means the monthly quota of the Free plan is used up (402 quota_exceeded).

Send your first message today

Create the account, verify your domain and paste the key. The free plan is enough to try it.

Create a free account