How do you implement a custom email backend in Django (django.core.mail.backends.base.BaseEmailBackend) using requests / httpx to send emails through AutoSend?
Django Custom Email Backend for AutoSend
By writing a custom BaseEmailBackend, all calls to django.core.mail.send_mail() and EmailMultiAlternatives seamlessly route through AutoSend.
1. Custom Backend (myapp/email_backend.py)
import requests
from django.conf import settings
from django.core.mail.backends.base import BaseEmailBackend
class AutoSendEmailBackend(BaseEmailBackend):
def __init__(self, api_key=None, fail_silently=False, **kwargs):
super().__init__(fail_silently=fail_silently, **kwargs)
self.api_key = api_key or getattr(settings, "AUTOSEND_API_KEY", "")
self.api_url = "https://api.autosend.com/v1/mails/send"
def send_messages(self, email_messages):
if not email_messages:
return 0
sent_count = 0
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
}
for msg in email_messages:
payload = {
"from": msg.from_email,
"to": msg.to,
"subject": msg.subject,
"text": msg.body,
}
# Check for alternative HTML parts
if hasattr(msg, "alternatives"):
for content, mimetype in msg.alternatives:
if mimetype == "text/html":
payload["html"] = content
break
try:
res = requests.post(self.api_url, json=payload, headers=headers, timeout=10)
res.raise_for_status()
sent_count += 1
except Exception as e:
if not self.fail_silently:
raise e
return sent_count
2. Configure settings.py
EMAIL_BACKEND = 'myapp.email_backend.AutoSendEmailBackend'
AUTOSEND_API_KEY = os.environ.get('AUTOSEND_API_KEY')
DEFAULT_FROM_EMAIL = 'Notifications <notifications@yourdomain.com>'