I am using smtplib and I am sending notification emails from my application. However I noticed that sometimes (especially when there is a lot of idle time between mail sending) I get a SMTPServerDisconnected error.
I guess there are 2 solutions for this (know none of them, though)
- Increase idle time between sending mails
- reconnect when connection is down.
I think 2nd solution seems more elegant. But how can I do that?
edit: I am adding the code
from smtplib import SMTP
smtp = SMTP()
smtp.connect('smtp.server.com')
smtp.login('username','password')
def notifyUser():
smtp.sendmail(from_email, to_email, msg.as_string())
If your use case is sending a single message at a time, the solution that seems most correct to me, would be to create a new SMTP session for each message:
If your SMTP server doesn’t required that you authenticate yourself (a common case), this can be further simplified to:
If it is common to have more than one message to send at once, and you want to optimise this case by reusing the same SMTP session for the group of messages (can be simplified as above if you don’t need to login to the SMTP server):