# Python: smtplib.SMTPServerDisconnected: Connection unexpectedly closed

**Code:** `SMTPServerDisconnected: Connection unexpectedly closed` · **Category:** Email / SMTP · **Seen on:** SMTP, Python

The server closed the connection before your script finished the SMTP conversation — a timeout, blocked IP, TLS mismatch or rate limit.

## 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

1. Enable `server.set_debuglevel(1)` and read the final reply
2. Match SMTP/SMTP_SSL with the port
3. Reconnect for each batch and add timeouts

## Detailed fix by platform

### Python

1. `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

1. **Step** — Which call raised?
2. **Debug** — Last server line?
3. **Port** — Mode matches?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/email/python-smtpserverdisconnected)
