安装
pip install flask-mail
引入
from flask_mail import Mail, Message
邮箱配置
app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USERNAME'] = '@qq.com'
app.config['MAIL_PASSWORD'] = '授权码'
PS:授权码需要在邮箱中设置 QQ邮箱==》设置==>账户==》开启服务 IMAP/SMTP服务 获得授权码
初始化
mail = Mail(app)
视图
# 异步发送邮件
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
@app.route('/email/')
def email():
msg = Message(title, sender='发送邮箱', recipients=['目标邮箱'])
msg.body = 'this is body string'
msg.html = '邮件内容'
thread = Thread(target=send_async_email, args=[app, msg])
thread.start()
return '<h1>邮件发送成功</h1>'
title 为邮件主题
Sender 为发送邮箱 与上面的配置中相同
recipients 为目标邮箱,可以添加多个目标邮箱
Msg.html 为邮件内容 格式为HTML格式
完成后开启服务 访问 127.0.0.0/email/ 即可发送邮件
网友评论