我尝试使用 SMTP 发送电子邮件并遇到“连接意外关闭”异常。我已经检查了所有参数,包括 SMTP 服务器地址和端口。我使用的是从我的 Google 帐户设置生成的密码,并且已确保“使用两步验证登录”已开启。尽管进行了这些检查,我仍然面临这个问题。我将不胜感激任何有关解决此问题的帮助或见解。
`from email.message import EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import time
import ssl
import smtplib
# Email configuration
sender_email = my_email
app_password = my_password #generated from my Google Account settings
receiver_email = some_email
subject = 'Test Email'
body = 'This is a test email sent using smtplib in Python.'
# Create message
em = EmailMessage()
em['From'] = sender_email
em['To'] = receiver_email
em['Subject'] = subject
em.set_content(body)
# Gmail SMTP server configuration
smtp_server = 'smtp.gmail.com'
smtp_port = 465
max_retries = 3
retry_delay_seconds = 5
for attempt in range(1, max_retries + 1):
try:
# Connect to the SMTP server
with smtplib.SMTP(smtp_server, smtp_port) as smtp:
# Log in
smtp.login(sender_email, app_password)
# Send mail
smtp.sendmail(sender_email, receiver_email, em.as_string())
print("Email sent successfully!")
break # Exit the loop if successful
except smtplib.SMTPServerDisconnected as e:
print(f"Attempt {attempt}: SMTPServerDisconnected - {e}")
if attempt < max_retries:
print(f"Retrying in {retry_delay_seconds} seconds...")
time.sleep(retry_delay_seconds)
else:
print("Maximum retries reached. Exiting.")
raise
except Exception as e:
print(f"Unexpected error: {e}")
raise`
让我们一步步解决这个问题。
1 SMTP 类别和端口的正确使用:
您的代码使用
smtplib.SMTP
连接到 Gmail 的 SMTP 服务器。但是,对于使用 SSL 的安全连接(这是 Gmail 所要求的),您应该使用 smtplib.SMTP_SSL
。
SSL 连接端口已正确设置为 465。只需确保您使用 SMTP_SSL 来匹配此端口即可。
2 SMTP_SSL 代码修订:
以下是修改代码的方法:
import smtplib
from email.message import EmailMessage
# Email configuration
sender_email = 'my_email'
app_password = 'my_password' # App password generated from Google Account settings
receiver_email = 'some_email'
# Create the email message
em = EmailMessage()
em['From'] = sender_email
em['To'] = receiver_email
em['Subject'] = 'Test Email'
em.set_content('This is a test email sent using smtplib in Python.')
# Gmail SMTP server configuration for SSL
smtp_server = 'smtp.gmail.com'
smtp_port = 465 # Port for SSL
try:
with smtplib.SMTP_SSL(smtp_server, smtp_port) as smtp:
smtp.login(sender_email, app_password)
smtp.send_message(em)
print("Email sent successfully!")
except Exception as e:
print(f"An error occurred: {e}")