邮件无法发送问题排查及Python邮件发送代码错误分析请求
Hey there, let's tackle your two email sending problems one by one:
一、Troubleshooting "Email Won't Send" General Issues
If your email isn't going through, start checking these common culprits:
- Incorrect SMTP Config: Double-check the SMTP server address and port (e.g., Gmail uses
smtp.gmail.com:587, Outlook usessmtp.office365.com:587). Make sure TLS/SSL is enabled as required. - Authentication Failures: Verify your sender email and password are correct. For Gmail specifically:
- If you have 2-step verification enabled, you need to use an App Password instead of your regular account password.
- The "Less secure apps" option is mostly deprecated now, so App Passwords are the recommended approach.
- Network Blockages: Check if your firewall, antivirus, or proxy is blocking the SMTP port (usually 587 or 465). Try pinging the SMTP server to confirm basic connectivity.
- Invalid Email Format: SMTP requires proper email headers (like
From,To,Subject) and a blank line between headers and body. Missing these can get your message rejected by the server. - Recipient/Sender Restrictions: Ensure the recipient email exists and hasn't blocked you. Also, check if your sender account has hit a daily sending limit (common with free email services).
二、Fixing the Python Code That Always Outputs "Email not sent"
Let's break down the issues in your code and fix them:
1. Overly Broad & Risky Exception Handling
Your except: catches every possible error but gives zero context about what went wrong. Even worse, if an error happens before the server variable is initialized (like a failed connection), calling server.quit() later will throw another error because server doesn't exist yet.
2. Non-Standard Email Format
You're sending raw text as the message, but SMTP expects a properly formatted email with mandatory headers. Without From, To, and Subject fields, most mail servers will reject the message outright.
3. Gmail-Specific Authentication Limits
As mentioned earlier, Gmail no longer allows regular passwords for SMTP login if 2-step verification is enabled. You need an App Password to authenticate successfully.
Corrected Code Example
import smtplib from email.mime.text import MIMEText port = 587 sender_mail = input("Enter your email address : ") # Note: Gmail users with 2FA enabled must use an App Password here sender_password = input("Enter your password : ") receiver_mail = input("Enter receiver's mail address : ") subject = input("Enter email subject : ") message_body = input("Enter the message you want to send : ") # Build a standards-compliant email message msg = MIMEText(message_body) msg['From'] = sender_mail msg['To'] = receiver_mail msg['Subject'] = subject try: server = smtplib.SMTP("smtp.gmail.com", port) server.starttls() # Enable TLS encryption for security server.login(sender_mail, sender_password) # Send the formatted MIME message instead of raw text server.send_message(msg) print("Email sent successfully") except Exception as e: # Print exact error details to diagnose the problem print(f"Email not sent. Error details: {str(e)}") finally: # Ensure we close the server connection even if an error occurs if 'server' in locals(): server.quit()
Key Fixes Explained
- Used
email.mime.text.MIMETextto create a properly structured email with all required headers. - Added specific exception handling to print error details—critical for debugging why the send failed.
- Used a
finallyblock to safely close the SMTP connection, avoiding resource leaks. - Added a subject input to make the email fully functional and compliant with mail server requirements.
内容的提问来源于stack exchange,提问作者Mayank Goel

