首先进入虚拟环境安装flask-mail扩展模块
pip install flask-mail
发送邮件需要配置发送邮件的服务器。flask-mail固定的配置变量名如下
在macos或者linux操作系统中使用export命令导入环境变量
export MAIL_USERNAME = username
export MAIL_PASSWORD = passowrd
windows操作系统
set MAIL_USERNAME = username
set MAIL_PASSWORD = passoword
同步发送电子邮件
import os
# ...
app.config['MAIL_SERVER'] = 'smtp.googlemail.com' //stmp邮箱服务器
app.config['MAIL_PORT'] = 587 //端口
from flask.ext.mail import Message
from flask.ext.mail import Mail
#...
app.config['MAIL_SUBJECT_PREFIX'] = '[prefix]' //邮件主题前缀
app.config['MAIL_SENDER'] = 'Admin <test@test.test>'
mail = Mail(app)
def send_email(to, subject, template, **kwargs):
msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + subject, sender = app.config['MAIL_SENDER'], recipients=[to])
msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
mail.send(msg) //调用mail实例的send函数发送邮件
app.config['MAIL_USE_TLS'] = True //是否采用安全协议app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME') //从环境变量中获取用户名
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD') //从环境变量中获取密码,一般这种数据配置在环境变量中,防止隐私信息不消息被公布
使用这种方式发送邮件当然是可以的,但是如果网络或者邮件服务器有问题,导致发送邮件出问题或者缓慢,将会导致整个程序运行阻塞。因此最好的方式新开线程异步发送
from threading import Thread
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
def send_mail(to, subject, template, **kwargs):
msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + subject, sender = app.config['MAIL_SENDER'], recipient=[to])
msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
th = Thread(target = send_async_email, args=[app, msg])
th.start()
return th
当然生产环境中如果有很多邮件发送会创建大量大线程,一般是发送到队列中执行。
import os # ... app.config['MAIL_SERVER'] = 'smtp.googlemail.com' //stmp邮箱服务器 app.config['MAIL_PORT'] = 587 //端口
from flask.ext.mail import Message from flask.ext.mail import Mail #... app.config['MAIL_SUBJECT_PREFIX'] = '[prefix]' //邮件主题前缀 app.config['MAIL_SENDER'] = 'Admin <test@test.test>' mail = Mail(app) def send_email(to, subject, template, **kwargs): msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + subject, sender = app.config['MAIL_SENDER'], recipients=[to]) msg.body = render_template(template + '.txt', **kwargs) msg.html = render_template(template + '.html', **kwargs) mail.send(msg) //调用mail实例的send函数发送邮件
app.config['MAIL_USE_TLS'] = True //是否采用安全协议app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME') //从环境变量中获取用户名app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD') //从环境变量中获取密码,一般这种数据配置在环境变量中,防止隐私信息不消息被公布