Python logging.SMTP处理程序不工作
我试图做的是创建一个单独的记录器,通过电子邮件发送错误日志。 但是,每次我调用email_logger.error(“…”)时,都会发生以下错误: smtplib.SMTPNotSupportedError:服务器不支持SMTP验证扩展名 我使用的代码如下所示:Python logging.SMTP处理程序不工作,python,email,logging,handler,smtplib,Python,Email,Logging,Handler,Smtplib,我试图做的是创建一个单独的记录器,通过电子邮件发送错误日志。 但是,每次我调用email_logger.error(“…”)时,都会发生以下错误: smtplib.SMTPNotSupportedError:服务器不支持SMTP验证扩展名 我使用的代码如下所示: logging.basicConfig(level=logging.INFO, format='%(asctime)s :: %(funcName)s :: %(levelname)s :: %(message)s') email_l
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)
当我使用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,具体取决于您的安全设置。我在通过日志模块向Amazon STMP服务器(Amazon SES)发送电子邮件时遇到了相同的问题。我通过使用
secure=()
解决了这个问题
因为当向强制使用安全模式的STMP发送电子邮件时,secure
选项不得为None
。这是日志模块内部用于发送电子邮件的代码:
如果self.username:
如果self.secure不是None:
smtp.ehlo()
smtp.starttls(*self.secure)
smtp.ehlo()
smtp.login(self.username、self.password)
smtp.send_消息(msg)
smtp.quit()
因此,为了使用安全模式而不向smtp.starttls传递参数,我将安全选项设置为()
,它解决了我的问题:它正确地使用TLS连接向smtp服务器发送电子邮件