美文网首页
logging模块配置smtp协议465端口发送错误日志邮件

logging模块配置smtp协议465端口发送错误日志邮件

作者: 水荣_eb7e | 来源:发表于2019-06-24 17:19 被阅读0次

问题:
直接配置logging发送smtp协议465端口发送邮件会出现,如下错误,如图:


20190624165933.png

其实原因就是,发送邮件时直接调用smtplib中的SMTP方法,该方法是没有封装支持TLS协议,所以会出现超时连接错误。


解决方法:
重写发送邮件的emit方法
修改前:

    def emit(self, record):
        """
        Emit a record.

        Format the record and send it to the specified addressees.
        """
        try:
            import smtplib
            from email.message import EmailMessage
            import email.utils

            port = self.mailport
            if not port:
                port = smtplib.SMTP_PORT
            smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout)
            msg = EmailMessage()
            msg['From'] = self.fromaddr
            msg['To'] = ','.join(self.toaddrs)
            msg['Subject'] = self.getSubject(record)
            msg['Date'] = email.utils.localtime()
            msg.set_content(self.format(record))
            if self.username:
                if self.secure is not None:
                    smtp.ehlo()
                    smtp.starttls(*self.secure)
                    smtp.ehlo()
                smtp.login(self.username, self.password)
            smtp.send_message(msg)
            smtp.quit()
        except Exception:
            self.handleError(record)

修改后:

def emit(self, record):
    """
    Overwrite the logging.handlers.SMTPHandler.emit function with SMTP_SSL.
    Emit a record.
    Format the record and send it to the specified addressees.
    """
    try:
        import smtplib
        from email.utils import formatdate
        port = self.mailport
        if not port:
            port = smtplib.SMTP_PORT
        smtp = smtplib.SMTP_SSL(self.mailhost, port, timeout=5)
        msg = self.format(record)
        msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
        self.fromaddr, ", ".join(self.toaddrs), self.getSubject(record), formatdate(), msg)
        if self.username:
            smtp.ehlo()
            smtp.login(self.username, self.password)
        smtp.sendmail(self.fromaddr, self.toaddrs, msg)
        smtp.quit()
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        self.handleError(record)

修改完之后,直接把原来的方法覆盖就好了,代码如下:

handlers.SMTPHandler.emit = emit  # 需要导入from logging import handlers模块

最后问题就解决啦,可以直接发送TLS协议的邮件。

注:这里是参考了stack overflow的文章https://stackoverflow.com/questions/30770981/logging-handlers-smtphandler-raises-smtplib-smtpauthenticationerror/34003015#34003015

相关文章

网友评论

      本文标题:logging模块配置smtp协议465端口发送错误日志邮件

      本文链接:https://www.haomeiwen.com/subject/zzioqctx.html