Flask邮件发送

1、Flask通过flask-mail插件支持邮件发送
pip install flask-mail
pip install flask-script

2、下述将从两种方式验证flask-mail发送邮件,一种是脚本执行,另一种是集成在应用(程序)中发送邮件

2.1脚本方式,emails.py

from flask import Flask

from flask_mail import Message,Mail

from flask_script import Manager,Shell

import os

app=Flask( __name__)

manager=Manager(app)

mail=Mail(app)

app.config['MAIL_SERVER']="smtp.163.com"  #各个邮件服务商MAIL_SERVER不同

app.config['MAIL_PORT']=465

app.config['MAIL_USE_SSL']=True

app.config['MAIL_USERNAME']=os.environ.get("MAIL_USERNAME")

app.config['MAIL_PASSWORD']=os.environ.get("MAIL_PASSWORD")

(flask-venv) $export MAIL_USERNAME="[email protected]"

(flask-venv) $export MAIL_PASSWORD="xxxxxxx"

python emails.py shell

>>>from flask_mail import Message

>>>from emails import mail

>>>msg=Message("test subject",sender="[email protected]",

recipients=['[email protected]'])    

>>>msg.body="text body"

>>>msg.html='HTMLbody'

>>>with app.app_context():

...    mail.send(msg)

...

>>>

2.2 邮件发送集成到应用的方式,其中用到了多线程技术(threading)

#encoding=utf-8

from flask import Flask,render_template

from flask_mail import Message,Mailfrom threading 

import Threadfrom flask_script import Manager,Shell

import os app=Flask(__name__)

app.config['MAIL_SERVER']='smtp.163.com'

app.config['MAIL_PORT']=465

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)manager=Manager(app)

def send_async_email(app,msg):    

    with app.app_context():              #激活上下文?        

        mail.send(msg)                   

@app.route('/')

def index():    

    msg=Message('主题',sender=os.environ.get('MAIL_USERNAME'),

recipients=['[email protected]'])                       

    msg.body="文本body"    

    msg.html='HTMLbody'    

    thread=Thread(target=send_async_email,args=[app,msg])          

    thread.start()    

    mail.send(msg)    

    return '异步邮件发送成功。'

if __name__  ==  '__main__': 

    manager.run()

运行:python emails.py runserver -h 0.0.0.0 -p9090 页面刷新即可发送邮件

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