Solution for Python smtplib.SMTPServerDisconnected error
Posted Under (Python) by Ramraj Edagutti on Jul Wed, 2009
Since from two months I have been working on developing python application to automate the web importer task for our web application, and after completing import job an email needs to be sent to support team with the importer status.
So, while sending email using python smtplib library, I was getting smtplib.SMTPServerDisconnected error. It was working absolutely well before, I was wondering why the SMTPServerDisconnected error was coming now…
Error log
-
File "ImporterAutomation.py", line 470, in <module>
-
sys.exit(main())
-
File "ImporterAutomation.py", line 462, in main
-
sendmail.sendEmail()
-
File "C:projects…sendmail.py", line 83, in sendEmail
-
emailNotify(TEXT,Flag)
-
File "C:projects….sendmail.py", line 101, in emailNotify
-
server.sendmail(author, recipient_list, msg.as_string())
-
File "C:Python26libsmtplib.py", line 685, in sendmail
-
self.ehlo_or_helo_if_needed()
-
File "C:Python26libsmtplib.py", line 509, in ehlo_or_helo_if_needed
-
if not (200 <= self.ehlo()[0] <= 299):
-
File "C:Python26libsmtplib.py", line 382, in ehlo
-
self.putcmd(self.ehlo_msg, name or self.local_hostname)
-
File "C:Python26libsmtplib.py", line 318, in putcmd
-
self.send(str)
-
File "C:Python26libsmtplib.py", line 310, in send
-
raise SMTPServerDisconnected('please run connect() first')
-
smtplib.SMTPServerDisconnected: please run connect() first
-
-
Then after some time I figured out it was problem with configuring SMTP host ip address. There was no smtp host configured in configuration file.
-
<blockquote>
-
-
smtp = smtplib.SMTP(smtp_host) — here smtp_host was null</blockquote>
Above smtp instance variable is created without SMTP connection, so when I was calling smtp.sendmail() method python smtp lib was throwing that error.
To fix it, I provided correct SMTP host/ip address, and also added error handling code to gracefully handle that error condition and log error message in log file.
Below is the fix
-
smtp = smtplib.SMTP(smtp_host)
-
if smtp_username and smtp_password:
-
smtp .login(smtp_username, smtp_password)
-
-
smtp .sendmail(author, recipient_list, msg.as_string())
-
except smtplib.SMTPException, e:
-
err_log.error('Error while seding email summary….')
-
err_log.error(e)
-
except socket.error, e:
-
err_log.error('Unable to connect to SMTP server….')
-
err_log.error(e)
-
else:
-
smtp .quit()
I know this very basic part of python smtp module, hope this may help python freshers. Any comments or feedback are welcome.
