Fixed #26802 -- Prevented crash when attaching bytes as text message

Thanks Tim Graham for the review.
This commit is contained in:
Claude Paroz 2016-07-01 22:01:58 +02:00
parent 9356f63a99
commit 04b7b28812
2 changed files with 14 additions and 2 deletions

View File

@ -212,9 +212,13 @@ class SafeMIMEText(MIMEMixin, MIMEText):
def __init__(self, _text, _subtype='plain', _charset=None): def __init__(self, _text, _subtype='plain', _charset=None):
self.encoding = _charset self.encoding = _charset
if _charset == 'utf-8': if _charset == 'utf-8':
# Unfortunately, Python < 3.5 doesn't support setting a Charset instance # Unfortunately, Python doesn't yet pass a Charset instance as
# as MIMEText init parameter (http://bugs.python.org/issue16324). # MIMEText init parameter to set_payload().
# http://bugs.python.org/issue27445
# We do it manually and trigger re-encoding of the payload. # 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) MIMEText.__init__(self, _text, _subtype, None)
del self['Content-Transfer-Encoding'] del self['Content-Transfer-Encoding']
has_long_lines = any(len(l) > RFC5322_EMAIL_LINE_LENGTH_LIMIT for l in _text.splitlines()) has_long_lines = any(len(l) > RFC5322_EMAIL_LINE_LENGTH_LIMIT for l in _text.splitlines())

View File

@ -390,6 +390,14 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
msgs_sent_num = email.send() msgs_sent_num = email.send()
self.assertEqual(msgs_sent_num, 1) 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): def test_dummy_backend(self):
""" """
Make sure that dummy backends returns correct number of sent messages Make sure that dummy backends returns correct number of sent messages