Flask之电子邮件
使用Flask-Mail提供电子邮件支持
Flask-Mail连接到简单邮件传输协议服务器,并把邮件交给这个服务器发送。
示例:配置Flask-Mail 使用Gmail
import os
#...
app.config['MAIL_SERVER']='smtp.googlemail.com'
app.config['MAIL_PORT']=587
app.config['MAIL_USE_TLS']=TRUE
app.config['MAIL_USERNAME']=os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD']=os.environ.get('MAIL_PASSWORD')
初始化Flask-Mail
from flask.ext.mail import Mail
mail=Mail(app)
保存电子邮件服务器用户名和密码的两个环境变量要在环境中定义。
set MAIL_USERNAME=<Gmail username>
set MAIL_PASSWORD=<Gmail password>
set FLASKY_ADMIN=<Gmail username>
发送测试邮件
from flask.ext.mail import Message
from hello import mail
msg=Message('test subject',sender='you@example.com',recipients=['you@example.com'])
msg.body='text body'
msg.html='<b>HTML</b> body'
with app.app_context():
mail.send(msg)
把发送电子邮件的通用部分抽象出来,避免每次手动编写电子邮件消息,使用 Jinja2 模板渲染邮件正文,灵活性极高。
from flask.ext.mail import Message
app.config['FLASK_MAIL_SUBJECT_PREFIX']='[Flasky]'
app.config['FLASKY_MAIL_SENDER']='Flask Admin <flasky@example.com>'
#这两个是程序特定配置项,分别定义邮件主题的前缀和发件人的地址。
def send_email(to,subject,template,**kwargs)
# send_email 函数的参数分别为收件人地址、主题、渲染邮件正文的模板和关键字参数列表。
msg=Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX']+subject,sender=app.config['FLASKY_MAIL_SENDER'],recipients=[to])
msg.body=render_template(tempalte+'.txt',**kwargs)
msg.html=render_template(tempalte+'.html',**kwargs)
mail.send(msg)
每当表单接收新名字时,程序都会给管理员发送一封电子邮件
#...
app.config['FLASKY_ADMIN']=os.environ.get('FLASKY_ADMIN')
#...
@app.route('/',methods=['GET','POST'])
def index():
form=NameForm
if form.validate_on_submit():
user=User.query.filter_by(username=form.name.data).first()
if user is None:
user=User(username=form.name.data)
db.session.add(user)
session['known']=Flase
if app.config['FLASKY_ADMIN']:
send_email(app.config['FLASKY_ADMIN'],'New User','mail/new_user',user=user)
else:
session['known']=True
session['name']=form.name.data
form.name.data=''
return redirect(url_for('index'))
return render_template('index.html',form=form,name=session.get('name'),known=session.get('known'),Flase)
把发送电子邮件的函数移到后台线程中
from threading import Thread
def send_async_email(app,msg):
with app.app_context():
mail.send(msg)
def send_email(to,subject,template,**kwargs):
msg=Message(app.config['FLASKY_MAIL_SENDER'],recipients=[to])
msg.body=render_template(tempalte+'.txt',**kwargs)
msg.html=render_template(template+'.html',**kwargs)
thr=Thread(target=send_async_email,args=[app,msg])
thr.start()
return thr