0

尝试使用主机发送电子邮件时: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
4

1 回答 1

0

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.

于 2018-07-13T15:17:10.050 回答