diff --git a/Lib/smtplib.py b/Lib/smtplib.py index 72093f7f8b0f2d..e33f72efa98754 100644 --- a/Lib/smtplib.py +++ b/Lib/smtplib.py @@ -150,7 +150,9 @@ def quoteaddr(addrstring): if (displayname, addr) == ('', ''): # parseaddr couldn't parse it, use it as is and hope for the best. if addrstring.strip().startswith('<'): - return addrstring + if addrstring.strip().endswith('>'): + return addrstring + return addrstring.strip() + '>' return "<%s>" % addrstring return "<%s>" % addr diff --git a/Lib/test/test_smtplib.py b/Lib/test/test_smtplib.py index b8aac8c20202a2..fac8323d75953c 100644 --- a/Lib/test/test_smtplib.py +++ b/Lib/test/test_smtplib.py @@ -77,6 +77,26 @@ def testQuoteData(self): expected = "abc\r\n..jkl\r\nfoo\r\n...blue" self.assertEqual(expected, smtplib.quotedata(teststr)) + def testQuoteAddr(self): + # Standard address is wrapped in angle brackets. + self.assertEqual(smtplib.quoteaddr('user@example.com'), + '') + # Already angle-bracketed and valid. + self.assertEqual(smtplib.quoteaddr(''), + '') + # Empty string produces empty angle brackets. + self.assertEqual(smtplib.quoteaddr(''), '<>') + + def testQuoteAddrMalformedAngleBracket(self): + # Inputs starting with '<' but missing closing '>' must still + # produce output that ends with '>'. + result = smtplib.quoteaddr('<') + self.assertTrue(result.startswith('<') and result.endswith('>'), result) + result = smtplib.quoteaddr('< ') + self.assertTrue(result.startswith('<') and result.endswith('>'), result) + result = smtplib.quoteaddr(''), result) + def testBasic1(self): mock_socket.reply_with(b"220 Hola mundo") # connects diff --git a/Misc/NEWS.d/next/Library/2026-03-05-15-20-18.gh-issue-145552.80p_Cr.rst b/Misc/NEWS.d/next/Library/2026-03-05-15-20-18.gh-issue-145552.80p_Cr.rst new file mode 100644 index 00000000000000..8c074d08e79380 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-03-05-15-20-18.gh-issue-145552.80p_Cr.rst @@ -0,0 +1 @@ +Fix ``smtplib.quoteaddr()`` to ensure the returned address always has a closing ``>`` when the input starts with ``<`` but ``email.utils.parseaddr()`` fails to parse it.