Python: smtplib.SMTPServerDisconnected: Connection unexpectedly closed
The server closed the connection before your script finished the SMTP conversation — a timeout, blocked IP, TLS mismatch or rate limit.
smtplib.SMTPServerDisconnected: Connection unexpectedly closedSMTPServerDisconnected Connection unexpectedly closedSMTPServerDisconnected: please run connect() firstConnection unexpectedly closed: timed out Meaning
The error is raised at whichever call was in progress (connect, ehlo, starttls, login, sendmail). Run with set_debuglevel(1) to see the last server line. Servers hang up on wrong TLS mode, idle timeouts, too many messages per connection, abuse filters or blocked IPs.
Common causes
- Wrong TLS mode for the port (SMTP vs SMTP_SSL)
- Idle timeout on a long-lived connection
- Server rate limits or blocks the IP
- Message too large
- Firewall/antivirus closing the connection
⚡ Quick fix
- Enable
server.set_debuglevel(1)and read the final reply - Match SMTP/SMTP_SSL with the port
- Reconnect for each batch and add timeouts
Detailed fix by platform
Python
with smtplib.SMTP(host, 587, timeout=30) as s: s.set_debuglevel(1); s.ehlo(); s.starttls(); s.ehlo(); s.login(u, p); s.send_message(msg)
How to diagnose
- Step — Which call raised?
- Debug — Last server line?
- Port — Mode matches?
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
- 421 4.7.0 Try again later (rate limited) SMTP: 421 4.7.0 Our system has detected an unusual rate of unsolicited mail originating from your IP address. Mail sent from your IP address has been temporarily rate limited
- 450 4.7.1 Greylisted, please try again later SMTP: 450 4.7.1 <user@example.com>: Recipient address rejected: Greylisted, see http://postgrey.schweikert.ch/help/example.com.html
- 451 4.3.0 Local error in processing SMTP: 451 4.3.0 Error: queue file write error / 451 Requested action aborted: local error in processing
Most viewed in Email / SMTP
Other ways to find it
Where this error sits
Origin: Network. Errors that are often confused with or caused by this one (click to open):
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 4 Nov 2026