python 发送邮件 报554

按照菜鸟教程来发送,各种报554

Error: 无法发送邮件 (554, b'DT:SPM 163 smtp12,EMCowABnNMrmSVtj+d+YGQ--.44845S2 1666927083,please see http://mail.163.com/help/help_spam_16.htm?ip=222.2xx.84.37&hostid=smtp12&time=1666927083')

然后查资料说是给邮箱地址加“<>”包裹起来,确实就可以发送了。
随后,又想给邮箱附带收件人、发件人昵称,又报554。然后各种找资料,发现需要对message的属性进行编码(但不对receiver, sender编码)

测试可行代码如下:

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr, parseaddr


def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))


# 第三方 SMTP 服务
mail_host = "smtp.163.com"  # 设置服务器
mail_user = "176*****00@163.com"  # 用户名
mail_pass = "FZ*******APH"  # 口令

sender = '二狗<17608008600@163.com>'
receivers = ['大狗<55xxxx74@qq.com>', '三喵<10xxxx475@qq.com>']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

message = MIMEText('邮件发送测试...', 'plain', 'utf-8')
message['From'] = _format_addr(sender)
message['To'] = ','.join(list(map(_format_addr, receivers)))

subject = 'SMTP 测试邮件'
message['Subject'] = subject

try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)  # 25 为 SMTP 端口号
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    smtpObj.quit()
    print("邮件发送成功")
except smtplib.SMTPException as e:
    print("Error: 无法发送邮件", e)
posted @ 2022-10-28 11:31  流失的痕迹  阅读(305)  评论(0编辑  收藏  举报