10

python 3中的以下代码在我的计算机上引发错误,我不知道如何正确登录:

import smtplib
connection = smtplib.SMTP('smtp-mail.outlook.com', 587)
connection.ehlo()
connection.starttls()
connection.ehlo()
connection.login('_these_dont_matter@outlook.com', '_the_error_persists_')

最后一行产生以下输出:

Traceback (most recent call last):
  File "/usr/lib/python3.3/smtplib.py", line 366, in getreply
    line = self.file.readline()
  File "/usr/lib/python3.3/socket.py", line 297, in readinto
    return self._sock.recv_into(b)
  File "/usr/lib/python3.3/ssl.py", line 460, in recv_into
    return self.read(nbytes, buffer)
  File "/usr/lib/python3.3/ssl.py", line 334, in read
    v = self._sslobj.read(len, buffer)
ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1504)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.3/smtplib.py", line 621, in login
    AUTH_PLAIN + " " + encode_plain(user, password))
  File "/usr/lib/python3.3/smtplib.py", line 398, in docmd
    return self.getreply()
  File "/usr/lib/python3.3/smtplib.py", line 370, in getreply
    + str(e))
smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1504)

我使用的 SMTP 信息(端口等)来自微软帮助站点,我尝试过的 Outlook 的其他端口或域会导致相同的错误。

的输出openssl version1.0.1e 11 Feb 2013

4

2 回答 2

10

@user2884042 的答案几乎是正确的。

根据https://docs.python.org/3/library/ssl.html

在 3.5 版更改:默认 ssl_version 从 PROTOCOL_SSLv3 更改为 PROTOCOL_TLS 以最大程度地兼容现代服务器。

因此,您需要将 'PROTOCOL_SSLv3' 替换为 'PROTOCOL_TLS',从而使代码类似于:


    import smtplib
    import ssl
    context = ssl.SSLContext(ssl.PROTOCOL_TLS)
    connection = smtplib.SMTP('smtp-mail.outlook.com', 587)
    connection.ehlo()
    connection.starttls(context=context)
    connection.ehlo()
    connection.login('now_your_real_login_data@outlook.com', 'otherwise_SMTPServerDisconnect')

有时您甚至不需要登录。而不是以下行,

$ connection.login('now_your_real_login_data@outlook.com', 'otherwise_SMTPServerDisconnect')

您可以使用您的凭据直接发送电子邮件。

$ sender_email = "senderemail@example.com"
$ receiver_email = "receiveremail@example.com"
$ msg = "Hello from python!"
$ connection.sendmail(sender_email, receiver_email, msg)
于 2019-08-29T12:12:08.057 回答
9

要回答我自己的问题:从 python 3.3 开始,您不必像在这个答案中那样破解 smtplib ,而是可以SSLContext在使用时传递一个对象starttls

但是,请注意:如果登录数据错误,它仍然会引发错误。如果登录数据正确,则使用以下代码一切正常:

import smtplib
import ssl
context = ssl.SSLContext(ssl.PROTOCOL_SSLv3)
connection = smtplib.SMTP('smtp-mail.outlook.com', 587)
connection.ehlo()
connection.starttls(context=context)
connection.ehlo()
connection.login('now_your_real_login_data@outlook.com', 'otherwise_SMTPServerDisconnect')
于 2013-10-16T10:58:03.897 回答