python - 通过python发送电子邮件时出现SMTPServerDisconnected错误
问题描述
尝试使用主机发送电子邮件时: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
解决方案
Considering the port number you are using I'd try with SMTP_SSL
instead of SMTP
and starttls()
.
https://docs.python.org/3/library/smtplib.html:
An SMTP_SSL instance behaves exactly the same as instances of SMTP. SMTP_SSL should be used for situations where SSL is required from the beginning of the connection and using starttls() is not appropriate. If host is not specified, the local host is used. If port is zero, the standard SMTP-over-SSL port (465) is used.
STARTTLS
is a form of opportunistic TLS, it is supposed to be used with old protocols, that originally did't support TLS, to upgrade the connection.
The port 465 was used before the introduction of STARTTLS
for SMTPS
, which is now deprecated.
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()
Alternatively you should be able to use port 25 with your original code.
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()
In both examples you can completely omit the port number as you are using the default ports.
推荐阅读
- css - 移动前端有个bug:容器不固定
- python - IndexError:索引 12 超出轴 1 的范围,大小为 12 GradientBoostingClassifier
- scala - 猫效应:如何将 Map[x,IO[y]] 转换为 IO[Map[x,y]]
- java - Android 从 Firebase 隐藏通知
- mysql - 设置语句中的 MySQL 脚本
- apache-kafka - 如何仅在窗口完成时输出窗口聚合的结果?
- jquery - JQuery如何在每次显示时为里程碑计数器设置动画
- r - R : 用十进制逗号读取 csv 数字,包 sparklyr
- scrapy - 为什么scrapy不使用随机代理下载器中间件?
- javascript - 在使用 jquery 加载时同时动态设置不同 HTML 页面的按钮文本