Flask-mail 发送邮件

配置 app 对象的邮件服务器地址,端口,用户名和密码等
创建一个 Mail 的实例:mail = Mail(app)
创建一个 Message 消息实例,有三个参数:邮件标题、发送者和接收者
创建邮件内容,如果是 HTML 格式,则使用 msg.html,如果是纯文本格式,则使用 msg.body
最后调用 mail.send(msg) 发送消息
记得设置好mail_username,mail_password两个值在环境变量中。


Flask-mail 发送邮件_第1张图片
image.png
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='[email protected]',recipients=['[email protected]'])
    msg.html='hello web'
    mail.send(msg)
    return '

ok!

' @app.route('/user/') def user(name): return '

hello ,%s!

'%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='[email protected]',recipients=['[email protected]'])
    msg.html='send this sync'
    thr=Thread(target=send_sync_email,args=[app,msg])
    thr.start()
    return '

send sync ok!

'

你可能感兴趣的:(Flask-mail 发送邮件)