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