diff --git a/Lib/email/message.py b/Lib/email/message.py index 08192c50a8ff5c..e7c3a13ca7dd7f 100644 --- a/Lib/email/message.py +++ b/Lib/email/message.py @@ -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): diff --git a/Lib/test/test_email/test_message.py b/Lib/test/test_email/test_message.py index 034f7626c1fc7c..3d832aa4cca14e 100644 --- a/Lib/test/test_email/test_message.py +++ b/Lib/test/test_email/test_message.py @@ -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 diff --git a/Misc/NEWS.d/next/Library/2024-09-06-11-58-17.gh-issue-123742.jSBNUv.rst b/Misc/NEWS.d/next/Library/2024-09-06-11-58-17.gh-issue-123742.jSBNUv.rst new file mode 100644 index 00000000000000..daa63024a48e96 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-09-06-11-58-17.gh-issue-123742.jSBNUv.rst @@ -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``.