Skip to content

Commit c017206

Browse files
committed
SendGrid UUID message_id cleanup
* Update authors * Update integration tests * Add webhook message_id = smtp-id fallback test case * Test webhooks ignore smtp-id in non-fallback cases * Update docs
1 parent d8d1407 commit c017206

File tree

8 files changed

+75
-27
lines changed

8 files changed

+75
-27
lines changed

AUTHORS.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ Peter Wu
77
Charlie DeTar
88
Jonathan Baugh
99
Noel Rignon
10+
Josh Kersey
1011

1112

1213
Anymail was forked from Djrill, which included contributions from:

docs/esps/sendgrid.rst

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,14 @@ nor ``ANYMAIL_SENDGRID_API_KEY`` is set.
6565

6666
.. rubric:: SENDGRID_GENERATE_MESSAGE_ID
6767

68-
Whether Anymail should generate a Message-ID for messages sent
69-
through SendGrid, to facilitate event tracking.
70-
71-
Default ``True``. You can set to ``False`` to disable this behavior.
68+
Whether Anymail should generate a UUID for each message sent through SendGrid,
69+
to facilitate status tracking. The UUID is attached to the message as a
70+
SendGrid custom arg named "anymail_id" and made available as
71+
:attr:`anymail_status.message_id <anymail.message.AnymailMessage.anymail_status>`
72+
on the sent message.
73+
74+
Default ``True``. You can set to ``False`` to disable this behavior, in which
75+
case sent messages will have a `message_id` of ``None``.
7276
See :ref:`Message-ID quirks <sendgrid-message-id>` below.
7377

7478

@@ -162,22 +166,26 @@ Limitations and quirks
162166
Knowing a sent message's ID can be important for later queries about
163167
the message's status.
164168

