python使用SMTP发送邮件报错:smtplib.SMTPDataError: (554, 'DT:SPM...

下面为学习python使用SMTP发送邮件时的一段代码,运行时总是报错smtplib.SMTPDataError: (554, 'DT:SPM...,添加smtp.set_debuglevel(1)发现是调用smtp.sendmail()时出错了,找了好多文章都说是 msg['Subject'] = sub msg['From'] = "username" + "<" + from_server + ">" msg['To'] = ";".join(to_list)内容有问题,仔细改了好几遍还是报一样的错,后来在发现有人使用邮件客户端时遇到同样的问题:
https://blog.csdn.net/jerry11112/article/details/81213162
是因为126服务器把发送的邮件当成垃圾邮件了,在收件人列表里面加上自己的邮箱,就可以成功发送了。折腾了一个晚上解决了之后感觉自己好无奈~~~
感觉解决办法有点儿low,不知道有没从代码上可以解决的办法,请指教。

# coding:utf-8
import smtplib
from email.mime.text import MIMEText


class SendEmail:

    global host
    global from_server
    global password
    host = "smtp.126.com"
    from_server = "******@126.com"
    password = "*******"

    def send_email(self, sub, to_list, content):
        msg = MIMEText(content, 'plain', 'utf-8')
        msg['Subject'] = sub 
        msg['From'] = "username" + "<" + from_server + ">" 
        msg['To'] = ";".join(to_list)

        smtp = smtplib.SMTP()
       # smtp.set_debuglevel(1)
        smtp.connect(host)
        smtp.login(from_server, password)
        smtp.sendmail(from_server, to_list, msg.as_string())
        smtp.quit()
        smtp.close()

if __name__ == '__main__':

    sen = SendEmail()
    sub = "测试"
    to_list = ["******@126.com", "******@163.com"]
    content = "第一封邮件"
    sen.send_email(sub, to_list, content)


你可能感兴趣的:(python)