赞
踩
首先进入虚拟环境安装flask-mail扩展模块
pip install 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') //从环境变量中获取密码,一般这种数据配置在环境变量中,防止隐私信息不消息被公布
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。