Skip to content

Commit 1679e1a

Browse files
authored
Improve error handling in SMTP email logging
Refactor email message handling in SMTP logging to ensure proper cleanup and error handling.
1 parent b6c11fe commit 1679e1a

1 file changed

Lines changed: 37 additions & 30 deletions

File tree

Lib/logging/handlers.py

Lines changed: 37 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1121,36 +1121,43 @@ def emit(self, record):
11211121
if not port:
11221122
port = smtplib.SMTP_PORT
11231123
smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout)
1124-
msg = EmailMessage()
1125-
msg['From'] = self.fromaddr
1126-
msg['To'] = ','.join(self.toaddrs)
1127-
msg['Subject'] = self.getSubject(record)
1128-
msg['Date'] = email.utils.localtime()
1129-
msg.set_content(self.format(record))
1130-
if self.username:
1131-
if self.secure is not None:
1132-
import ssl
1133-
1134-
try:
1135-
keyfile = self.secure[0]
1136-
except IndexError:
1137-
keyfile = None
1138-
1139-
try:
1140-
certfile = self.secure[1]
1141-
except IndexError:
1142-
certfile = None
1143-
1144-
context = ssl._create_stdlib_context(
1145-
certfile=certfile, keyfile=keyfile
1146-
)
1147-
smtp.ehlo()
1148-
smtp.starttls(context=context)
1149-
smtp.ehlo()
1150-
smtp.login(self.username, self.password)
1151-
smtp.send_message(msg)
1152-
smtp.quit()
1153-
except Exception:
1124+
try:
1125+
msg = EmailMessage()
1126+
msg['From'] = self.fromaddr
1127+
msg['To'] = ','.join(self.toaddrs)
1128+
msg['Subject'] = self.getSubject(record)
1129+
msg['Date'] = email.utils.localtime()
1130+
msg.set_content(self.format(record))
1131+
if self.username:
1132+
if self.secure is not None:
1133+
import ssl
1134+
1135+
try:
1136+
keyfile = self.secure[0]
1137+
except IndexError:
1138+
keyfile = None
1139+
1140+
try:
1141+
certfile = self.secure[1]
1142+
except IndexError:
1143+
certfile = None
1144+
1145+
context = ssl._create_stdlib_context(
1146+
certfile=certfile, keyfile=keyfile
1147+
)
1148+
smtp.ehlo()
1149+
smtp.starttls(context=context)
1150+
smtp.ehlo()
1151+
smtp.login(self.username, self.password)
1152+
smtp.send_message(msg)
1153+
smtp.quit()
1154+
except Exception:
1155+
try:
1156+
smtp.close()
1157+
except Exception:
1158+
pass
1159+
raise
1160+
except Exception:
11541161
self.handleError(record)
11551162

11561163
class NTEventLogHandler(logging.Handler):

0 commit comments

Comments
 (0)