跟着廖雪峰老师学习Python,
不论用qq\126\163等邮箱测试,都需要先去邮箱看看是否已设置“开启SMTP服务”,
qq设置方法:设置->账户,下拉 开启服务,发短信获取授权码
126邮箱(老用户,新用户未知)默认开启SMTP服务,需要在左侧“客户端授权密码”那里设置授权码
授权码填写错误报错授权失败:535, b'Error: authentication failed'
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
#格式化邮件地址
def _format_addr(s):
name ,addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
smtp_server = 'smtp.XX.com' #发送方邮箱的smtp服务器
from_addr = "XXXX@XX.com" #发送方邮箱
password = "XXXX" #发送方授权码,此处非邮箱密码,填写错误会报错 535
to_addr = ["XXXX@XX.com"] #接收方邮箱
msg = MIMEText('Hell, send by Python', 'plain', 'utf-8') #内容
msg['From'] = _format_addr('Python爱好者 <%s>' % from_addr) #发送方简称
msg['To'] = _format_addr('管理员 <%s>'% to_addr) #接收方简称
msg['Subject'] = Header('来自SMTP的问候~~', 'utf-8').encode() #邮件标题
#server = smtplib.SMTP(smtp_server, 25) #非加密方式
server = smtplib.SMTP_SSL(smtp_server, 465)#SSL加密方式
server.login(from_addr, password)
server.sendmail(from_addr, to_addr, msg.as_string())
print("sending..")
server.quit()
print("ok")