Reputation: 17332
This is my code using a SSL context:
with smtplib.SMTP(host, port) as smtpserver:
smtpserver.ehlo()
smtpserver.starttls(context=ssl.create_default_context())
... etc ...
Is the default context object a constant that can be shared and reused in a multi-threaded program? I mean creating it just once:
SSL_CONTEXT = ssl.create_default_context()
and then:
with smtplib.SMTP(host, port) as smtpserver:
smtpserver.ehlo()
smtpserver.starttls(context=SSL_CONTEXT)
for every message sent.
Upvotes: 3
Views: 11803
Reputation: 19
Each connection should have its own context. You can see in the Python source code for http.client, that HTTPSConnection creates the new context for every connection.
https://github.com/python/cpython/blob/master/Lib/http/client.py
Upvotes: 1
Reputation: 47264
Indeed ssl.create_default_context()
can be used again (as it's purpose) after initializing it:
import ssl, smtplib
>>> smtp = smtplib.SMTP("mail.python.org", port=587)
>>> context = ssl.create_default_context()
>>> smtp.starttls(context=context)
(220, b'2.0.0 Ready to start TLS')
↳ https://docs.python.org/3/library/ssl.html#best-defaults
Upvotes: 1