1.配置信息
1)在163的设置中,开启客户端的授权密码
2)配置参数
app.config['MAIL_SERVER'] = 'smtp.163.com'
app.config['MAIL_PORT'] = 25
app.config['MAIL_USERNAME'] = 'xxx@163.com'
app.config['MAIL_PASSWORD'] = 'xxx'
app.config['FLASKY_ADMIN'] = 'xxx@qq.com'
2.使用python shell 模式来测试配置是否正确
from test import Message
from test import mail
msg = Message('test subject', sender=app.config['MAIL_USERNAME'], recipients=[to]) # 注意[]必须有,否则将会报错
msg.body = 'test body'
msg.html = 'test html'
with app.app_context():
mail.send(msg)
3.配置成功后,可以使用程序来发送邮件
def send_mail(to, title):
msg = Message(title, app.config['MAIL_USERNAME'], recipients=[to])
msg.body = 'test body'
msg.html = 'test html'
thr = Thread(target=send_async_email, args=[app, msg])
thr.start()
return thr
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
创建新的线程thr来执行发送邮件操作,达到异步的效果,否则将可能出现停滞几秒,浏览器像无响应一样的状态。
参考文献:《基于python 的web应用开发》