You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何完善Python+Flask+Jinja2环境下SMTP模板邮件发送函数?

完成SMTP邮件发送的send_email函数实现

核心实现代码

直接补充send_email函数的SMTP逻辑即可,以下是带注释的完整实现:

def send_email(to, subj, body):
    # 替换为你的邮箱配置信息
    FROM_EMAIL = "your-sender-email@example.com"
    SMTP_SERVER = "smtp.example.com"  # 示例:Gmail用smtp.gmail.com,QQ邮箱用smtp.qq.com
    SMTP_PORT = 465  # SSL加密端口,多数邮箱默认用465;若用STARTTLS则填587
    SMTP_PASSWORD = "your-email-app-password"  # 优先用邮箱授权码,而非登录密码

    # 构建邮件对象
    msg = EmailMessage()
    msg["Subject"] = subj
    msg["From"] = FROM_EMAIL
    msg["To"] = to
    # 标记内容为HTML格式,确保模板渲染的HTML能正确显示
    msg.set_content(body, subtype="html")

    try:
        # 建立加密SMTP连接并发送邮件
        with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT) as server:
            server.login(FROM_EMAIL, SMTP_PASSWORD)
            server.send_message(msg)
        print("邮件发送成功")
    except Exception as e:
        print(f"邮件发送失败: {str(e)}")

不同SMTP端口的适配

如果你的邮箱要求使用STARTTLS协议(端口通常为587),将连接部分修改为:

with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
    server.starttls()  # 启用加密传输
    server.login(FROM_EMAIL, SMTP_PASSWORD)
    server.send_message(msg)

Flask项目的最佳实践

为避免硬编码敏感信息,建议将邮箱配置存入Flask的配置中:

# 在Flask app初始化时添加配置
app.config.update(
    FROM_EMAIL="your-sender-email@example.com",
    SMTP_SERVER="smtp.example.com",
    SMTP_PORT=465,
    SMTP_PASSWORD="your-email-app-password"
)

# 修改send_email函数读取配置
def send_email(to, subj, body):
    from flask import current_app

    msg = EmailMessage()
    msg["Subject"] = subj
    msg["From"] = current_app.config["FROM_EMAIL"]
    msg["To"] = to
    msg.set_content(body, subtype="html")

    try:
        with smtplib.SMTP_SSL(current_app.config["SMTP_SERVER"], current_app.config["SMTP_PORT"]) as server:
            server.login(current_app.config["FROM_EMAIL"], current_app.config["SMTP_PASSWORD"])
            server.send_message(msg)
        print("邮件发送成功")
    except Exception as e:
        print(f"邮件发送失败: {str(e)}")

注意事项

  • 多数邮箱(如Gmail、QQ邮箱)需要手动开启SMTP服务,并生成授权码替代登录密码,直接用登录密码可能会被拦截
  • 开发阶段可使用本地测试SMTP服务(如smtp4dev),避免发送真实邮件干扰他人
  • 保留异常捕获逻辑,防止邮件发送失败导致Flask请求崩溃

内容的提问来源于stack exchange,提问作者tv_dinner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 08:57:14