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

Flask博客站点Post请求后发送邮件失败问题排查

Flask表单提交后邮件发送失败问题排查

我在Flask搭建的博客站点中,希望用户提交Contact表单(POST请求完成后)自动发送邮件。表单提交的变量均能正常获取,但send_mail函数执行后,邮件始终无法送达收件箱。相关代码如下:

import smtplib
from flask import Flask, request, render_template

app = Flask(__name__)

def send_mail(who_will_receive: str, subject: str, message: str):
    """发送邮件给指定用户"""
    my_google_email = "email@gmail.com"
    password_google = "apppassword"  # 已替换为谷歌应用密码

    with smtplib.SMTP(host="smtp.gmail.com", port=587, timeout=120) as connection:
        connection.starttls()
        connection.login(user=my_google_email, password=password_google)
        connection.sendmail(
            from_addr=my_google_email,
            to_addrs=who_will_receive,
            msg=f"Subject: {subject}\n\n{message}".encode("utf8")
        )

@app.route("/contact", methods=["POST", "GET"])
def contact_page():
    if request.method == "POST":
        name = request.form['name']
        email = request.form['email']
        phone = request.form['phone']
        message = request.form['message']
        # 以下变量均能正常打印,说明表单数据获取正常
        print(name, email, phone, message)
        # 调用发送邮件函数,但邮件未送达
        send_mail("mymail@gmail.com", f"Contact from {name}", f"Name: {name}\nEmail: {email}\nPhone Number: {phone}\nMessage: {message}")
        return render_template("contact.html", form_submitted=True)
    return render_template("contact.html")

已尝试更换谷歌应用密码、为SMTP连接添加timeout=120参数,问题仍未解决。


排查与解决办法
  • 检查垃圾邮件/促销文件夹:谷歌邮箱会自动过滤自动发送的邮件,先去垃圾箱、促销邮件目录查找是否有目标邮件。
  • 补充邮件头部信息:当前邮件仅包含Subject字段,缺少From和To标识,容易被邮件服务器判定为垃圾邮件。修改邮件内容格式:
    msg = f"From: {my_google_email}\nTo: {who_will_receive}\nSubject: {subject}\n\n{message}".encode("utf8")
    
  • 添加异常捕获排查错误:原代码未处理发送过程中的异常,可能存在隐性错误。修改send_mail函数,添加错误捕获与打印:
    def send_mail(who_will_receive: str, subject: str, message: str):
        my_google_email = "email@gmail.com"
        password_google = "apppassword"
        try:
            with smtplib.SMTP(host="smtp.gmail.com", port=587, timeout=120) as connection:
                connection.starttls()
                connection.login(user=my_google_email, password=password_google)
                msg = f"From: {my_google_email}\nTo: {who_will_receive}\nSubject: {subject}\n\n{message}".encode("utf8")
                connection.sendmail(from_addr=my_google_email, to_addrs=who_will_receive, msg=msg)
            print("邮件发送成功")
        except smtplib.SMTPException as e:
            print(f"SMTP发送错误:{str(e)}")
        except Exception as e:
            print(f"未知错误:{str(e)}")
    
  • 确认谷歌账号配置:
    • 确保账号已开启两步验证,应用密码是在两步验证开启后生成的(未开启两步验证无法生成有效应用密码)。
    • 登录谷歌账号查看「最近活动」,确认SMTP登录是否被系统拦截,若有拦截提示,手动允许该设备/IP的登录请求。
  • 切换SMTP连接方式:尝试使用SSL协议的465端口替代TLS的587端口:
    with smtplib.SMTP_SSL(host="smtp.gmail.com", port=465, timeout=120) as connection:
        connection.login(user=my_google_email, password=password_google)
        msg = f"From: {my_google_email}\nTo: {who_will_receive}\nSubject: {subject}\n\n{message}".encode("utf8")
        connection.sendmail(from_addr=my_google_email, to_addrs=who_will_receive, msg=msg)
    
  • 验证收件人地址:确认send_mail中传入的收件地址"mymail@gmail.com"拼写完全正确,无大小写或字符错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 11:32:01