Django email backend implementation compatible with SendGrid API v5+ for seamless email delivery integration
—
The core SendGrid email backend implementation that integrates with Django's email system. This backend replaces Django's default SMTP backend with SendGrid's REST API for improved deliverability, tracking, and advanced email features.
Main email backend class that inherits from Django's BaseEmailBackend and implements SendGrid API integration.
class SendgridBackend(BaseEmailBackend):
"""
Django email backend using SendGrid REST API v5+.
Supports both SendGrid v5 and v6 with automatic version detection.
Handles authentication, sandbox mode, tracking settings, and debugging.
"""
def __init__(self, *args, **kwargs):
"""
Initialize the SendGrid backend.
Parameters:
- api_key (str, optional): SendGrid API key, overrides settings.SENDGRID_API_KEY
- host (str, optional): SendGrid API host, overrides settings.SENDGRID_HOST_URL
- stream (io.TextIOBase, optional): Output stream for email echoing
- **kwargs: Additional arguments passed to BaseEmailBackend
Raises:
- ImproperlyConfigured: If no API key is provided in settings or kwargs
"""
def send_messages(self, email_messages) -> int:
"""
Send a list of EmailMessage objects via SendGrid API.
Parameters:
- email_messages (Iterable[EmailMessage]): Django email messages to send
Returns:
- int: Number of successfully sent messages
Raises:
- HTTPError: If SendGrid API returns an error and fail_silently=False
"""
def echo_to_output_stream(self, email_messages):
"""
Write email messages to output stream for debugging.
Used when SENDGRID_ECHO_TO_STDOUT setting is enabled.
Thread-safe implementation with proper stream management.
Parameters:
- email_messages (Iterable[EmailMessage]): Messages to echo
"""The backend automatically configures itself based on Django settings and initialization parameters.
# Required settings
SENDGRID_API_KEY = "your-api-key" # SendGrid API key
# Optional settings with defaults
SENDGRID_HOST_URL = "https://api.sendgrid.com" # API endpoint
SENDGRID_SANDBOX_MODE_IN_DEBUG = True # Sandbox mode in DEBUG
SENDGRID_ECHO_TO_STDOUT = False # Debug email echoing
SENDGRID_TRACK_EMAIL_OPENS = True # Open tracking
SENDGRID_TRACK_CLICKS_HTML = True # HTML click tracking
SENDGRID_TRACK_CLICKS_PLAIN = True # Plain text click trackingBasic backend setup:
# settings.py
EMAIL_BACKEND = "sendgrid_backend.SendgridBackend"
SENDGRID_API_KEY = os.environ["SENDGRID_API_KEY"]
# Use Django's standard email API
from django.core.mail import send_mail
send_mail(
subject="Test Email",
message="This is a test message",
from_email="sender@example.com",
recipient_list=["recipient@example.com"]
)Advanced backend initialization:
from sendgrid_backend import SendgridBackend
# Custom backend instance with overrides
backend = SendgridBackend(
api_key="custom-api-key",
host="https://api.eu.sendgrid.com", # EU endpoint
fail_silently=False
)
# Send messages through custom backend
messages = [EmailMessage(...)]
sent_count = backend.send_messages(messages)Debugging with email echoing:
# settings.py
SENDGRID_ECHO_TO_STDOUT = True
# Emails will be echoed to stdout in addition to being sent
send_mail("Debug Test", "Message content", "from@test.com", ["to@test.com"])The backend handles various error conditions:
from python_http_client.exceptions import HTTPError
from django.core.exceptions import ImproperlyConfigured
try:
send_mail("Test", "Content", "from@test.com", ["to@test.com"])
except ImproperlyConfigured:
# Missing or invalid API key configuration
pass
except HTTPError as e:
# SendGrid API error (rate limits, invalid template, etc.)
error_body = getattr(e, 'body', None)
print(f"SendGrid error: {e}, Response: {error_body}")The backend automatically handles:
Install with Tessl CLI
npx tessl i tessl/pypi-django-sendgrid-v5