Skip to content

Commit 5d41708

Browse files
committed
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 #14 (comment)
1 parent c9dfec6 commit 5d41708

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

anymail/backends/sendgrid.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,14 @@ def serialize_data(self):
9696

9797
self.build_merge_data()
9898
if self.merge_data is not None:
99-
# Must *also* set smtpapi 'to' field so SG does batch send
100-
# (else all recipients would see each other's emails)
99+
# Move the 'to' recipients to smtpapi, so SG does batch send
100+
# (else all recipients would see each other's emails).
101+
# Regular 'to' must still be a valid email (even though "ignored")...
102+
# we use the from_email as recommended by SG support
103+
# (See https://github.com/anymail/django-anymail/pull/14#issuecomment-220231250)
101104
self.smtpapi['to'] = [email.address for email in self.to_list]
105+
self.data['to'] = [self.data['from']]
106+
self.data['toname'] = [self.data.get('fromname', " ")]
102107

103108
# Serialize x-smtpapi to json:
104109
if len(self.smtpapi) > 0:

tests/test_sendgrid_backend.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,7 @@ def test_template_id(self):
413413
})
414414

415415
def test_merge_data(self):
416+
self.message.from_email = '[email protected]'
416417
self.message.to = ['[email protected]', 'Bob <[email protected]>']
417418
# SendGrid template_id is not required to use merge.
418419
# You can just supply template content as the message (e.g.):
@@ -431,10 +432,12 @@ def test_merge_data(self):
431432

432433
data = self.get_api_call_data()
433434
smtpapi = self.get_smtpapi()
434-
# For batch send, must set both to+toname *and* smtpapi['to']:
435-
self.assertEqual(data['toname'], [' ', 'Bob'])
436-
self.assertEqual(data['to'], ['[email protected]', '[email protected]'])
435+
# For batch send, smtpapi['to'] gets real recipient list;
436+
# normal 'to' is not used (but must be valid, so we substitute the from_email):
437+
self.assertEqual(data['to'], ['[email protected]'])
438+
self.assertEqual(data['toname'], [' ']) # empty string if no name in from_email
437439
self.assertEqual(smtpapi['to'], ['[email protected]', 'Bob <[email protected]>'])
440+
# smtpapi['sub'] values should be in to-list order:
438441
self.assertEqual(smtpapi['sub'], {
439442
':name': ["Alice", "Bob"],
440443
':group': ["Developers", ":group"], # missing value gets replaced with var name...

0 commit comments

Comments
 (0)