1。 smtplib.SMTP_SSL
在 Python 3 文档中 smtplib.SMTP_SSL
它说:
class smtplib.SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, certfile=None, [timeout, ]context=None, source_address=None)
(...) context, also optional, can contain a
SSLContext
and allows configuring various aspects of the secure connection. Please read Security considerations for best practices.
2。安全注意事项文章
所以请阅读上面提到的Security considerations它说:
(...) it is highly recommended that you use the
create_default_context()
function to create your SSL context.
和
(...) if you create the SSL context by calling the
SSLContext
constructor yourself, it will not have certificate validation nor hostname checking enabled by default.
看来我确实想要前者:create_default_context
用于 SSL 上下文。
3。 smtplib.py
我快速浏览了 smtplib.py
如果我省略 smtplib.SMTP_SSL
的 context
参数,看看会发生什么:
if context is None: context = ssl._create_stdlib_context(certfile=certfile, keyfile=keyfile)
因此,有一个对 ssl._create_stdlib_context
的调用,这似乎与安全注意事项文章中推荐的 ssl.create_default_context
不同。
4。 ssl.py
在 ssl.py
中的函数文档字符串处我发现:
All Python stdlib modules shall use this function to create SSLContext objects in order to keep common settings in one place. The configuration is less restrict than create_default_context()'s to increase backward compatibility.
5。问题
根据安全注意事项文章,我应该如何调用 smtplib.SMTP_SSL
?看来我真的需要每次“手动”调用create_default_context
来创建上下文?
server = smtplib.SMTP_SSL(context=ssl.create_default_context())
或者是
server = smtplib.SMTP_SSL()
够了吗?为什么?
非常感谢:-)
最佳答案
最佳实践是使用server = smtplib.SMTP_SSL(context=ssl.create_default_context())
。
根据文档字符串,由于向后兼容性,_create_stdlib_context
比 create_default_context
受到的限制更少。
引用:https://github.com/python/cpython/blob/master/Lib/ssl.py#L581
关于Python 文档文章 "Security considerations"有关 `smtplib` 的 SSL 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53566679/