【selenium+Python unittest】之发送邮箱时报错:smtplib.SMTPDataError、smtplib.SMTPAuthenticationError(例:126邮箱),,原代码如下:impo


原代码如下:

import smtplibfrom email.mime.text import MIMETextfrom email.header import Header#要发送的服务器smtpserver = ‘smtp.126.com‘#要发送的邮箱用户名/密码user = ‘[email protected]‘password = ‘XXX‘#发送的邮箱sender = ‘[email protected]‘#接收的邮箱receiver = ‘[email protected]‘#发送邮箱主题subject = ‘test_mail‘#编写HTML类型的邮件正文msg = MIMEText(‘<html><h1>大佬好!</h1></html>‘,‘html‘,‘utf-8‘)msg[‘Subject‘] = Header(subject,‘utf-8‘)#连接发送邮件smtp = smtplib.SMTP()smtp.connect(smtpserver)smtp.login(user,password)smtp.sendmail(sender,receiver,msg.as_string())smtp.quit()

一、现象:

发送邮件时,运行时报错smtplib.SMTPDataError,如下图:

技术分享图片

二、解决办法

①经网上查询得知:因为126邮箱中没有开启【授权码】,如下图所示应该开启:

技术分享图片

②但是再次运行代码还是报错:smtplib.SMTPAuthenticationError,如下图,提示登陆失败:

技术分享图片

原因是:代码中的密码应该改为授权密码即可。

③继续运行后,但是代码还是报错:smtplib.SMTPDataError:(554, b‘DT:SPM 126 smtp4

报错原因是没有加上下面的代码:

#报错原因是因为“发件人和收件人参数没有进行定义msg[‘from‘] = ‘[email protected]‘msg[‘to‘] = ‘[email protected]‘

加上之后,终于解决发送邮件失败的问题了。

完整代码如下:(因保密自行替换)

import smtplibfrom email.mime.text import MIMETextfrom email.header import Header#要发送的服务器smtpserver = ‘smtp.126.com‘#要发送的邮箱用户名/密码user = ‘[email protected]‘password = ‘XXX‘#发送的邮箱sender = ‘[email protected]‘#接收的邮箱receiver = ‘[email protected]‘#发送邮箱主题subject = ‘test_mail‘#编写HTML类型的邮件正文msg = MIMEText(‘<html><h1>大佬好!</h1></html>‘,‘html‘,‘utf-8‘)msg[‘Subject‘] = Header(subject,‘utf-8‘)msg[‘from‘] = ‘[email protected]‘msg[‘to‘] = ‘[email protected]‘#连接发送邮件smtp = smtplib.SMTP()smtp.connect(smtpserver)smtp.login(user,password)smtp.sendmail(sender,receiver,msg.as_string())smtp.quit()

【selenium+Python unittest】之发送邮箱时报错:smtplib.SMTPDataError、smtplib.SMTPAuthenticationError(例:126邮箱)

评论关闭