Skip to content

Commit 8e43f29

Browse files
committed
Workaround missing smtp-id in SendGrid tracking.
* Add smtp-id in unique_args (metadata), to ensure it shows up in click and open events. * Add SENDGRID_GENERATE_MESSAGE_ID setting, default True, to control auto-Message-ID behavior. * Document it.
1 parent ca7dbdc commit 8e43f29

File tree

3 files changed

+55
-8
lines changed

3 files changed

+55
-8
lines changed

anymail/backends/sendgrid.py

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from email.utils import unquote
2+
13
from django.core.exceptions import ImproperlyConfigured
24
from django.core.mail import make_msgid
35
from requests.structures import CaseInsensitiveDict
@@ -9,7 +11,6 @@
911
from .base_requests import AnymailRequestsBackend, RequestsPayload
1012

1113

12-
1314
class SendGridBackend(AnymailRequestsBackend):
1415
"""
1516
SendGrid API Email Backend
@@ -27,6 +28,8 @@ def __init__(self, **kwargs):
2728
"SENDGRID_PASSWORD in your Django ANYMAIL settings."
2829
)
2930

31+
self.generate_message_id = get_anymail_setting('SENDGRID_GENERATE_MESSAGE_ID', default=True)
32+
3033
# This is SendGrid's Web API v2 (because the Web API v3 doesn't support sending)
3134
api_url = get_anymail_setting("SENDGRID_API_URL", "https://api.sendgrid.com/api/")
3235
if not api_url.endswith("/"):
@@ -56,6 +59,7 @@ class SendGridPayload(RequestsPayload):
5659

5760
def __init__(self, message, defaults, backend, *args, **kwargs):
5861
self.all_recipients = [] # used for backend.parse_recipient_status
62+
self.generate_message_id = backend.generate_message_id
5963
self.message_id = None # Message-ID -- assigned in serialize_data unless provided in headers
6064
self.smtpapi = {} # SendGrid x-smtpapi field
6165

@@ -76,6 +80,9 @@ def get_api_endpoint(self):
7680
def serialize_data(self):
7781
"""Performs any necessary serialization on self.data, and returns the result."""
7882

83+
if self.generate_message_id:
84+
self.ensure_message_id()
85+
7986
# Serialize x-smtpapi to json:
8087
if len(self.smtpapi) > 0:
8188
# If esp_extra was also used to set x-smtpapi, need to merge it
@@ -86,16 +93,26 @@ def serialize_data(self):
8693
elif "x-smtpapi" in self.data:
8794
self.data["x-smtpapi"] = self.serialize_json(self.data["x-smtpapi"])
8895

89-
# Add our own message_id, and serialize extra headers to json:
96+
# Serialize extra headers to json:
9097
headers = self.data["headers"]
91-
try:
92-
self.message_id = headers["Message-ID"]
93-
except KeyError:
94-
self.message_id = headers["Message-ID"] = self.make_message_id()
9598
self.data["headers"] = self.serialize_json(dict(headers.items()))
9699

97100
return self.data
98101

102+
def ensure_message_id(self):
103+
"""Ensure message has a known Message-ID for later event tracking"""
104+
headers = self.data["headers"]
105+
if "Message-ID" not in headers:
106+
# Only make our own if caller hasn't already provided one
107+
headers["Message-ID"] = self.make_message_id()
108+
self.message_id = headers["Message-ID"]
109+
110+
# Workaround for missing message ID (smtp-id) in SendGrid engagement events
111+
# (click and open tracking): because unique_args get merged into the raw event
112+
# record, we can supply the 'smtp-id' field for any events missing it.
113+
# Must use the unquoted (no <angle brackets>) version to match other SendGrid APIs.
114+
self.smtpapi.setdefault('unique_args', {})['smtp-id'] = unquote(self.message_id)
115+
99116
def make_message_id(self):
100117
"""Returns a Message-ID that could be used for this payload
101118

docs/esps/sendgrid.rst

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,17 @@ nor ``ANYMAIL_SENDGRID_USERNAME`` is set.
7878
.. _SendGrid credentials settings: https://app.sendgrid.com/settings/credentials
7979

8080

81+
.. setting:: ANYMAIL_SENDGRID_GENERATE_MESSAGE_ID
82+
83+
.. rubric:: SENDGRID_GENERATE_MESSAGE_ID
84+
85+
Whether Anymail should generate a Message-ID for messages sent
86+
through SendGrid, to facilitate event tracking.
87+
88+
Default ``True``. You can set to ``False`` to disable this behavior.
89+
See :ref:`Message-ID quirks <sendgrid-message-id>` below.
90+
91+
8192
.. setting:: ANYMAIL_SENDGRID_API_URL
8293

8394
.. rubric:: SENDGRID_API_URL
@@ -132,23 +143,30 @@ Limitations and quirks
132143
make sure each one has a unique, non-empty filename.
133144

134145

146+
.. _sendgrid-message-id:
147+
135148
**Message-ID**
136149
SendGrid does not return any sort of unique id from its send API call.
137150
Knowing a sent message's ID can be important for later queries about
138151
the message's status.
139152

