python smtplib.SMTP_SS发邮件提示550, b‘The “From“ header is missing or invalid
发现网站不能注册新用户,报错提示:(550, b’The “From” header is missing or invalid. Please follow RFC5322, RFC2047, RFC822 standard protocol. https://service.mail.qq.com/detail/124/995.')
定位是注册时不能发邮件验证导致。QQ邮箱的From格式变更,需改为:昵称+空格+<邮箱地址>形式,注意有空格。(原文)
原代码:
message['From'] = Header(fromName, 'utf-8')
改为:
message['From'] = Header('nickname <abc@qq.com>')
#若发件人fromName含中文,则需要base64转码
message['From'] = Header('"=?utf-8?B?UVHpgq7nrrHmmLXnp7DnpLrkvos=?=" <abc@qq.com>')
先将汉字转为bytes,再bytes转base64。此时还是报错(550, b’The mail may contain inappropriate words or content.‘),一直调试发现转完的base64格式字符串是b’xxxx’形式,还需要将b’xxxx’转为’xxxx’。
以为这就完了吗,拼接邮箱名称和邮箱地址时fromNamestr打印出来总是少一截,邮箱地址不能显示。不是空格,不是转义字符的问题,是最后的右尖括号,需要用双引号来包裹!
本以为只是小问题,最后花了好几个小时才搞定,总结一个给大家避坑吧。完整代码如下:
import base64
def send_mail(receivers,content,fromName,toName,subject,type='plain'):
message = MIMEText(content, type, 'utf-8')
#汉字转base64
fromName64 = base64.b64encode(bytes(fromName, 'utf-8'))
#b'xxxx'转为'xxxx'
fromName64str = str(fromName64,'utf-8')
#尖括号拼接用双引号
fromNamestr = '"=?utf-8?B?' + fromName64str + '=?=" <' + sender + ">"
message['From'] = Header(fromNamestr)
#
message['To'] = Header(toName, 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP_SSL(host=mail_host)
smtpObj.connect(mail_host, 465) # 25 为 SMTP 端口号
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
return True
except smtplib.SMTPException:
return False