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)
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())
Yes, you can check if the connection is open. To do this, issue a NOOP command and test for status == 250. If not, then open the connection before sending out your mail.
def test_conn_open(conn):
try:
status = conn.noop()[0]
except: # smtplib.SMTPServerDisconnected
status = -1
return True if status == 250 else False
def send_email(conn, from_email, to_email, msg):
if not test_conn_open(conn):
conn = create_conn()
conn.sendmail(from_email, to_email, msg.as_string())
return conn # as you want are trying to reuse it.
Note that you are doing this as opening a connection, say with gmail, consumes time, like 2-3 secs. Subsequently, to optimize on sending multiple emails that you may have at hand, then you should also follow Pedro's response (last part).