From b03d5002955256c4b3ed7cfae5150eb79c0eb97e Mon Sep 17 00:00:00 2001 From: Jon Dufresne Date: Sat, 9 Dec 2017 06:42:46 -0800 Subject: [PATCH] Fixed #28971 -- Made EmailMessage.message() set Cc from headers dict if it exists. --- django/core/mail/message.py | 18 ++++++++++++++---- tests/mail/tests.py | 7 +++++++ 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/django/core/mail/message.py b/django/core/mail/message.py index 9c68b8be6d..5052b5c90e 100644 --- a/django/core/mail/message.py +++ b/django/core/mail/message.py @@ -255,10 +255,8 @@ class EmailMessage: msg['Subject'] = self.subject msg['From'] = self.extra_headers.get('From', self.from_email) msg['To'] = self.extra_headers.get('To', ', '.join(map(str, self.to))) - if self.cc: - msg['Cc'] = ', '.join(str(cc) for cc in self.cc) - if self.reply_to: - msg['Reply-To'] = self.extra_headers.get('Reply-To', ', '.join(str(r) for r in self.reply_to)) + self._set_list_header_if_not_empty(msg, 'Cc', self.cc) + self._set_list_header_if_not_empty(msg, 'Reply-To', self.reply_to) # Email header names are case-insensitive (RFC 2045), so we have to # accommodate that when doing comparisons. @@ -408,6 +406,18 @@ class EmailMessage: filename=filename) return attachment + def _set_list_header_if_not_empty(self, msg, header, values): + """ + Set msg's header, either from self.extra_headers, if present, or from + the values argument. + """ + if values: + try: + value = self.extra_headers[header] + except KeyError: + value = ', '.join(str(v) for v in values) + msg[header] = value + class EmailMultiAlternatives(EmailMessage): """ diff --git a/tests/mail/tests.py b/tests/mail/tests.py index 869cd764bf..c7b8d09027 100644 --- a/tests/mail/tests.py +++ b/tests/mail/tests.py @@ -132,6 +132,13 @@ class MailTests(HeadersCheckMixin, SimpleTestCase): ['to@example.com', 'other@example.com', 'cc@example.com', 'cc.other@example.com', 'bcc@example.com'] ) + def test_cc_headers(self): + message = EmailMessage( + 'Subject', 'Content', 'bounce@example.com', ['to@example.com'], + cc=['foo@example.com'], headers={'Cc': 'override@example.com'}, + ).message() + self.assertEqual(message['Cc'], 'override@example.com') + def test_cc_in_headers_only(self): message = EmailMessage( 'Subject', 'Content', 'bounce@example.com', ['to@example.com'],