I have a small issue with the smtplib in Python. I am currently building an API with Flask and I am going through the authentication stage. The theory is very simple: I have created a route accepting POST requests via json with username, password and an email address. Every time a new user is created the inner logic sends a basic response to the given email with a secret code to activate the account. Everything works wonderfully, however the request takes on average 7.5s and the bulk of that is the actual email delivery.
I am using the smtp library in this way inside a function that gets triggered every time a new user is created:
def func(*args, **kwargs): # the arguments are email address from/to and the actual message
with smtplib.SMTP_SLL('****.mail.com') as smtp:
smtp.login(ADDRESS, PASSWORD)
smtp.sendemail(msg)
My question is: Would it be possible and maybe faster to assign the SMTP_SSL connection to an object, like below, outside the function so that the connection were always open:
server = smtplib.SMTP_SSL('****.mail.com')
server.login(ADDRESS, PASSWORD)
def func(*args, **kwargs): # the function doesn't connect everytime
server.sendemail(msg)
In my estimation the actual connection, verification and login take up the longest. Also, which security problems might emerge keeping the SMTP connection always open when the web server for the website is running?
Thank you very much
A similar question has been adressed in
How to send bulk emails through SMTP without establising a connection for every email?
In general, I think it's ill advised. If you're connecting to your ISP's SMTP-server, they will not appreciate permanently hogging a socket. If it takes that long to do the handshake, it would be a fair guess that they already have some load to sure.
Besides, you will likely be disconnected after a while of inactivity. Exception handling will also get tricky if you do it like you suggested.
Depending on your environment, and as suggested in the above discussion, you can set up Postfix as a null client, with connection caching enabled. This punts handling the hairy bits to a piece of software that is engineered to deal with it.
Your webserver would then use smtplib to connect to this null client and send your email. This transaction will be practically instant, and Postfix would do its thing.