Skip to content

gh-155946: Improve error handling in SMTP email logging - #155950

Open
MazinSharaf wants to merge 6 commits into
python:mainfrom
MazinSharaf:logging-smtp
Open

gh-155946: Improve error handling in SMTP email logging#155950
MazinSharaf wants to merge 6 commits into
python:mainfrom
MazinSharaf:logging-smtp

Conversation

@MazinSharaf

@MazinSharaf MazinSharaf commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Fixes #155946

gh-155946: The error handling inside of SMTP email logging has been improved so that the SMTPHandler.emit() no longer leaks.

Refactor email message handling in SMTP logging to ensure proper cleanup and error handling.
@MazinSharaf
MazinSharaf requested a review from vsajip as a code owner August 17, 2026 09:26
@MazinSharaf MazinSharaf changed the title Improve error handling in SMTP email logging gh-155497: Improve error handling in SMTP email logging Aug 17, 2026
@MazinSharaf MazinSharaf changed the title gh-155497: Improve error handling in SMTP email logging gh-155496: Improve error handling in SMTP email logging Aug 17, 2026
@MazinSharaf MazinSharaf changed the title gh-155496: Improve error handling in SMTP email logging gh-155946: Improve error handling in SMTP email logging Aug 17, 2026

@picnixz picnixz left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are trailing whitespaces. In addition add tests and a NEWS entry.

Comment thread Lib/logging/handlers.py
smtp.send_message(msg)
smtp.quit()
except Exception:
try:

@picnixz picnixz Aug 17, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't put it in an entire try-catch. Only the relevant parts.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Address this. Don't use a full try-except block around code that doesn't need it.

Comment thread Lib/logging/handlers.py
Comment on lines +1154 to +1159
except Exception:
try:
smtp.close()
except Exception:
pass
raise

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only put a try-except when smtp is actually being used.

@bedevere-app

bedevere-app Bot commented Aug 17, 2026

Copy link
Copy Markdown

A Python core developer has requested some changes be made to your pull request before we can consider merging it. If you could please address their requests along with any other requests in other reviews from core developers that would be appreciated.

Once you have made the requested changes, please leave a comment on this pull request containing the phrase I have made the requested changes; please review again. I will then notify any core developers who have left a review that you're ready for them to take another look at this pull request.

@MazinSharaf

MazinSharaf commented Aug 17, 2026

Copy link
Copy Markdown
Contributor Author

How do I add the NEWS entry? And also, am I able to use the original issuer's test? His code for reproducing was:


logging.raiseExceptions = False
open_conns = []

def handle(conn):
    conn.sendall(b"220 fake ESMTP\r\n")
    for line in conn.makefile("rb"):
        cmd = line.strip().upper()
        if cmd.startswith(b"EHLO"):
            conn.sendall(b"250-fake\r\n250 AUTH PLAIN LOGIN\r\n")
        elif cmd.startswith(b"AUTH"):
            conn.sendall(b"535 authentication failed\r\n")
        else:
            conn.sendall(b"250 ok\r\n")
    open_conns.remove(conn)  # reached when the client closes the connection
    conn.close()

def serve(listener):
    while True:
        conn, _ = listener.accept()
        open_conns.append(conn)
        threading.Thread(target=handle, args=(conn,), daemon=True).start()

listener = socket.create_server(("127.0.0.1", 0))
threading.Thread(target=serve, args=(listener,), daemon=True).start()

h = logging.handlers.SMTPHandler(("127.0.0.1", listener.getsockname()[1]),
                                 "me@example.com", "you@example.com", "subject",
                                 credentials=("user", "wrong-password"))
for i in range(5):
    h.emit(logging.makeLogRecord({"msg": "hello"}))  # SMTPAuthenticationError
time.sleep(0.5)
print("open connections after 5 failed emits:", len(open_conns))
gc.collect(); time.sleep(0.5)
print("after gc.collect():", len(open_conns))

@picnixz

picnixz commented Aug 17, 2026

Copy link
Copy Markdown
Member

How do I add the NEWS entry

Use https://blurb-it.herokuapp.com/ or write it yourself with python -m blurb (I suggest using the app).

And also, am I able to use the original issuer's test

I beléieve so but you may also want to clean it up and have a minimal working example instead. You should also read the existing tests first.

@MazinSharaf

Copy link
Copy Markdown
Contributor Author

Do I just add the tests into the description of the PR or just leave a comment with the test(s)?

Removed unnecessary blank lines in the SSL context setup.
@picnixz

picnixz commented Aug 17, 2026

Copy link
Copy Markdown
Member

Do I just add the tests into the description of the PR or just leave a comment with the test(s)?

I don't understand. The PR description isn't really relevant as long as we have the issue.

@picnixz

picnixz commented Aug 17, 2026

Copy link
Copy Markdown
Member

You must add tests inside Lib/test/test_logging.py (look at the files)

Add test for connection closure on SMTP send failure.
@MazinSharaf

Copy link
Copy Markdown
Contributor Author

Sorry, got confused. Everything should be done now.

@@ -0,0 +1 @@
Fix SMTPHandler to close the SMTP connection when sending an email fails.

@picnixz picnixz Aug 17, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Fix SMTPHandler to close the SMTP connection when sending an email fails.
:mod:`logging`: ensure that :class:`~logging.handlers.SMTPHandler`
correctly releases resources on SMTP connection failures.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

logging: SMTPHandler.emit() leaks the SMTP connection when sending fails

2 participants