140-
To work around this, Anymail generates a new Message-ID for each
153+
To work around this, Anymail by default generates a new Message-ID for each
141154
outgoing message, provides it to SendGrid, and includes it in the
142155
:attr:`~anymail.message.AnymailMessage.anymail_status`
143156
attribute after you send the message.
144157

145158
In later SendGrid API calls, you can match that Message-ID
146-
to SendGrid's ``smtp-id`` event field.
159+
to SendGrid's ``smtp-id`` event field. (Anymail uses an additional
160+
workaround to ensure smtp-id is included in all SendGrid events,
161+
even those that aren't documented to include it.)
147162

148163
Anymail will use the domain of the message's :attr:`from_email`
149164
to generate the Message-ID. (If this isn't desired, you can supply
150165
your own Message-ID in the message's :attr:`extra_headers`.)
151166

167+
To disable all of these Message-ID workarounds, set
168+
:setting:`ANYMAIL_SENDGRID_GENERATE_MESSAGE_ID` to False in your settings.
169+
152170

153171
**Invalid Addresses**
154172
SendGrid will accept *and send* just about anything as

tests/test_sendgrid_backend.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,9 @@ def test_send_mail(self):
6464
# make sure backend assigned a Message-ID for event tracking
6565
email_headers = json.loads(data['headers'])
6666
self.assertRegex(email_headers['Message-ID'], r'\<.+@sender\.example\.com\>') # id uses from_email's domain
67+
# make sure we added the unquoted Message-ID to unique_args for event notification
68+
smtpapi = self.get_smtpapi()
69+
self.assertEqual(email_headers['Message-ID'], '<{}>'.format(smtpapi['unique_args']['smtp-id']))
6770

6871
@override_settings(ANYMAIL={'SENDGRID_USERNAME': 'sg_username', 'SENDGRID_PASSWORD': 'sg_password'})
6972
def test_user_pass_auth(self):
@@ -124,6 +127,10 @@ def test_email_message(self):
124127
'Reply-To': '[email protected]',
125128
'X-MyHeader': 'my value',
126129
})
130+
# make sure custom Message-ID also added to unique_args
131+
self.assertJSONEqual(data['x-smtpapi'], {
132+
'unique_args': {'smtp-id': '[email protected]'}
133+
})
127134

128135
def test_html_message(self):
129136
text_content = 'This is an important message.'
@@ -347,6 +354,7 @@ def test_metadata(self):
347354
self.message.metadata = {'user_id': "12345", 'items': 6}
348355
self.message.send()
349356
smtpapi = self.get_smtpapi()
357+
smtpapi['unique_args'].pop('smtp-id', None) # remove Message-ID we added as tracking workaround
350358
self.assertEqual(smtpapi['unique_args'], {'user_id': "12345", 'items': 6})
351359

352360
def test_send_at(self):
@@ -401,6 +409,7 @@ def test_tracking(self):
401409
self.assertEqual(smtpapi['filters']['clicktrack'], {'settings': {'enable': 1}})
402410
self.assertEqual(smtpapi['filters']['opentrack'], {'settings': {'enable': 0}})
403411

412+
@override_settings(ANYMAIL_SENDGRID_GENERATE_MESSAGE_ID=False) # else we force unique_args
404413
def test_default_omits_options(self):
405414
"""Make sure by default we don't send any ESP-specific options.
406415
@@ -508,6 +517,7 @@ def test_send_defaults(self):
508517
data = self.get_api_call_data()
509518
smtpapi = self.get_smtpapi()
510519
# All these values came from ANYMAIL_SEND_DEFAULTS:
520+
smtpapi['unique_args'].pop('smtp-id', None) # remove Message-ID we added as tracking workaround
511521
self.assertEqual(smtpapi['unique_args'], {'global': 'globalvalue', 'other': 'othervalue'})
512522
self.assertEqual(smtpapi['category'], ['globaltag'])
513523
self.assertEqual(smtpapi['filters']['clicktrack']['settings']['enable'], 1)
@@ -525,6 +535,7 @@ def test_merge_message_with_send_defaults(self):
525535
data = self.get_api_call_data()
526536
smtpapi = self.get_smtpapi()
527537
# All these values came from ANYMAIL_SEND_DEFAULTS + message.*:
538+
smtpapi['unique_args'].pop('smtp-id', None) # remove Message-ID we added as tracking workaround
528539
self.assertEqual(smtpapi['unique_args'], {
529540
'global': 'globalvalue',
530541
'message': 'messagevalue', # additional metadata
@@ -547,6 +558,7 @@ def test_esp_send_defaults(self):
547558
data = self.get_api_call_data()
548559
smtpapi = self.get_smtpapi()
549560
# All these values came from ANYMAIL_SEND_DEFAULTS plus ANYMAIL_SENDGRID_SEND_DEFAULTS:
561+
smtpapi['unique_args'].pop('smtp-id', None) # remove Message-ID we added as tracking workaround
550562
self.assertEqual(smtpapi['unique_args'], {'esp': 'espvalue'}) # entire metadata overridden
551563
self.assertCountEqual(smtpapi['category'], ['esptag']) # entire tags overridden
552564
self.assertEqual(smtpapi['filters']['clicktrack']['settings']['enable'], 1) # no override

0 commit comments

Comments
 (0)