Flask-mail
安装
(venv) $ pip install flask-mail
配置信息
FLASK-MAIL SMTP服务器配置信息
配置 | 默认值 | 说明 |
---|---|---|
MAIL_SERVER | localhost | 电子邮件服务器的主机名或ip地址 |
MAIL_PORT | 25 | 电子邮件服务器的端口 |
MAIL_USE_TLS | False | 启动传输层安全(TLS translate layer security)协议 |
MAIL_USE_SSL | False | 启动安全套阶层(SSL secure sockets layer)协议 |
MAIL_USERNAME | None | 邮箱账号的用户名 |
MAIL_PASSWORD | None | 邮箱账户的密码 |
服务器名、地址与端口
服务器名称 | 服务器地址 | SSL协议端口号 | 非SSL协议端口号 |
---|---|---|---|
IMAP | imap.163.com | 993 | 143 |
SMTP | smtp.163.com | 465/994 | 25 |
smtp.126.com | 465/994 | 25 | |
POP3 | Pop.163.com | 995 | 110 |
配置使用
import os
# ...
from flask_mail import Mail
app.config['MAIL_SERVER'] = 'smtp.126.com'
app.config['MAIL_PORT'] = 25
# 开源作品,账号密码千万不要直接写入脚本
app.config['MAIL_USERNAME'] = os.environ.get("mail_username")
app.config['MAIL_PASSWORD'] = os.environ.get("mail_password")
# Flask_Mail初始化
mail = Mail(app)
一次性环境变量设置
(venv) set MAIL_USERNAME = {username}
在python shell中发送
注意,Flask-Mail 中的 send() 函数使用 current_app,因此要在激活的程序上下文中执行。
(venv) E:\blog>set FLASK_APP=hello.py
from flask_mail import Message
from hello import mail
mail_title = "test mail"
sender = "sender@126.com"
recipients = ["recipient1@163.com"]
msg = Message(mail_title, sender=sender, recipients=recipients)
msg.body = "test body"
msg.html = "<h1> html </h1>"
with app.app_context():
mail.send(msg)
在应用中集成功能
定义发邮件函数,在视图函数中调用
#...
# 配置邮件信息
app.config['FLASKY_ADMIN'] = os.environ.get('FLASKY_ADMIN')
app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin <xxx@163.com>'
def send_main(to, subject, template, **kwargs):
msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
mail.send(msg)
@app.route('/', methods=['POST', 'GET'])
def index():
form = NameForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.name.data).first()
if not user:
user = User(username=form.name.data, password='123456')
db.session.add(user)
db.session.commit()
session['known'] = False
send_mail(form.name.data)
else:
session['known'] = True
session['name'] = request.form.get("name")
form.name.data = ""
return redirect(url_for('index'))
return render_template('index.html', form=form, name=session.get('name'))
异步发送邮件
在处理mail.send函数时停滞了几秒钟,为了在处理请求过程中避免不必要的延迟,将发送电子邮件函数移到后台线程中
#...
# 配置邮件信息
app.config['FLASKY_ADMIN'] = os.environ.get('FLASKY_ADMIN')
app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin <xxx@163.com>'
def send_main(to, subject, template, **kwargs):
msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
thr = Thread(target=send_async_email(), args=[app, msg])
thr.start()
return thr
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
@app.route('/', methods=['POST', 'GET'])
def index():
form = NameForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.name.data).first()
if not user:
user = User(username=form.name.data, password='123456')
db.session.add(user)
db.session.commit()
session['known'] = False
send_async_email()
else:
session['known'] = True
session['name'] = request.form.get("name")
form.name.data = ""
return redirect(url_for('index'))
return render_template('index.html', form=form, name=session.get('name'))