0
# Email Backend
1
2
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.
3
4
## Capabilities
5
6
### SendgridBackend Class
7
8
Main email backend class that inherits from Django's BaseEmailBackend and implements SendGrid API integration.
9
10
```python { .api }
11
class SendgridBackend(BaseEmailBackend):
12
"""
13
Django email backend using SendGrid REST API v5+.
14
15
Supports both SendGrid v5 and v6 with automatic version detection.
16
Handles authentication, sandbox mode, tracking settings, and debugging.
17
"""
18
19
def __init__(self, *args, **kwargs):
20
"""
21
Initialize the SendGrid backend.
22
23
Parameters:
24
- api_key (str, optional): SendGrid API key, overrides settings.SENDGRID_API_KEY
25
- host (str, optional): SendGrid API host, overrides settings.SENDGRID_HOST_URL
26
- stream (io.TextIOBase, optional): Output stream for email echoing
27
- **kwargs: Additional arguments passed to BaseEmailBackend
28
29
Raises:
30
- ImproperlyConfigured: If no API key is provided in settings or kwargs
31
"""
32
33
def send_messages(self, email_messages) -> int:
34
"""
35
Send a list of EmailMessage objects via SendGrid API.
36
37
Parameters:
38
- email_messages (Iterable[EmailMessage]): Django email messages to send
39
40
Returns:
41
- int: Number of successfully sent messages
42
43
Raises:
44
- HTTPError: If SendGrid API returns an error and fail_silently=False
45
"""
46
47
def echo_to_output_stream(self, email_messages):
48
"""
49
Write email messages to output stream for debugging.
50
51
Used when SENDGRID_ECHO_TO_STDOUT setting is enabled.
52
Thread-safe implementation with proper stream management.
53
54
Parameters:
55
- email_messages (Iterable[EmailMessage]): Messages to echo
56
"""
57
```
58
59
### Backend Configuration
60
61
The backend automatically configures itself based on Django settings and initialization parameters.
62
63
```python { .api }
64
# Required settings
65
SENDGRID_API_KEY = "your-api-key" # SendGrid API key
66
67
# Optional settings with defaults
68
SENDGRID_HOST_URL = "https://api.sendgrid.com" # API endpoint
69
SENDGRID_SANDBOX_MODE_IN_DEBUG = True # Sandbox mode in DEBUG
70
SENDGRID_ECHO_TO_STDOUT = False # Debug email echoing
71
SENDGRID_TRACK_EMAIL_OPENS = True # Open tracking
72
SENDGRID_TRACK_CLICKS_HTML = True # HTML click tracking
73
SENDGRID_TRACK_CLICKS_PLAIN = True # Plain text click tracking
74
```
75
76
### Usage Examples
77
78
Basic backend setup:
79
80
```python
81
# settings.py
82
EMAIL_BACKEND = "sendgrid_backend.SendgridBackend"
83
SENDGRID_API_KEY = os.environ["SENDGRID_API_KEY"]
84
85
# Use Django's standard email API
86
from django.core.mail import send_mail
87
88
send_mail(
89
subject="Test Email",
90
message="This is a test message",
91
from_email="sender@example.com",
92
recipient_list=["recipient@example.com"]
93
)
94
```
95
96
Advanced backend initialization:
97
98
```python
99
from sendgrid_backend import SendgridBackend
100
101
# Custom backend instance with overrides
102
backend = SendgridBackend(
103
api_key="custom-api-key",
104
host="https://api.eu.sendgrid.com", # EU endpoint
105
fail_silently=False
106
)
107
108
# Send messages through custom backend
109
messages = [EmailMessage(...)]
110
sent_count = backend.send_messages(messages)
111
```
112
113
Debugging with email echoing:
114
115
```python
116
# settings.py
117
SENDGRID_ECHO_TO_STDOUT = True
118
119
# Emails will be echoed to stdout in addition to being sent
120
send_mail("Debug Test", "Message content", "from@test.com", ["to@test.com"])
121
```
122
123
### Error Handling
124
125
The backend handles various error conditions:
126
127
```python
128
from python_http_client.exceptions import HTTPError
129
from django.core.exceptions import ImproperlyConfigured
130
131
try:
132
send_mail("Test", "Content", "from@test.com", ["to@test.com"])
133
except ImproperlyConfigured:
134
# Missing or invalid API key configuration
135
pass
136
except HTTPError as e:
137
# SendGrid API error (rate limits, invalid template, etc.)
138
error_body = getattr(e, 'body', None)
139
print(f"SendGrid error: {e}, Response: {error_body}")
140
```
141
142
### Automatic Features
143
144
The backend automatically handles:
145
146
- **Version Detection**: Detects SendGrid API v5 vs v6 and adapts accordingly
147
- **Sandbox Mode**: Automatically enables sandbox mode in Django DEBUG mode (configurable)
148
- **Tracking Settings**: Applies configured tracking settings to all emails
149
- **Message ID Tracking**: Extracts and stores SendGrid message IDs in email headers
150
- **Signal Emission**: Emits Django signals for sent/failed email events