From e79c9930f64f2a45e38212753831eb2f4b309a87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Delfino?= Date: Mon, 2 Nov 2026 20:09:10 -0300 Subject: [PATCH] gh-161222: Fix email.utils.encode_rfc2231() writing "None" as the charset When only *language* was given, the missing charset was interpolated into the result as the literal string "None". Leave the charset field blank instead, as RFC 2231 permits, mirroring how a missing language is already handled. Co-Authored-By: Claude Opus 5.5 --- Lib/email/utils.py | 2 ++ Lib/test/test_email/test_email.py | 10 ++++++++++ .../2026-11-02-20-08-49.gh-issue-161222.e4eARb.rst | 3 +++ 3 files changed, 15 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2026-11-02-20-08-49.gh-issue-161222.e4eARb.rst diff --git a/Lib/email/utils.py b/Lib/email/utils.py index c8a6d0af37532c9..960ad77638d0f52 100644 --- a/Lib/email/utils.py +++ b/Lib/email/utils.py @@ -394,6 +394,8 @@ def encode_rfc2231(s, charset=None, language=None): s = urllib.parse.quote(s, safe='', encoding=charset or 'ascii') if charset is None and language is None: return s + if charset is None: + charset = '' if language is None: language = '' return "%s'%s'%s" % (charset, language, s) diff --git a/Lib/test/test_email/test_email.py b/Lib/test/test_email/test_email.py index 2a5794a5b66fc5b..a0fdd278034ccec 100644 --- a/Lib/test/test_email/test_email.py +++ b/Lib/test/test_email/test_email.py @@ -5926,6 +5926,16 @@ def test_rfc2231_unencoded_then_encoded_segments(self): eq(language, 'en-us') eq(s, 'My Document For You') + def test_rfc2231_encode_language_without_charset(self): + eq = self.assertEqual + eq(utils.encode_rfc2231('abc', language='en'), "'en'abc") + msg = Message() + msg.add_header('Content-Disposition', 'attachment', + filename=(None, 'en', 'report.txt')) + eq(msg['Content-Disposition'], + "attachment; filename*='en'report.txt") + eq(msg.get_filename(), 'report.txt') + def test_should_not_hang_on_invalid_ew_messages(self): messages = ["""From: user@host.com To: user@host.com diff --git a/Misc/NEWS.d/next/Library/2026-11-02-20-08-49.gh-issue-161222.e4eARb.rst b/Misc/NEWS.d/next/Library/2026-11-02-20-08-49.gh-issue-161222.e4eARb.rst new file mode 100644 index 000000000000000..54c8ded14acbf2c --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-02-20-08-49.gh-issue-161222.e4eARb.rst @@ -0,0 +1,3 @@ +Fix :func:`email.utils.encode_rfc2231` writing the literal string ``None`` +as the charset when only *language* is given. The charset field is now left +blank, as permitted by :rfc:`2231`.