Fixes #14314: Improved SMTP timeout handling.

This commit is contained in:
Vinay Sajip 2012-03-15 12:02:08 +00:00
parent 7cc7033cb4
commit 17160fd6d6
2 changed files with 7 additions and 3 deletions

View File

@ -867,7 +867,7 @@ class SMTPHandler(logging.Handler):
A handler class which sends an SMTP email for each logging event. A handler class which sends an SMTP email for each logging event.
""" """
def __init__(self, mailhost, fromaddr, toaddrs, subject, def __init__(self, mailhost, fromaddr, toaddrs, subject,
credentials=None, secure=None): credentials=None, secure=None, timeout=1.0):
""" """
Initialize the handler. Initialize the handler.
@ -881,6 +881,8 @@ class SMTPHandler(logging.Handler):
will be either an empty tuple, or a single-value tuple with the name will be either an empty tuple, or a single-value tuple with the name
of a keyfile, or a 2-value tuple with the names of the keyfile and of a keyfile, or a 2-value tuple with the names of the keyfile and
certificate file. (This tuple is passed to the `starttls` method). certificate file. (This tuple is passed to the `starttls` method).
A timeout in seconds can be specified for the SMTP connection (the
default is one second).
""" """
logging.Handler.__init__(self) logging.Handler.__init__(self)
if isinstance(mailhost, tuple): if isinstance(mailhost, tuple):
@ -897,6 +899,7 @@ class SMTPHandler(logging.Handler):
self.toaddrs = toaddrs self.toaddrs = toaddrs
self.subject = subject self.subject = subject
self.secure = secure self.secure = secure
self.timeout = timeout
def getSubject(self, record): def getSubject(self, record):
""" """
@ -919,7 +922,7 @@ class SMTPHandler(logging.Handler):
port = self.mailport port = self.mailport
if not port: if not port:
port = smtplib.SMTP_PORT port = smtplib.SMTP_PORT
smtp = smtplib.SMTP(self.mailhost, port) smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout)
msg = self.format(record) msg = self.format(record)
msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % ( msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
self.fromaddr, self.fromaddr,

View File

@ -936,8 +936,9 @@ class SMTPHandlerTest(BaseTest):
r = logging.makeLogRecord({'msg': 'Hello'}) r = logging.makeLogRecord({'msg': 'Hello'})
self.handled = threading.Event() self.handled = threading.Event()
h.handle(r) h.handle(r)
self.handled.wait() self.handled.wait(5.0) # 14314: don't wait forever
server.stop() server.stop()
self.assertTrue(self.handled.is_set())
self.assertEqual(len(self.messages), 1) self.assertEqual(len(self.messages), 1)
peer, mailfrom, rcpttos, data = self.messages[0] peer, mailfrom, rcpttos, data = self.messages[0]
self.assertEqual(mailfrom, 'me') self.assertEqual(mailfrom, 'me')