(学习flask) 05 使用flask-mail

使用flask-mail扩展

pip install flask-mail

1.配置邮箱

(1)我这里使用的是163邮箱,首先需要打开邮箱,找到下图这里
(学习flask) 05 使用flask-mail_第1张图片
(2)开启SMTP服务,然后申请授权密码,需要绑定手机号
(学习flask) 05 使用flask-mail_第2张图片
(3)163的服务器地址和端口如下
(学习flask) 05 使用flask-mail_第3张图片

2.配置app.config

这里把用户名和密码都配进了本地的系统变量中

from flask import Flask
import os

app=Flask(__name__)
app.config['MAIL_SERVER']='smtp.163.com'
app.config['MAIL_PORT']=994
app.config['MAIL_USE_TLS']=False
app.config['MAIL_USE_SSL']=True
app.config['MAIL_USERNAME']=os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD']=os.environ.get('MAIL_PASSWORD')

3.初始化邮箱

flask_mail会自动帮我们创建好SMTP服务器

from flask_mail import Mail,Message
mail=Mail(app)

4.同步方式发送邮件

@app.route('/sendMail')
def sendMail():
    msg=Message('test message',sender=os.environ.get('MAIL_USERNAME'),recipients=['[email protected]'])
    msg.body='this is body!'
    msg.html='HTML body'
    with app.app_context():
        mail.send(msg)
    return '

发送成功!

'

5.异步方式发送邮件

def send_async_mail(app,msg):
    with app.app_context():
        mail.send(msg)

def send_mail(to,subject,template,**kwargs):
    msg=Message('async test '+subject,sender=os.environ.get('MAIL_USERNAME'),recipients=[to])
    msg.body=render_template(template+'.txt',**kwargs)
    msg.body = render_template(template+'.html', **kwargs)
    th=Thread(target=send_async_mail,args=[app,msg])
    th.start()
    return th

@app.route('/sendSync')
def send_async():
    to='[email protected]'
    subject='ASYNC'
    template='test'
    send_mail(to,subject,template)
    return '

ASYNC 发送成功!

'

6.完整代码

# coding:utf-8
from flask import Flask,render_template
import os
from flask_mail import Mail,Message

from threading import Thread

app=Flask(__name__)
app.config['MAIL_SERVER']='smtp.163.com'
app.config['MAIL_PORT']=994
app.config['MAIL_USE_TLS']=False
app.config['MAIL_USE_SSL']=True
app.config['MAIL_USERNAME']=os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD']=os.environ.get('MAIL_PASSWORD')
mail=Mail(app)

def send_async_mail(app,msg):
    with app.app_context():
        mail.send(msg)

def send_mail(to,subject,template,**kwargs):
    msg=Message('async test '+subject,sender=os.environ.get('MAIL_USERNAME'),recipients=[to])
    msg.body=render_template(template+'.txt',**kwargs)
    msg.body = render_template(template+'.html', **kwargs)
    th=Thread(target=send_async_mail,args=[app,msg])
    th.start()
    return th

@app.route('/sendSync')
def send_async():
    to='[email protected]'
    subject='ASYNC'
    template='test'
    send_mail(to,subject,template)
    return '

ASYNC 发送成功!

'
@app.route('/sendMail') def sendMail(): msg=Message('test message',sender=os.environ.get('MAIL_USERNAME'),recipients=['[email protected]']) msg.body='this is body!' msg.html='HTML body' with app.app_context(): mail.send(msg) return '

发送成功!

'
if __name__=='__main__': app.run(debug=True)

你可能感兴趣的:(Coding,flask)