smtplib.SMTPServerDisconnected: Connection unexpectedly closed

  The error SMTPServerDisconnected: Connection unexpectedly closed generally indicates that the SMTP server dropped the connection. This could be due to several reasons:

  1. Incorrect SMTP server or port: Make sure that the SMTP server and port are correct. Different email providers use different SMTP servers and ports.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值