Django sends all email through an email backend. Add the small backend below and every send_mail() call, EmailMessage, and built-in email such as password resets goes through the Robust Email API. No other code changes.
Setup
pip install requests
export ROBUSTEMAIL_API_KEY="rb_test_..."
The email backend
# myproject/robustemail_backend.py
import base64
import os
import requests
from django.core.mail.backends.base import BaseEmailBackend
API = "https://robustemail.com/api/v2/emails"
# Headers that have their own field in the API
RESERVED_HEADERS = {"from", "to", "cc", "bcc", "reply-to", "subject"}
class RobustEmailBackend(BaseEmailBackend):
"""Sends Django email through the Robust Email API."""
def __init__(self, fail_silently=False, **kwargs):
super().__init__(fail_silently=fail_silently, **kwargs)
self.session = requests.Session()
self.session.headers["Authorization"] = f"Bearer {os.environ['ROBUSTEMAIL_API_KEY']}"
def send_messages(self, email_messages):
sent = 0
for message in email_messages:
try:
res = self.session.post(API, json=self.payload(message), timeout=15)
if not res.ok:
body = res.json()
raise RuntimeError(f"{body.get('name')}: {body.get('message')}")
sent += 1
except Exception:
if not self.fail_silently:
raise
return sent
def payload(self, message):
data = {"from": message.from_email, "to": message.to, "subject": message.subject}
if message.cc:
data["cc"] = message.cc
if message.bcc:
data["bcc"] = message.bcc
if message.reply_to:
data["reply_to"] = message.reply_to
if message.content_subtype == "html":
data["html"] = message.body
else:
data["text"] = message.body
for content, mimetype in getattr(message, "alternatives", []):
if mimetype == "text/html":
data["html"] = content
headers = {k: v for k, v in message.extra_headers.items() if k.lower() not in RESERVED_HEADERS}
if headers:
data["headers"] = headers
attachments = []
for attachment in message.attachments:
# Files added with attach() or attach_file() are (filename, content, mimetype)
if not isinstance(attachment, tuple):
continue
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:
data["attachments"] = attachments
return data
Turn it on
# settings.py
EMAIL_BACKEND = "myproject.robustemail_backend.RobustEmailBackend"
DEFAULT_FROM_EMAIL = "Acme <hello@acme.com>"
Send email the Django way
from django.core.mail import EmailMultiAlternatives, send_mail
from django.template.loader import render_to_string
# Plain and HTML
send_mail(
"Welcome to Acme",
"Thanks for signing up.",
None, # uses DEFAULT_FROM_EMAIL
["delivered@sandbox.robustemail.dev"],
html_message="<p>Thanks for signing up.</p>",
)
# From a template, with an attachment
html = render_to_string("emails/invoice.html", {"invoice": invoice})
msg = EmailMultiAlternatives("Your invoice #2041", "Your invoice is attached.", to=["jane@example.com"])
msg.attach_alternative(html, "text/html")
msg.attach_file("invoices/2041.pdf")
msg.send()
Password reset emails, admin error emails and anything else Django sends now go through the API too.
Tips
- Send from a background task. Calling the API inside a web request adds a network round trip. Celery, RQ or Django-Q keep requests fast.
- Test safely. With a
rb_test_key nothing is delivered; each email shows in Developers › Emails with a simulated result. In unit tests, Django swaps in its own in-memory backend automatically.