说明:本例使用163邮箱
一、报错信息
使用SMTP发送邮件遇到以下报错:
554, b'DT:SPM 163 smtp10,DsCowACXeOtmjRRdsY8aCw--.21947S2 1561628007,please see http://mail.163.com/help/help_spam_16.htm?ip=36.110.94.251&hostid=smtp10&time=1561628007'
二、排查原因
1.检查163邮箱是否设置授权码,授权码对不对。不对会报错:535, b'Error: authentication failed'
2.检查代码邮件格式规范
下面贴出菜鸟教程部分代码使用header。看已发送邮件的确是显示了发件人别名(显示代发),收件人看到的发件人也是自己起的别名。如下图:
# -*- coding: utf-8 -*- # Nola import smtplib from email.mime.text import MIMEText from email.header import Header import time mail_server = "smtp.163.com" mail_port = 25 sender = "xxxxx@163.com" sender_password = "xxxxxx" # 授权码 receivers = "wewewwe@163.com" message = MIMEText('Python邮件发送测试...', 'plain', 'utf-8') # message['From'] = sender # message['To'] = receivers message['From'] = Header("菜鸟教程", 'utf-8') message['To'] = Header("测试", 'utf-8') send_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) subject = '邮件测试' + send_time message['Subject'] = subject try: smtp_obj = smtplib.SMTP() smtp_obj.connect(mail_server, mail_port) smtp_obj.login(sender, sender_password) smtp_obj.sendmail(sender, [receivers], message.as_string()) print('success!') except smtplib.SMTPException as e: print('failure!') print(e)
重点是:收到几封邮件后,收不到了,换收件人也收不到,猜测是163禁发了。点上图中帮助可以看到下图,所以善意的伪装也会产生误会。
三、解决方法
From和To使用发件人和收件人真实邮箱地址,发送即可成功。
# -*- coding: utf-8 -*- # Nola import smtplib from email.mime.text import MIMEText import time mail_server = "smtp.163.com" mail_port = 25 sender = "xxxxx@163.com" sender_password = "xxxxxx" # 授权码 receivers = "wewewwe@163.com" message = MIMEText('Python邮件发送测试...', 'plain', 'utf-8') message['From'] = sender message['To'] = receivers send_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) subject = '邮件测试' + send_time message['Subject'] = subject try: smtp_obj = smtplib.SMTP() smtp_obj.connect(mail_server, mail_port) smtp_obj.login(sender, sender_password) smtp_obj.sendmail(sender, [receivers], message.as_string()) print('success!') except smtplib.SMTPException as e: print('failure!') print(e)