The error SMTPServerDisconnected: Connection unexpectedly closed generally indicates that the SMTP server dropped the connection. This could be due to several reasons:
- Incorrect SMTP server or port: Make sure that the SMTP server and port are correct. Different email providers use different SMTP servers and ports.
- TLS/SSL requirement: Some servers require the connection to be secured with SSL or TLS. If your server requires a secure connection, you should use smtplib.SMTP_SSL() instead of smtplib.SMTP() to create the SMTP object. Alternatively, you may need to call smtp.starttls() before logging in.
- Server downtime or network issues: There could be a temporary issue with the server, or there could be network connectivity problems between your system and the server.
- Login before sending: Some SMTP servers require you to login before sending mail. Make sure you’re logged in with smtp.login(user, password) before attempting to send.
- Incorrect login credentials: Make sure that your username and password are correct. If you have two-factor authentication enabled for your email account, you may need to generate and use an app-specific password.
- SMTP server doesn’t support the command: It’s possible that the server doesn’t support a command that was sent by smtplib, which can cause the server to drop the connection.
Here’s an example that handles SMTPServerDisconnected exception:
import smtplib
from email.mime.text import MIMEText
mail_host = "smtp.example.com"
port_ = 465
account = "youraccount@example.com"
password = "password"
receivers = ["receiver@example.com"]
message = MIMEText('This is the body of the email.')
message['Subject'] = 'Subject of the Email'
message['From'] = account
message['To'] = ", ".join(receivers)
try:
smtp_ = smtplib.SMTP_SSL(mail_host, port=port_)
smtp_.login(user=account, password=password)
smtp_.sendmail(account, receivers, message.as_string())
except smtplib.SMTPServerDisconnected as e:
print(f"Server unexpectedly disconnected: {e}")
except smtplib.SMTPException as e:
print(f"An SMTP error occurred: {e}")
finally:
smtp_.quit()
In this script, the SMTPServerDisconnected exception is caught separately from other SMTPException errors, which allows for more specific error handling.