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

无法通过Django发送邮件:/index/触发Internal Server Error

Fixing Django Email Sending: SMTPServerDisconnected Error

Hey there, that smtplib.SMTPServerDisconnected: Connection unexpectedly closed error means Django can’t maintain a stable connection with your SMTP email server. Let’s walk through the most likely fixes to get your form-based email sending up and running:

1. Double-Check Your Django Email Configuration (settings.py)

This is the most common culprit. Make sure your email settings match your provider’s requirements exactly. Here are examples for popular providers:

For Gmail (with 2FA enabled):

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'your-gmail-address@gmail.com'
# Important: Use an App Password instead of your regular login password (required for 2FA)
EMAIL_HOST_PASSWORD = 'your-gmail-app-password'

For QQ Mail:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.qq.com'
EMAIL_PORT = 465
EMAIL_USE_SSL = True
EMAIL_HOST_USER = 'your-qq-email@qq.com'
# Use the authorization code generated from QQ Mail's SMTP settings page
EMAIL_HOST_PASSWORD = 'your-qq-authorization-code'

Key notes:

  • Never hardcode passwords in settings.py in production! Use environment variables instead (e.g., os.getenv('EMAIL_HOST_PASSWORD')).
  • Ensure you’re using the correct encryption type (EMAIL_USE_TLS vs EMAIL_USE_SSL) and matching port for your provider.

2. Verify Your Email Provider’s SMTP Settings

  • Enable SMTP access: Most providers (Gmail, QQ, Outlook) require you to manually turn on SMTP service in your account settings.
  • Use an authorization/app password: If you have two-factor authentication (2FA) enabled on your email account, your regular login password won’t work for SMTP. You’ll need to generate a dedicated app password or authorization code from your email provider’s security settings.

3. Test Network & Firewall Access

  • On your local machine: Check if your firewall or antivirus is blocking outgoing connections to ports 587 (TLS) or 465 (SSL).
  • On a production server: Some hosting providers block default SMTP ports (like 25). Confirm your host allows outgoing connections to 587 or 465, or use their recommended email service (e.g., SendGrid, Mailgun) if SMTP is restricted.

4. Test SMTP Connection Outside Django

To rule out Django-specific issues, run this simple Python script to test your SMTP setup directly:

import smtplib
from email.message import EmailMessage

# Configure your details here
sender_email = "your-email@example.com"
sender_password = "your-app-password/authorization-code"
recipient_email = "avulapradeep333@gmail.com"

msg = EmailMessage()
msg.set_content("This is a test email from Python's smtplib!")
msg["Subject"] = "Test SMTP Connection"
msg["From"] = sender_email
msg["To"] = recipient_email

try:
    # Match your provider's SMTP host and port
    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls()  # Use this if your provider uses TLS
        server.login(sender_email, sender_password)
        server.send_message(msg)
    print("Email sent successfully!")
except Exception as e:
    print(f"Error connecting to SMTP server: {str(e)}")

If this script fails, the issue is with your email settings or network—not Django. If it works, double-check that your Django settings.py has identical values.

5. Confirm Your View Code is Correct

In your views.py, make sure you’re importing settings correctly and passing valid arguments to send_mail:

from django.conf import settings
from django.core.mail import send_mail
from django.shortcuts import render

def index(request):
    if request.method == "POST":
        # Add your form processing logic here if needed
        send_mail(
            "Email Subject",
            "Email message content",
            settings.EMAIL_HOST_USER,
            ["avulapradeep333@gmail.com"],
            fail_silently=False
        )
        # Add success handling (e.g., redirect to a success page)
    return render(request, "index.html")
  • Ensure settings.EMAIL_HOST_USER is correctly referenced (no typos like EMAIL_USER instead of EMAIL_HOST_USER).
  • Keep fail_silently=False (like you did) to get detailed error messages for debugging.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:36:32