Python调用smtplib.SMTP连接Gmail服务器时程序冻结问题求助
Hey there! It’s super frustrating when your script freezes mid-execution, especially before even getting to the authentication step. Let’s break down the possible causes and practical fixes for this issue.
First, Try This Modified Script
Adding a timeout to your SMTP connection and basic error handling will help you diagnose the problem immediately instead of waiting indefinitely:
import smtplib from socket import timeout fromaddr = 'XXX@gmail.com' toaddrs = 'YYY@gmail.com' msg = 'Enter your message here' username = 'XXX@gmail.com' password = 'PPP' try: # Add a 10-second timeout to prevent infinite freezing server = smtplib.SMTP('smtp.gmail.com', 587, timeout=10) print("Connected to SMTP server successfully!") server.starttls() server.login(username, password) server.sendmail(fromaddr, toaddrs, msg) print("Email sent!") server.quit() except timeout: print("Connection timed out! Check your network or SMTP settings.") except Exception as e: print(f"An error occurred: {str(e)}")
Common Causes & Fixes
1. Network Restrictions (Firewall/Proxy/ISP Block)
The most likely culprit is a network issue blocking outgoing connections to port 587:
- Check your local firewall: Ensure Windows Defender Firewall, macOS Firewall, or any third-party firewall isn’t blocking Python from accessing the internet.
- Proxy configuration: If you’re behind a corporate or school proxy, you’ll need to configure smtplib to use it. You can add a proxy handler before creating the SMTP connection.
- ISP port blocking: Some ISPs block port 587 for anti-spam reasons. Try switching to port 465 (SMTP_SSL) instead—note you won’t need
server.starttls()when using this method:server = smtplib.SMTP_SSL('smtp.gmail.com', 465, timeout=10)
2. Missing Timeout in Older smtplib (Pre-Python 3.7)
Python 3.6’s smtplib.SMTP doesn’t set a default timeout. If the connection can’t be established, it’ll hang forever. Adding the timeout parameter (like in the modified script) forces it to fail fast, giving you a clear error message instead of freezing.
3. Gmail Server Access Restrictions
Even before the login step, Gmail’s servers might throttle or block connections from unfamiliar IPs:
- If you have 2FA enabled on your Gmail account, use an App Password instead of your regular password (this is more secure than enabling "Less secure app access").
- Check your Gmail account’s Security Log to see if the connection attempt was flagged as suspicious.
Final Notes
Always include error handling in your scripts to catch issues early, and consider upgrading to a newer Python version (3.7+)—they have better default timeouts and improved smtplib functionality.
内容的提问来源于stack exchange,提问作者OD1995

