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

Flask应用SMTP邮件发送失败(500内部服务器错误)

问题:Flask联系表单提交出现500内部服务器错误

我用Python和Flask开发网站,搭建的联系表单模态框能正常打开填写,但提交时触发500内部服务器错误。已验证SMTP服务可正常发信,推测是代码问题,怀疑sender参数需要是列表,求解答。


相关代码

Flask后端代码

from flask import Flask, render_template, send_from_directory, request
from flask_mail import Mail, Message
from config import sender_mail_username, sender_mail_password, recipient_mail_username

app = Flask(__name__)

mail = Mail(app)

app.config["MAIL_SERVER"] = "smtp.gmail.com"
app.config["MAIL_PORT"] = 465
app.config["MAIL_USE_TLS"] = False
app.config["MAIL_USE_SSL"] = True
app.config["MAIL_USERNAME"] = sender_mail_username
app.config["MAIL_PASSWORD"] = sender_mail_password


@app.route("/")
def home():
    return render_template("home.html")


@app.route("/", methods=["GET", "POST"])
def contact():
    if request.method == "POST":
        email = request.form.get("email")
        subject = request.form.get("subject")
        message = request.form.get("message")

        msg = Message(sender=sender_mail_username, recipients=recipient_mail_username,
                      subject="UNIFINITY Contact Form submission", body=f"Email {email}\nSubject: {subject}"
                                                                        f"\n\n{message}")
        mail.send(msg)
    return render_template("sent.html")


if __name__ == "__main__":
app.run()

前端表单代码

表单提交方法:

<form name="contact" role="form" method="POST">

提交按钮:

<button type="submit" class="btn btn-dark">Send</button>

报错回溯信息

Traceback (most recent call last):
  File "/Users/Jules/Documents/IT/Pycharm/UNIFINITY Webpage/webpage.py", line 35, in contact
    mail.send(msg)
  File "/Users/Jules/Library/Python/3.9/lib/python/site-packages/flask_mail.py", line 491, in send
    with self.connect() as connection:
  File "/Users/Jules/Library/Python/3.9/lib/python/site-packages/flask_mail.py", line 144, in __enter__
    self.host = self.configure_host()
  File "/Users/Jules/Library/Python/3.9/lib/python/site-packages/flask_mail.py", line 158, in configure_host
    host = smtplib.SMTP(self.mail.server, self.mail.port)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/smtplib.py", line 255, in __init__
    (code, msg) = self.connect(host, port)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/smtplib.py", line 341, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/smtplib.py", line 312, in _get_socket
    return socket.create_connection((host, port), timeout,
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/socket.py", line 843, in create_connection
    raise err
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/socket.py", line 831, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 61] Connection refused
[2023-12-05 09:31:58,550] ERROR in app: Exception on / [POST]
Traceback (most recent call last):
  File "/Library/Python/3.9/site-packages/flask/app.py", line 1455, in wsgi_app
    response = self.full_dispatch_request()
  File "/Library/Python/3.9/site-packages/flask/app.py", line 870, in full_dispatch_request
    return self.finalize_request(rv)
  File "/Library/Python/3.9/site-packages/flask/app.py", line 889, in finalize_request
    response = self.make_response(rv)
  File "/Library/Python/3.9/site-packages/flask/app.py", line 1161, in make_response
    raise TypeError(
TypeError: The view function for 'contact' did not return a valid response. The function either returned None or ended without a return statement.
127.0.0.1 - - [05/Dec/2023 09:31:58] "POST / HTTP/1.1" 500 -

问题分析与修复方案

1. SMTP连接初始化顺序错误

报错里的ConnectionRefusedError是因为先初始化了Mail对象,后配置邮件参数,导致Mail实例未读取到正确的SMTP配置。
修复:调整初始化顺序

app = Flask(__name__)

# 先配置邮件参数
app.config["MAIL_SERVER"] = "smtp.gmail.com"
app.config["MAIL_PORT"] = 465
app.config["MAIL_USE_TLS"] = False
app.config["MAIL_USE_SSL"] = True
app.config["MAIL_USERNAME"] = sender_mail_username
app.config["MAIL_PASSWORD"] = sender_mail_password

# 再初始化Mail对象
mail = Mail(app)

2. recipients参数格式错误

Flask-Mail要求recipients必须是列表类型,而非单个字符串。你的怀疑(sender需要是列表)不正确,问题出在收件人参数上。
修复:将收件人转为列表

msg = Message(
    sender=sender_mail_username,
    recipients=[recipient_mail_username],  # 改为列表格式
    subject="UNIFINITY Contact Form submission",
    body=f"Email {email}\nSubject: {subject}\n\n{message}"
)

3. 视图函数响应不完整

报错里的TypeError是因为邮件发送抛出异常时,视图函数没有返回合法响应。需添加异常捕获,确保所有分支都有返回值,同时合并重复的根路由:

@app.route("/", methods=["GET", "POST"])
def contact():
    if request.method == "POST":
        email = request.form.get("email")
        subject = request.form.get("subject")
        message = request.form.get("message")
        try:
            msg = Message(
                sender=sender_mail_username,
                recipients=[recipient_mail_username],
                subject="UNIFINITY Contact Form submission",
                body=f"Email {email}\nSubject: {subject}\n\n{message}"
            )
            mail.send(msg)
            return render_template("sent.html")
        except Exception as e:
            return render_template("error.html", error=str(e)), 500
    # GET请求返回首页
    return render_template("home.html")

4. Gmail SMTP额外配置(若使用Gmail)

  • 若开启了2FA,需使用应用专用密码替代普通密码
  • 未开启2FA时,需开启"低安全性应用访问"权限
  • 检查本地防火墙/代理是否阻止465端口的出站连接

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 22:33:22