Skip to content
Closed
2 changes: 1 addition & 1 deletion Lib/email/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ def get_payload(self, i=None, decode=False):
raise TypeError('Expected list, got %s' % type(self._payload))
payload = self._payload
# cte might be a Header, so for now stringify it.
cte = str(self.get('content-transfer-encoding', '')).lower()
cte = str(self.get('content-transfer-encoding', '')).lower().strip()
# payload may be bytes here.
if not decode:
if isinstance(payload, str) and utils._has_surrogates(payload):
Expand Down
29 changes: 29 additions & 0 deletions Lib/test/test_email/test_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -985,6 +985,35 @@ def test_get_body_malformed(self):
# AttributeError: 'str' object has no attribute 'is_attachment'
m.get_body()

def test_get_payload_strip_ex_space(self):
# gh-123742
#
# Test whether get_payload can handle extra
# spaces in 'content-transfer-encoding' field.

err_field = 'Content-Transfer-Encoding: base64 '
msg = textwrap.dedent(f"""\
From: no-reply@example.com
To: reciever@example.com
Subject: Report
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="----=_Part3035080226180533"
Message-ID: <01000191b7fd06ba-d3c9ca36-5171-4a1d-ba3c-b378336cccbc-000000@email.amazonses.com>
Date: Tue, 3 Sep 2024 13:04:58 +0000

------=_Part3035080226180533
Content-Disposition: attachment;
Content-Type: text/plain; charset=UTF-8
{err_field}

aGVsbG8=
------=_Part3035080226180533
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 7bit
""")
m = self._str_msg(msg)
recv_m = m.get_payload(0).get_payload(decode=True)
self.assertEqual(recv_m, b"hello")

class TestMIMEPart(TestEmailMessageBase, TestEmailBase):
# Doing the full test run here may seem a bit redundant, since the two
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fixed :meth:`!email.Message.get_payload` failing to parse the
``content-transfer-encoding`` field with extra spaces. It will now
automatically strip spaces from ``content-transfer-encoding``.
Loading