SMTPHandler无法发送带有超时错误的日志记录电子邮件

时间:2020-08-25 12:45:07

标签: python email smtplib

在使用python的SMTPHandler来发送Web应用程序中的错误消息时,我遇到了问题,但是当我在shell实例中使用smtplib来查看这是否是服务器问题或我自己的连接,我可以很好地连接到服务器,并且可以发送邮件。

这是我的处理程序设置:

if not app.debug:
    if app.config['MAIL_SERVER']:
        auth = None
        if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
            auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
        secure = None
        if app.config['MAIL_USE_TLS']:
            secure = ()
        mail_handler = SMTPHandler(
            mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
            fromaddr='no-reply@' + app.config['MAIL_SERVER'],
            toaddrs=app.config['ADMINS'], subject='Blog Failure',
            credentials=auth, secure=secure)
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)

我通过打破数据库中的唯一约束来触发错误,并且获得了与正在发送的电子邮件有关的以下堆栈跟踪:

Traceback (most recent call last):
  File "/usr/lib/python3.7/smtplib.py", line 387, in getreply
    line = self.file.readline(_MAXLINE + 1)
  File "/usr/lib/python3.7/socket.py", line 589, in readinto
    return self._sock.recv_into(b)
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.7/logging/handlers.py", line 1016, in emit
    smtp.ehlo()
  File "/usr/lib/python3.7/smtplib.py", line 441, in ehlo
    (code, msg) = self.getreply()
  File "/usr/lib/python3.7/smtplib.py", line 391, in getreply
    + str(e))
smtplib.SMTPServerDisconnected: Connection unexpectedly closed: timed out

正如我提到的那样,我已经排除了这是我这边或我正在使用的SMTP服务器的连接问题,因为我已经使用flask shell连接了它:

>>> server = smtplib.SMTP(app.config['MAIL_SERVER'],app.config['MAIL_PORT'])
S>>> server.ehlo()
(250, b'smtp.gmail.com at your service, [80.44.155.7]\nSIZE 35882577\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8')
>>> server.starttls(context=context)
(220, b'2.0.0 Ready to start TLS')
>>> server.ehlo()
(250, b'smtp.gmail.com at your service, [80.44.155.7]\nSIZE 35882577\n8BITMIME\nAUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8')
>>> server.login(app.config['MAIL_USERNAME'],app.config['MAIL_PASSWORD'])
(235, b'2.7.0 Accepted')

熟悉python处理程序的人是否知道可能导致此问题的原因?

1 个答案:

答案 0 :(得分:0)

我遇到了类似的问题,我注意到 SMTPHandler 构造函数现在有一个超时参数,默认为 1,这可能不足以管理请求。尝试增加超时时间。

例如:

mail_handler = SMTPHandler(
        mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
        fromaddr='no-reply@' + app.config['MAIL_SERVER'],
        toaddrs=app.config['ADMINS'], subject='Blog Failure',
        credentials=auth, secure=secure, timeout=10.0)

我找不到超时的度量(秒、毫秒或其他)