From 5d417080eef983ed8bcc2c158673f431531df725 Mon Sep 17 00:00:00 2001 From: medmunds Date: Wed, 1 Jun 2016 08:05:51 -0700 Subject: [PATCH] SendGrid: set `to` to `from` in batch send. Set ignored (but required-valid) `to` field to the from_email for batch send with merge_data. See https://github.com/anymail/django-anymail/pull/14#issuecomment-220231250 --- anymail/backends/sendgrid.py | 9 +++++++-- tests/test_sendgrid_backend.py | 9 ++++++--- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/anymail/backends/sendgrid.py b/anymail/backends/sendgrid.py index 9bf2232..b7e6f44 100644 --- a/anymail/backends/sendgrid.py +++ b/anymail/backends/sendgrid.py @@ -96,9 +96,14 @@ class SendGridPayload(RequestsPayload): self.build_merge_data() if self.merge_data is not None: - # Must *also* set smtpapi 'to' field so SG does batch send - # (else all recipients would see each other's emails) + # Move the 'to' recipients to smtpapi, so SG does batch send + # (else all recipients would see each other's emails). + # Regular 'to' must still be a valid email (even though "ignored")... + # we use the from_email as recommended by SG support + # (See https://github.com/anymail/django-anymail/pull/14#issuecomment-220231250) self.smtpapi['to'] = [email.address for email in self.to_list] + self.data['to'] = [self.data['from']] + self.data['toname'] = [self.data.get('fromname', " ")] # Serialize x-smtpapi to json: if len(self.smtpapi) > 0: diff --git a/tests/test_sendgrid_backend.py b/tests/test_sendgrid_backend.py index 23e1ef2..a9e5fe7 100644 --- a/tests/test_sendgrid_backend.py +++ b/tests/test_sendgrid_backend.py @@ -413,6 +413,7 @@ class SendGridBackendAnymailFeatureTests(SendGridBackendMockAPITestCase): }) def test_merge_data(self): + self.message.from_email = 'from@example.com' self.message.to = ['alice@example.com', 'Bob '] # SendGrid template_id is not required to use merge. # You can just supply template content as the message (e.g.): @@ -431,10 +432,12 @@ class SendGridBackendAnymailFeatureTests(SendGridBackendMockAPITestCase): data = self.get_api_call_data() smtpapi = self.get_smtpapi() - # For batch send, must set both to+toname *and* smtpapi['to']: - self.assertEqual(data['toname'], [' ', 'Bob']) - self.assertEqual(data['to'], ['alice@example.com', 'bob@example.com']) + # For batch send, smtpapi['to'] gets real recipient list; + # normal 'to' is not used (but must be valid, so we substitute the from_email): + self.assertEqual(data['to'], ['from@example.com']) + self.assertEqual(data['toname'], [' ']) # empty string if no name in from_email self.assertEqual(smtpapi['to'], ['alice@example.com', 'Bob ']) + # smtpapi['sub'] values should be in to-list order: self.assertEqual(smtpapi['sub'], { ':name': ["Alice", "Bob"], ':group': ["Developers", ":group"], # missing value gets replaced with var name...