From 04b7b28812fa6b2721096da6e00b929784c00da6 Mon Sep 17 00:00:00 2001 From: Claude Paroz Date: Fri, 1 Jul 2016 22:01:58 +0200 Subject: [PATCH] Fixed #26802 -- Prevented crash when attaching bytes as text message Thanks Tim Graham for the review. --- django/core/mail/message.py | 8 ++++++-- tests/mail/tests.py | 8 ++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/django/core/mail/message.py b/django/core/mail/message.py index 21ba1dfa85..29012201ef 100644 --- a/django/core/mail/message.py +++ b/django/core/mail/message.py @@ -212,9 +212,13 @@ class SafeMIMEText(MIMEMixin, MIMEText): def __init__(self, _text, _subtype='plain', _charset=None): self.encoding = _charset if _charset == 'utf-8': - # Unfortunately, Python < 3.5 doesn't support setting a Charset instance - # as MIMEText init parameter (http://bugs.python.org/issue16324). + # Unfortunately, Python doesn't yet pass a Charset instance as + # MIMEText init parameter to set_payload(). + # http://bugs.python.org/issue27445 # We do it manually and trigger re-encoding of the payload. + if six.PY3 and isinstance(_text, bytes): + # Sniffing encoding would fail with bytes content in MIMEText.__init__. + _text = _text.decode('utf-8') MIMEText.__init__(self, _text, _subtype, None) del self['Content-Transfer-Encoding'] has_long_lines = any(len(l) > RFC5322_EMAIL_LINE_LENGTH_LIMIT for l in _text.splitlines()) diff --git a/tests/mail/tests.py b/tests/mail/tests.py index fac7c576c2..f5e93c6d89 100644 --- a/tests/mail/tests.py +++ b/tests/mail/tests.py @@ -390,6 +390,14 @@ class MailTests(HeadersCheckMixin, SimpleTestCase): msgs_sent_num = email.send() self.assertEqual(msgs_sent_num, 1) + def test_attach_text_as_bytes(self): + msg = EmailMessage('subject', 'body', 'from@example.com', ['to@example.com']) + file_path = os.path.join(os.path.dirname(upath(__file__)), 'attachments', 'file.txt') + with open(file_path, mode='rb') as fh: + msg.attach('file.txt', fh.read()) + sent_num = msg.send() + self.assertEqual(sent_num, 1) + def test_dummy_backend(self): """ Make sure that dummy backends returns correct number of sent messages