簡(jiǎn)介
在 Web 應(yīng)用中的一個(gè)最基本的功能就是能夠給用戶(hù)發(fā)送郵件哺徊。
Flask-Mail 擴(kuò)展提供了一個(gè)簡(jiǎn)單的接口驰弄,可以在 Flask 應(yīng)用中設(shè)置 SMTP 使得可以在視圖以及腳本中發(fā)送郵件信息。
安裝
pip install Flask-Mail
配置
Flask-Mail 使用標(biāo)準(zhǔn)的 Flask 配置 API 進(jìn)行配置:
- MAIL_SERVER: 默認(rèn)為'localhost'
- MAIL_PORT: 默認(rèn)為25
- MAIL_USE_TLS:默認(rèn)為 False
- MAIL_USE_SSL:默認(rèn)為 False
- MAIL_DEBUG: 默認(rèn)為None
- MAIL_USERNAME:默認(rèn)為None
- MAIL_PASSWORD:默認(rèn)為None
- MAIL_DEFAULT_SENDER:默認(rèn)為None
- MAIL_MAX_EMAILS:默認(rèn)為None
- MAIL_SUPPRESS_SEND:默認(rèn)為app.testing
- MAIL_ASCII_ATTACHMENTS:默認(rèn)為False
初始化
from flask import Flask
from flask_mail import Mail
app = Flask(__name__)
mail = Mail(app)
也可以在開(kāi)發(fā)中利用工廠(chǎng)模式初始化
from flask import Flask
from flask_mail import Mail
mail = Mail()
app = Flask(__name__)
mail.init_app(app)
發(fā)送郵件
from flask_mail import Message
@app.route("/")
def index():
msg = Message("Hello",
sender="from@example.com",
recipients=["to@example.com"])
也可以設(shè)置一個(gè)或多人接收:
msg.recipients = ["you@example.com"]
msg.add_recipient("somebodyelse@example.com")
如果你在配置文件里設(shè)置MAIL_DEFAULT_SENDER绣的,你就不必在此填寫(xiě)sender,默認(rèn)使用配置項(xiàng)的sender:
msg = Message("Hello",
recipients=["to@example.com"])
同時(shí)sender也可以設(shè)置為二元組叠赐,分別為姓名,郵件地址:
msg = Message("Hello",
sender=("Me", "me@example.com"))
assert msg.sender == "Me <me@example.com>"
郵件的內(nèi)容包含主題甚至是html文件:
msg.body = "testing"
msg.html = "<b>testing</b>"
所有信息配置就緒最后就是發(fā)送郵件:
mail.send(msg)
郵件的信息內(nèi)也可以添加附件:
with app.open_resource("image.png") as fp:
msg.attach("image.png", "image/png", fp.read())
下面引用一下李輝大神 項(xiàng)目中的代碼:
# -*- 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)