首页 > 解决方案 > raise SMTPServerDisconnected("连接意外关闭")

问题描述

带有 smtlib 连接的新问题

例子

当我尝试使用带有 gmail 或私人 gmail 域的 python 发送电子邮件时,阻止/关闭/断开所有 smtp

编码

import pandas as pd
import smtplib

e = pd.read_excel("xxx")
emails = e['xxx'].values
server = smtplib.SMTP("smtp.gmail.com", 587)
server.login = "xxx"
server.password = "xxx"
server.starttls()
msg = "Hello this is a email form python"
subject = "Hello world"
body = "Subject: {}\n\n{}".format(subject, msg)

for email in emails:
    server.sendmail(server.login, server.password, body)
server.quit()

错误

  File "C:\Python39\lib\smtplib.py", line 637, in auth
    (code, resp) = self.docmd("AUTH", mechanism + " " + response)
  File "C:\Python39\lib\smtplib.py", line 427, in docmd
    return self.getreply()
  File "C:\Python39\lib\smtplib.py", line 400, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

标签: pythonpython-3.x

解决方案


为了通过 发送邮件smtp.gmail.com,您需要验证您的 SMTP 会话。您通常会通过调用对象login上的方法来执行此操作smtplib.SMTP...但是您已将此方法替换为字符串,因此即使您尝试过也无法执行此操作。

因为您没有进行身份验证,Gmail 会断开您的连接。

此外,您似乎正在使用您的用户名和密码,该sendmail方法需要“发件人”和“收件人”电子邮件地址。

您可能希望您的代码看起来更像这样:

import pandas as pd
import smtplib

e = pd.read_excel("xxx")
emails = e['xxx'].values

server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login("your_gmail_account_here", "your_password_here")

msg = "Hello this is a email from python"
subject = "Hello world"
body = "Subject: {}\n\n{}".format(subject, msg)

for email in emails:
    server.sendmail("you@your_email_address", email, body)
server.quit()

这假设这emails实际上是一个电子邮件地址列表。您需要在此处填写信息(您的用户名、密码和电子邮件地址)才能正常工作。


推荐阅读