【问题标题】:Getting SMTPServerDisconnected error sending email through python通过python发送电子邮件时出现SMTPServerDisconnected错误
【发布时间】:2018-07-13 15:08:59
【问题描述】:

尝试与主机发送电子邮件时:cpanel.freehosting.com P 它引发了类似的错误

这是我的代码:

import smtplib
s = smtplib.SMTP('cpanel.freehosting.com', 465)
s.starttls()
s.login("myusername", "mypassword")
message = "Message_you_need_to_send"
s.sendmail("myemailid", "receiver_email_id", message)
s.quit()

这是我得到的错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python3.5/smtplib.py", line 337, in connect
(code, msg) = self.getreply()
File "/usr/lib/python3.5/smtplib.py", line 393, in getreply
  raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

【问题讨论】:

  • 您最好向服务提供商咨询,即“您的 SMTP 服务器是否需要 TLS?465 端口是正确的端口吗?”等等我也怀疑这是正确的服务器网址
  • 要使邮件服务器正常工作需要做很多工作。 MX 记录、反向 DNS、白名单、路由问题等。例如,您确定 cpanel.freehosting.com 是您的邮件服务器吗?

标签: python smtp starttls smtps


【解决方案1】:

考虑到您使用的端口号,我会尝试使用 SMTP_SSL 而不是 SMTPstarttls()

https://docs.python.org/3/library/smtplib.html:

SMTP_SSL 实例的行为与 SMTP 实例完全相同。 SMTP_SSL 应该用于需要 SSL 的情况 连接的开始和使用 starttls() 是不合适的。 如果未指定主机,则使用本地主机。如果端口为零,则 使用标准 SMTP-over-SSL 端口 (465)。

STARTTLSopportunistic TLS 的一种形式,它应该与原本不支持 TLS 的旧协议一起使用,以升级连接。 在为SMTPS 引入STARTTLS 之前使用端口465,现在已弃用。

import smtplib
s = smtplib.SMTP_SSL('cpanel.freehosting.com', 465)
s.login("myusername", "mypassword")
message = "Message_you_need_to_send"
s.sendmail("myemailid", "receiver_email_id", message)
s.quit()

或者,您应该能够将端口 25 与您的原始代码一起使用。

import smtplib
s = smtplib.SMTP('cpanel.freehosting.com', 25)
s.starttls()
s.login("myusername", "mypassword")
message = "Message_you_need_to_send"
s.sendmail("myemailid", "receiver_email_id", message)
s.quit()

在这两个示例中,您可以完全省略端口号,因为您使用的是默认端口。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 2015-06-09
    • 2019-05-06
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 2018-01-20
    相关资源
    最近更新 更多