Flask(九)邮件发送与通知系统
在 Web 应用中,邮件通知是常见的功能,如:
- 用户注册验证邮件
- 密码找回邮件
- 订单确认邮件
- 订阅通知邮件
Flask 可以通过 Flask-Mail、Flask-Mailman 或 第三方 API(如 SendGrid、Mailgun) 发送邮件。本章介绍:
- 使用 Flask-Mail 发送邮件
- 发送带附件的邮件
- 使用 Flask-Mailman 发送邮件
- 使用 Celery 异步发送邮件
- 使用 SendGrid 发送邮件
9.1 安装 Flask-Mail
首先,安装 Flask-Mail:
pip install Flask-Mail
然后,在 app.py 中进行配置:
from flask import Flask, render_template, request
from flask_mail import Mail, Message
app = Flask(__name__)
# 邮件服务器配置
app.config['MAIL_SERVER'] = 'smtp.gmail.com' # 邮件服务器(Gmail、QQ 邮箱)
app.config['MAIL_PORT'] = 587 # 端口号
app.config['MAIL_USE_TLS'] = True # 使用 TLS 传输层安全协议
app.config['MAIL_USERNAME'] = 'your-email@gmail.com' # 你的邮箱
app.config['MAIL_PASSWORD'] = 'your-password' # 邮箱密码或授权码
app.config['MAIL_DEFAULT_SENDER'] = ('Your App', 'your-email@gmail.com') # 发件人名称
mail = Mail(app)
9.2 发送简单邮件
定义一个邮件发送函数:
@app.route('/send_email')
def send_email():
msg = Message("Hello from Flask", recipients=["recipient@example.com"])
msg.body = "This is a test email sent from Flask!"
mail.send(msg)
return "Email sent successfully!"
运行应用并测试
启动 Flask:
flask run
然后访问:
http://127.0.0.1:5000/send_email
9.3 发送带 HTML 格式的邮件
Flask-Mail 支持 HTML 邮件:
@app.route('/send_html_email')
def send_html_email():
msg = Message("HTML Email from Flask", recipients=["recipient@example.com"])
msg.html = "<h1>Welcome</h1><p>This is an <b>HTML email</b> sent from Flask.</p>"
mail.send(msg)
return "HTML Email sent!"
9.4 发送带附件的邮件
@app.route('/send_email_with_attachment')
def send_email_with_attachment():
msg = Message("Email with Attachment", recipients=["recipient@example.com"])
msg.body = "Please find the attachment."
with app.open_resource("static/sample.pdf") as attachment:
msg.attach("sample.pdf", "application/pdf", attachment.read())
mail.send(msg)
return "Email with attachment sent!"
9.5 使用 Flask-Mailman 发送邮件
Flask-Mail 维护较少,推荐使用 Flask-Mailman 作为替代:
pip install Flask-Mailman
修改 app.py:
from flask_mailman import Mail, EmailMessage
mail = Mail(app)
@app.route('/send_mailman_email')d
ef send_mailman_email():
msg = EmailMessage(
subject="Hello from Flask-Mailman",
body="This is a test email from Flask-Mailman!",
to=["recipient@example.com"]
)
msg.send()
return "Email sent using Flask-Mailman!"
9.6 使用 Celery 异步发送邮件
避免 Flask 请求阻塞,建议使用 Celery 进行异步邮件发送。
安装 Celery
pip install celery
配置 Celery
在 celery_config.py:
from celery import Celery
def make_celery(app):
celery = Celery(
app.import_name,
backend=app.config['CELERY_RESULT_BACKEND'],
broker=app.config['CELERY_BROKER_URL']
)
celery.conf.update(app.config)
return celery
修改 app.py:
from celery_config import make_celery
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'
celery = make_celery(app)
定义异步任务
@celery.task
def send_async_email(recipient):
msg = Message("Async Email", recipients=[recipient])
msg.body = "This email was sent asynchronously using Celery!"
mail.send(msg)
调用异步任务
@app.route('/send_async_email/<email>')
def send_async(email):
task = send_async_email.apply_async(args=[email])
return f"Email is being sent asynchronously. Task ID: {task.id}"
运行 Celery Worker
celery -A app.celery worker --loglevel=info
9.7 使用 SendGrid 发送邮件
9.7.1 注册 SendGrid 并获取 API Key
- 访问 SendGrid 注册账号
- 在 "API Keys" 处生成 API Key
9.7.2 安装 SendGrid 库
pip install sendgrid
9.7.3 配置 SendGrid
import sendgrid
from sendgrid.helpers.mail import Mail
SENDGRID_API_KEY = "your_sendgrid_api_key"
def send_email_via_sendgrid(to_email):
sg = sendgrid.SendGridAPIClient(api_key=SENDGRID_API_KEY)
message = Mail(
from_email="your-email@gmail.com",
to_emails=to_email,
subject="Hello from SendGrid",
html_content="<strong>This is a test email sent via SendGrid.</strong>"
)
response = sg.send(message)
return response.status_code
调用:
@app.route('/send_sendgrid/<email>')
def send_via_sendgrid(email):
status = send_email_via_sendgrid(email)
return f"SendGrid Email Sent! Status: {status}"
9.8 发送批量邮件
@app.route('/send_bulk_email')
def send_bulk_email():
recipients = ["user1@example.com", "user2@example.com"]
msg = Message("Bulk Email", recipients=recipients)
msg.body = "This is a bulk email sent to multiple users."
mail.send(msg)
return "Bulk Email Sent!"
9.9 结语
本章介绍了 Flask 发送邮件的多种方法:
- Flask-Mail(传统方式)
- Flask-Mailman(更好的维护支持)
- Celery 异步邮件(解决阻塞问题)
- SendGrid API(适用于企业邮件)
下一章,我们将探讨 Flask 的日志与错误处理。