Skip to content

Commit d7672e5

Browse files
authored
gh-127712: Fix secure argument of logging.handlers.SMTPHandler (GH-127726)
GH-127712: Fix `secure` argument of `logging.handlers.SMTPHandler` Python 3.12 removed support for the `keyfile` and `certfile` parameters in `smtplib.SMTP.starttls()`, requiring a `ssl.SSLContext` instead. `SMTPHandler` now creates a context from the `secure` tuple and passes that to `starttls`.
1 parent 94cd2e0 commit d7672e5

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

Lib/logging/handlers.py

+18-2
Original file line numberDiff line numberDiff line change
@@ -1043,7 +1043,8 @@ def __init__(self, mailhost, fromaddr, toaddrs, subject,
10431043
only be used when authentication credentials are supplied. The tuple
10441044
will be either an empty tuple, or a single-value tuple with the name
10451045
of a keyfile, or a 2-value tuple with the names of the keyfile and
1046-
certificate file. (This tuple is passed to the `starttls` method).
1046+
certificate file. (This tuple is passed to the
1047+
`ssl.SSLContext.load_cert_chain` method).
10471048
A timeout in seconds can be specified for the SMTP connection (the
10481049
default is one second).
10491050
"""
@@ -1096,8 +1097,23 @@ def emit(self, record):
10961097
msg.set_content(self.format(record))
10971098
if self.username:
10981099
if self.secure is not None:
1100+
import ssl
1101+
1102+
try:
1103+
keyfile = self.secure[0]
1104+
except IndexError:
1105+
keyfile = None
1106+
1107+
try:
1108+
certfile = self.secure[1]
1109+
except IndexError:
1110+
certfile = None
1111+
1112+
context = ssl._create_stdlib_context(
1113+
certfile=certfile, keyfile=keyfile
1114+
)
10991115
smtp.ehlo()
1100-
smtp.starttls(*self.secure)
1116+
smtp.starttls(context=context)
11011117
smtp.ehlo()
11021118
smtp.login(self.username, self.password)
11031119
smtp.send_message(msg)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix handling of the ``secure`` argument of :class:`logging.handlers.SMTPHandler`.

0 commit comments

Comments
 (0)