简介
在 Web 应用中的一个最基本的功能就是能够给用户发送邮件。
Flask-Mail 扩展提供了一个简单的接口,可以在 Flask 应用中设置 SMTP 使得可以在视图以及脚本中发送邮件信息。
安装
pip install Flask-Mail
配置
Flask-Mail 使用标准的 Flask 配置 API 进行配置:
- MAIL_SERVER: 默认为'localhost'
- MAIL_PORT: 默认为25
- MAIL_USE_TLS:默认为 False
- MAIL_USE_SSL:默认为 False
- MAIL_DEBUG: 默认为None
- MAIL_USERNAME:默认为None
- MAIL_PASSWORD:默认为None
- MAIL_DEFAULT_SENDER:默认为None
- MAIL_MAX_EMAILS:默认为None
- MAIL_SUPPRESS_SEND:默认为app.testing
- MAIL_ASCII_ATTACHMENTS:默认为False
初始化
from flask import Flask
from flask_mail import Mail
app = Flask(__name__)
mail = Mail(app)
也可以在开发中利用工厂模式初始化
from flask import Flask
from flask_mail import Mail
mail = Mail()
app = Flask(__name__)
mail.init_app(app)
发送邮件
from flask_mail import Message
@app.route("/")
def index():
msg = Message("Hello",
sender="[email protected]",
recipients=["[email protected]"])
也可以设置一个或多人接收:
msg.recipients = ["[email protected]"]
msg.add_recipient("[email protected]")
如果你在配置文件里设置MAIL_DEFAULT_SENDER,你就不必在此填写sender,默认使用配置项的sender:
msg = Message("Hello",
recipients=["[email protected]"])
同时sender也可以设置为二元组,分别为姓名,邮件地址:
msg = Message("Hello",
sender=("Me", "[email protected]"))
assert msg.sender == "Me "
邮件的内容包含主题甚至是html文件:
msg.body = "testing"
msg.html = "testing"
所有信息配置就绪最后就是发送邮件:
mail.send(msg)
邮件的信息内也可以添加附件:
with app.open_resource("image.png") as fp:
msg.attach("image.png", "image/png", fp.read())
下面引用一下李辉大神 项目中的代码:
# -*- coding: utf-8 -*-
from threading import Thread
from flask import current_app, render_template
from flask_mail import Message
from albumy.extensions import mail
def _send_async_mail(app, message):
with app.app_context():
mail.send(message)
def send_mail(to, subject, template, **kwargs):
message = Message(current_app.config['ALBUMY_MAIL_SUBJECT_PREFIX'] + subject, recipients=[to])
message.body = render_template(template + '.txt', **kwargs)
message.html = render_template(template + '.html', **kwargs)
app = current_app._get_current_object()
thr = Thread(target=_send_async_mail, args=[app, message])
thr.start()
return thr
def send_confirm_email(user, token, to=None):
send_mail(subject='Email Confirm', to=to or user.email, template='emails/confirm', user=user, token=token)
def send_reset_password_email(user, token):
send_mail(subject='Password Reset', to=user.email, template='emails/reset_password', user=user, token=token)
def send_change_email_email(user, token, to=None):
send_mail(subject='Change Email Confirm', to=to or user.email, template='emails/change_email', user=user, token=token)