配置 app 对象的邮件服务器地址,端口,用户名和密码等
创建一个 Mail 的实例:mail = Mail(app)
创建一个 Message 消息实例,有三个参数:邮件标题、发送者和接收者
创建邮件内容,如果是 HTML 格式,则使用 msg.html,如果是纯文本格式,则使用 msg.body
最后调用 mail.send(msg) 发送消息
记得设置好mail_username,mail_password两个值在环境变量中。
from flask import Flask,request
from flask_mail import Mail,Message
import os
app=Flask(__name__)
app.config['MAIL_SERVER']='smtp.qq.com'
app.config['MAIL_PORT']=25
app.config['MAIL_USE_TLS']=True
#app.config['MAIL_USERNAME']='xxx'
#app.config['MAIL_PASSWORD']='xxx'
app.config['MAIL_USERNAME']=os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD']=os.environ.get('MAIL_PASSWORD')
mail=Mail(app)
@app.route('/')
def index():
return app.config['MAIL_PASSWORD']
@app.route('/sendmail/')
def sendmail():
msg=Message('Hi',sender='798167096@qq.com',recipients=['240990723@qq.com'])
msg.html='<b>hello web</b>'
mail.send(msg)
return '<h1>ok!</h1>'
@app.route('/user/<name>')
def user(name):
return '<h1>hello ,%s!</h1>'%name
if __name__=='__main__':
app.run(debug=True)
异步发送
避免发送邮件过程中出现的延迟,我们把发送邮件的任务移到后台线程中。创建了一个线程,执行的任务是send_async_email
def send_sync_email(app,msg):
with app.app_context():
mail.send(msg)
@app.route('/sync/')
def sendmailsync():
msg=Message('Hi',sender='798167096@qq.com',recipients=['icecrea@yeah.net'])
msg.html='<b>send this sync</b>'
thr=Thread(target=send_sync_email,args=[app,msg])
thr.start()
return '<h1>send sync ok!</h1>'