165-
To work around this, Anymail by default generates a new Message-ID for each
166-
outgoing message, provides it to SendGrid, and includes it in the
167-
:attr:`~anymail.message.AnymailMessage.anymail_status`
168-
attribute after you send the message.
169-
170-
In later SendGrid API calls, you can match that Message-ID
171-
to SendGrid's ``smtp-id`` event field. (Anymail uses an additional
172-
workaround to ensure smtp-id is included in all SendGrid events,
173-
even those that aren't documented to include it.)
174-
175-
Anymail will use the domain of the message's :attr:`from_email`
176-
to generate the Message-ID. (If this isn't desired, you can supply
177-
your own Message-ID in the message's :attr:`extra_headers`.)
178-
179-
To disable all of these Message-ID workarounds, set
180-
:setting:`ANYMAIL_SENDGRID_GENERATE_MESSAGE_ID` to False in your settings.
169+
To work around this, Anymail generates a UUID for each outgoing message,
170+
provides it to SendGrid as a custom arg named "anymail_id" and makes it
171+
available as the message's
172+
:attr:`anymail_status.message_id <anymail.message.AnymailMessage.anymail_status>`
173+
attribute after sending. The same UUID will be passed to Anymail's
174+
:ref:`tracking webhooks <sendgrid-webhooks>` as
175+
:attr:`event.message_id <anymail.signals.AnymailTrackingEvent.message_id>`.
176+
177+
To disable attaching tracking UUIDs to sent messages, set
178+
:setting:`SENDGRID_GENERATE_MESSAGE_ID <ANYMAIL_SENDGRID_GENERATE_MESSAGE_ID>`
179+
to False in your Anymail settings.
180+
181+
.. versionchanged:: 3.0
182+
183+
Previously, Anymail generated a custom :mailheader:`Message-ID`
184+
header for each sent message. But SendGrid's "smtp-id" event field does
185+
not reliably reflect this header, which complicates status tracking.
186+
(For compatibility with messages sent in earlier versions, Anymail's
187+
webhook :attr:`message_id` will fall back to "smtp-id" when "anymail_id"
188+
isn't present.)
181189

182190
**Single Reply-To**
183191
SendGrid's v3 API only supports a single Reply-To address (and blocks

tests/test_sendgrid_backend.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,7 @@ def test_metadata(self):
341341
self.message.metadata = {'user_id': "12345", 'items': 6, 'float': 98.6, 'long': longtype(123)}
342342
self.message.send()
343343
data = self.get_api_call_json()
344-
data['custom_args'].pop('anymail_id', None) # remove Message-ID we added as tracking workaround
344+
data['custom_args'].pop('anymail_id', None) # remove anymail_id we added for tracking
345345
self.assertEqual(data['custom_args'], {'user_id': "12345",
346346
'items': "6", # int converted to a string,
347347
'float': "98.6", # float converted to a string (watch binary rounding!)
@@ -581,6 +581,13 @@ def test_send_attaches_anymail_status(self):
581581
msg.anymail_status.message_id)
582582
self.assertEqual(msg.anymail_status.esp_response.content, self.DEFAULT_RAW_RESPONSE)
583583

584+
@override_settings(ANYMAIL_SENDGRID_GENERATE_MESSAGE_ID=False)
585+
def test_disable_generate_message_id(self):
586+
msg = mail.EmailMessage('Subject', 'Message', '[email protected]', ['[email protected]'],)
587+
msg.send()
588+
self.assertIsNone(msg.anymail_status.message_id)
589+
self.assertIsNone(msg.anymail_status.recipients['[email protected]'].message_id)
590+
584591
# noinspection PyUnresolvedReferences
585592
def test_send_failed_anymail_status(self):
586593
""" If the send fails, anymail_status should contain initial values"""

tests/test_sendgrid_integration.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def test_simple_send(self):
5454
message_id = anymail_status.recipients['[email protected]'].message_id
5555

5656
self.assertEqual(sent_status, 'queued') # SendGrid always queues
57-
self.assertRegex(message_id, r'\<.+@example\.com\>') # should use from_email's domain
57+
self.assertUUIDIsValid(message_id) # Anymail generates a UUID tracking id
5858
self.assertEqual(anymail_status.status, {sent_status}) # set of all recipient statuses
5959
self.assertEqual(anymail_status.message_id, message_id)
6060

tests/test_sendgrid_v2_backend.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,7 @@ def test_metadata(self):
349349
self.message.metadata = {'user_id': "12345", 'items': 6}
350350
self.message.send()
351351
smtpapi = self.get_smtpapi()
352-
smtpapi['unique_args'].pop('anymail_id', None) # remove Message-ID we added as tracking workaround
352+
smtpapi['unique_args'].pop('anymail_id', None) # remove anymail_id we added for tracking
353353
self.assertEqual(smtpapi['unique_args'], {'user_id': "12345", 'items': 6})
354354

355355
def test_send_at(self):

tests/test_sendgrid_v2_integration.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def test_simple_send(self):
5555
message_id = anymail_status.recipients['[email protected]'].message_id
5656

5757
self.assertEqual(sent_status, 'queued') # SendGrid always queues
58-
self.assertRegex(message_id, r'\<.+@example\.com\>') # should use from_email's domain
58+
self.assertUUIDIsValid(message_id) # Anymail generates a UUID tracking id
5959
self.assertEqual(anymail_status.status, {sent_status}) # set of all recipient statuses
6060
self.assertEqual(anymail_status.message_id, message_id)
6161

tests/test_sendgrid_webhooks.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ def test_processed_event(self):
2424
"email": "[email protected]",
2525
"timestamp": 1461095246,
2626
"anymail_id": "3c2f4df8-c6dd-4cd2-9b91-6582b81a0349",
27+
"smtp-id": "<[email protected]>",
2728
"sg_event_id": "ZyjAM5rnQmuI1KFInHQ3Nw",
2829
"sg_message_id": "wrfRRvF7Q0GgwUo2CvDmEA.filter0425p1mdw1.13037.57168B4A1D.0",
2930
"event": "processed",
@@ -51,6 +52,7 @@ def test_delivered_event(self):
5152
raw_events = [{
5253
"ip": "167.89.17.173",
5354
"response": "250 2.0.0 OK 1461095248 m143si2210036ioe.159 - gsmtp ",
55+
"smtp-id": "<[email protected]>",
5456
"sg_event_id": "nOSv8m0eTQ-vxvwNwt3fZQ",
5557
"sg_message_id": "wrfRRvF7Q0GgwUo2CvDmEA.filter0425p1mdw1.13037.57168B4A1D.0",
5658
"tls": 1,
@@ -81,6 +83,7 @@ def test_dropped_invalid_event(self):
8183
"email": "invalid@invalid",
8284
"anymail_id": "c74002d9-7ccb-4f67-8b8c-766cec03c9a6",
8385
"timestamp": 1461095250,
86+
"smtp-id": "<[email protected]>",
8487
"sg_event_id": "3NPOePGOTkeM_U3fgWApfg",
8588
"sg_message_id": "filter0093p1las1.9128.5717FB8127.0",
8689
"reason": "Invalid",
@@ -106,6 +109,7 @@ def test_dropped_unsubscribed_event(self):
106109
"email": "[email protected]",
107110
"anymail_id": "a36ec0f9-aabe-45c7-9a84-3e17afb5cb65",
108111
"timestamp": 1461095250,
112+
"smtp-id": "<[email protected]>",
109113
"sg_event_id": "oxy9OLwMTAy5EsuZn1qhIg",
110114
"sg_message_id": "filter0199p1las1.4745.5717FB6F5.0",
111115
"reason": "Unsubscribed Address",
@@ -130,6 +134,7 @@ def test_bounce_event(self):
130134
raw_events = [{
131135
"ip": "167.89.17.173",
132136
"status": "5.1.1",
137+
"smtp-id": "<[email protected]>",
133138
"sg_event_id": "lC0Rc-FuQmKbnxCWxX1jRQ",
134139
"reason": "550 5.1.1 The email account that you tried to reach does not exist.",
135140
"sg_message_id": "Lli-03HcQ5-JLybO9fXsJg.filter0077p1las1.21536.5717FC482.0",
@@ -157,6 +162,7 @@ def test_bounce_event(self):
157162
def test_deferred_event(self):
158163
raw_events = [{
159164
"response": "Email was deferred due to the following reason(s): [IPs were throttled by recipient server]",
165+
"smtp-id": "<[email protected]>",
160166
"sg_event_id": "b_syL5UiTvWC_Ky5L6Bs5Q",
161167
"sg_message_id": "u9Gvi3mzT6iC2poAb58_qQ.filter0465p1mdw1.8054.5718271B40.0",
162168
"event": "deferred",
@@ -232,3 +238,29 @@ def test_click_event(self):
232238
self.assertEqual(event.recipient, "[email protected]")
233239
self.assertEqual(event.user_agent, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36")
234240
self.assertEqual(event.click_url, "http://www.example.com")
241+
242+
def test_compatibility_message_id_from_smtp_id(self):
243+
# Prior to v3.0, Anymail tried to use a custom Message-ID header as
244+
# the `message_id`, and relied on SendGrid passing that to webhooks as
245+
# 'smtp-id'. Make sure webhooks extract message_id for messages sent
246+
# with earlier Anymail versions. (See issue #108.)
247+
raw_events = [{
248+
"ip": "167.89.17.173",
249+
"response": "250 2.0.0 OK 1461095248 m143si2210036ioe.159 - gsmtp ",
250+
"smtp-id": "<[email protected]>",
251+
"sg_event_id": "nOSv8m0eTQ-vxvwNwt3fZQ",
252+
"sg_message_id": "wrfRRvF7Q0GgwUo2CvDmEA.filter0425p1mdw1.13037.57168B4A1D.0",
253+
"tls": 1,
254+
"event": "delivered",
255+
"email": "[email protected]",
256+
"timestamp": 1461095250,
257+
}]
258+
response = self.client.post('/anymail/sendgrid/tracking/',
259+
content_type='application/json', data=json.dumps(raw_events))
260+
self.assertEqual(response.status_code, 200)
261+
kwargs = self.assert_handler_called_once_with(self.tracking_handler, sender=SendGridTrackingWebhookView,
262+
event=ANY, esp_name='SendGrid')
263+
event = kwargs['event']
264+
self.assertIsInstance(event, AnymailTrackingEvent)
265+
self.assertEqual(event.message_id, "<[email protected]>")
266+
self.assertEqual(event.metadata, {}) # smtp-id not left in metadata

tests/utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -166,13 +166,13 @@ def assertEqualIgnoringHeaderFolding(self, first, second, msg=None):
166166
second = rfc822_unfold(second)
167167
self.assertEqual(first, second, msg)
168168

169-
def assertUUIDIsValid(self, uuid_str, version=4):
169+
def assertUUIDIsValid(self, uuid_str, msg=None, version=4):
170170
"""Assert the uuid_str evaluates to a valid UUID"""
171171
try:
172172
uuid.UUID(uuid_str, version=version)
173173
except (ValueError, AttributeError, TypeError):
174-
return False
175-
return True
174+
raise self.failureException(
175+
msg or "%r is not a valid UUID" % uuid_str)
176176

177177

178178
# Backported from Python 3.4

0 commit comments

Comments
 (0)