diff --git a/Lib/email/encoders.py b/Lib/email/encoders.py index 55741a22a07b204..0977a26ff597566 100644 --- a/Lib/email/encoders.py +++ b/Lib/email/encoders.py @@ -30,6 +30,7 @@ def encode_base64(msg): orig = msg.get_payload(decode=True) encdata = str(_bencode(orig), 'ascii') msg.set_payload(encdata) + del msg['Content-Transfer-Encoding'] msg['Content-Transfer-Encoding'] = 'base64' @@ -41,6 +42,7 @@ def encode_quopri(msg): orig = msg.get_payload(decode=True) encdata = _qencode(orig) msg.set_payload(encdata) + del msg['Content-Transfer-Encoding'] msg['Content-Transfer-Encoding'] = 'quoted-printable' diff --git a/Lib/test/test_email/test_email.py b/Lib/test/test_email/test_email.py index e40c82bba9af426..81f9fe9b680d226 100644 --- a/Lib/test/test_email/test_email.py +++ b/Lib/test/test_email/test_email.py @@ -916,6 +916,20 @@ def test_default_cte(self): msg = MIMEText('hello \xf8 world', _charset='iso-8859-1') eq(msg['content-transfer-encoding'], 'quoted-printable') + def test_encode_replaces_existing_cte(self): + # gh-43702: re-encoding must replace the old Content-Transfer-Encoding + # header, not add a second one. + for charset, encoder, cte in ( + ('iso-8859-1', encoders.encode_base64, 'base64'), + ('utf-8', encoders.encode_quopri, 'quoted-printable')): + with self.subTest(cte=cte): + msg = MIMEText('h\xe9llo', _charset=charset) + encoder(msg) + self.assertEqual(msg.get_all('content-transfer-encoding'), + [cte]) + self.assertEqual(msg.get_payload(decode=True), + 'h\xe9llo'.encode(charset)) + def test_encode7or8bit(self): # Make sure a charset whose input character set is 8bit but # whose output character set is 7bit gets a transfer-encoding diff --git a/Misc/NEWS.d/next/Library/2026-09-26-10-43-18.gh-issue-43702.koAZST.rst b/Misc/NEWS.d/next/Library/2026-09-26-10-43-18.gh-issue-43702.koAZST.rst new file mode 100644 index 000000000000000..abe4b48a29ace8d --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-09-26-10-43-18.gh-issue-43702.koAZST.rst @@ -0,0 +1,4 @@ +Fix :func:`email.encoders.encode_base64` and +:func:`email.encoders.encode_quopri` adding a second +:mailheader:`Content-Transfer-Encoding` header when they re-encode a +message that already has one.