当前位置: 首页 > news >正文

Flask(九)邮件发送与通知系统

在 Web 应用中,邮件通知是常见的功能,如:

  • 用户注册验证邮件
  • 密码找回邮件
  • 订单确认邮件
  • 订阅通知邮件

Flask 可以通过 Flask-MailFlask-Mailman 或 第三方 API(如 SendGrid、Mailgun) 发送邮件。本章介绍:

  1. 使用 Flask-Mail 发送邮件
  2. 发送带附件的邮件
  3. 使用 Flask-Mailman 发送邮件
  4. 使用 Celery 异步发送邮件
  5. 使用 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 的日志与错误处理

相关文章:

  • 分布式架构:Dubbo 协议如何做接口测试
  • 从振动谐波看电机寿命:PdM策略下的成本控制奇迹
  • Json快速入门
  • C++中的move操作
  • python 判断字符串是否包含关键字
  • 7.2 重复推送(每日、每周等)
  • springboot集成kafka,后续需要通过flask封装restful接口
  • 基于 Node.js 和 Spring Boot 的 RSA 加密登录实践
  • 程序化广告行业(70/89):ABTester系统助力落地页优化实践
  • 【C++篇】深入解析C/C++内存管理:从原理到实践
  • c语言 文件操作
  • MTO和MTS不同模式制造业数字化转型的“三座大山“:MES/ERP/PLM系统集成技术全解析
  • Buffer Pool 的核心作用与工作机制
  • uni-app使用web-view传参的坑
  • HOW - React Error Catch 机制
  • Three.js 系列专题 7:性能优化与最佳实践
  • TVBOX最新配置接口\直播源接口 收集整理【 2025.4】
  • Token无感刷新
  • 蓝桥杯备赛 Day 21 图论基础
  • 拼多多商品详情接口爬虫实战指南
  • 杭州“放大招”支持足球发展:足球人才可评“高层次人才”
  • 国家林业和草原局原党组成员、副局长李春良接受审查调查
  • 巴基斯坦全国航班仍持续延误或取消
  • 我国成功发射遥感四十号02组卫星
  • 当我们提起拉动消费时,应该拉动什么消费?
  • 韩国执政党总统候选人更换方案被否决,金文洙候选人资格即刻恢复