【问题标题】:Python logging.SMTP handler is not workingPython logging.SMTP 处理程序不工作
【发布时间】:2020-03-13 11:58:45
【问题描述】:

我想做的是创建一个单独的记录器,它将通过电子邮件发送错误日志。 但是,每次调用email_logger.error('...'),都会出现以下错误:

smtplib.SMTPNotSupportedError: 服务器不支持 SMTP AUTH 扩展。

我使用的代码如下所示:

logging.basicConfig(level=logging.INFO, format='%(asctime)s :: %(funcName)s :: %(levelname)s :: %(message)s')

email_logger = logging.getLogger(__name__)
email_logger.setLevel(logging.WARNING)

with smtplib.SMTP('smtp.gmail.com', 587) as server:
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login('host_email@gmail.com', r'thisismypassword')
    smtp_handler = logging.handlers.SMTPHandler(mailhost=('smtp.gmail.com', 587),
                                                fromaddr='host_email@gmail.com',
                                                toaddrs=['mymail@gmail.com'],
                                                subject='A dashing subject',
                                                credentials=('host_email@gmail.com',
                                                             r'thisismypassword'),
                                                secure=None)
    formatter = logging.Formatter('%(asctime)s : %(funcName)s : %(levelname)s : %(name)s : %(message)s')
    smtp_handler.setFormatter(formatter)
    email_logger.addHandler(smtp_handler)

【问题讨论】:

    标签: python email logging handler smtplib


    【解决方案1】:

    我在通过日志记录模块向 Amazon STMP 服务器 (Amazon SES) 发送电子邮件时遇到了同样的问题。我通过使用secure=() 解决了这个问题。

    因为在向强制执行安全模式的 STMP 发送电子邮件时,secure 选项不得为 None。这是日志模块内部用于发送电子邮件的代码:

                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()
    

    因此,要使用安全模式而不将参数传递给smtp.starttls,我将安全选项设置为(),它解决了我的问题:它正确地使用了 TLS 连接将电子邮件发送到 SMTP 服务器。

    【讨论】:

      【解决方案2】:

      当我使用 Gmail 从 Python 发送电子邮件时,我使用:

      server = smtplib.SMTP_SSL('smtp.gmail.com', 465) 
      

      另外,尝试在常规 python shell 中连接到服务器

      server = smtplib.SMTP_SSL('smtp.gmail.com', 465) 
      server.login(username, password)
      

      要查看您的详细信息是否正确,您可能需要设置应用密码才能通过应用使用 Gmail,具体取决于您的安全设置

      【讨论】:

        猜你喜欢
        • 2014-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多