Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ec317a8

Browse files
committed
#17171: fix email.encoders.encode_7or8bit when applied to binary data.
1 parent b3e8384 commit ec317a8

3 files changed

Lines changed: 24 additions & 2 deletions

File tree

Lib/email/encoders.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,15 +62,17 @@ def encode_7or8bit(msg):
6262
else:
6363
orig.decode('ascii')
6464
except UnicodeError:
65-
# iso-2022-* is non-ASCII but still 7-bit
6665
charset = msg.get_charset()
6766
output_cset = charset and charset.output_charset
67+
# iso-2022-* is non-ASCII but encodes to a 7-bit representation
6868
if output_cset and output_cset.lower().startswith('iso-2022-'):
6969
msg['Content-Transfer-Encoding'] = '7bit'
7070
else:
7171
msg['Content-Transfer-Encoding'] = '8bit'
7272
else:
7373
msg['Content-Transfer-Encoding'] = '7bit'
74+
if not isinstance(orig, str):
75+
msg.set_payload(orig.decode('ascii', 'surrogateescape'))
7476

7577

7678

Lib/email/test/test_email.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1438,7 +1438,24 @@ def test_body(self):
14381438
eq(msg.get_payload().strip(), '+vv8/f7/')
14391439
eq(msg.get_payload(decode=True), bytesdata)
14401440

1441-
def test_body_with_encode_noop(self):
1441+
def test_binary_body_with_encode_7or8bit(self):
1442+
# Issue 17171.
1443+
bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
1444+
msg = MIMEApplication(bytesdata, _encoder=encoders.encode_7or8bit)
1445+
# Treated as a string, this will be invalid code points.
1446+
self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata))
1447+
self.assertEqual(msg.get_payload(decode=True), bytesdata)
1448+
self.assertEqual(msg['Content-Transfer-Encoding'], '8bit')
1449+
s = BytesIO()
1450+
g = BytesGenerator(s)
1451+
g.flatten(msg)
1452+
wireform = s.getvalue()
1453+
msg2 = email.message_from_bytes(wireform)
1454+
self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata))
1455+
self.assertEqual(msg2.get_payload(decode=True), bytesdata)
1456+
self.assertEqual(msg2['Content-Transfer-Encoding'], '8bit')
1457+
1458+
def test_binary_body_with_encode_noop(self):
14421459
# Issue 16564: This does not produce an RFC valid message, since to be
14431460
# valid it should have a CTE of binary. But the below works in
14441461
# Python2, and is documented as working this way.

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,9 @@ Core and Builtins
221221
Library
222222
-------
223223

224+
- Issue #16564: Fixed regression relative to Python2 in the operation of
225+
email.encoders.encode_7or8bit when used with binary data.
226+
224227
- Issue #17052: unittest discovery should use self.testLoader.
225228

226229
- Issue #17141: random.vonmisesvariate() no more hangs for large kappas.

0 commit comments

Comments
 (0)