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`.