Search code examples
pythonsmtplib

Python smtplib second connection failing


I am trying to connect to my mail server, then disconnect, then reconnect at another time. The initial connection works and the email is sent. I disconnect using quit() and the reply is closing the connection. When I attempt to connect again, it raises SMTPServerDisconnected please run connect() first. I found this from a few years ago as the exact same problem (https://bugs.python.org/issue22216) and it shows that it was fixed. I am having this same issue now and unsure how to properly fix it or close the connection.

mail = smtplib.SMTP_SSL('mail.hostname.com', 465)
MAIL_PASS = 'password'
SENDER = '[email protected]'
RECEIVER = '[email protected]'

while True:  
  if (something)
    mail.login(SENDER, MAIL_PASS)
    mail.sendmail(SENDER, RECEIVER, 'test email')
    mail.quit()
  elif (something else)
    mail.login(SENDER, MAIL_PASS)
    mail.sendmail(SENDER, RECEIVER, 'test2 email')
    mail.quit()

After the first email and the quit request it says this:

reply: b'221 box5454.bluehost.com closing connection\r\n'
reply: retcode (221); Msg: b'box5454.bluehost.com closing connection'

The next connection attempt says this:

send: 'ehlo [127.0.1.1]\r\n'
Traceback (most recent call last):
mail.login(SENDER, MAIL_PASS)
self.ehlo_or_helo_if_needed()
if not (200 <= self.ehlo()[0] <= 299):
self.putcmd(self.ehlo_msg, name or self.local_hostname)
self.send(str)
raise SMTPServerDisconnected('please run connect() first')
smtplib.SMTPServerDisconnected: please run connect() first

Solution

  • I have found a way to make the program work. I am using a while True to continue the program. It seems when I declare the variable for the smtplib before while True, it has the problem. I declare the variable after while True and it works. May be a noob problem using while True, but it drove me nuts and hopefully it will help someone else

    MAIL_PASS = 'password'
    SENDER = '[email protected]'
    RECEIVER = '[email protected]'
    
    while True:
      mail = smtplib.SMTP_SSL('mail.hostname.com', 465)
    
      if (something)
        mail.login(SENDER, MAIL_PASS)
        mail.sendmail(SENDER, RECEIVER, 'test email')
        mail.quit()
      elif (something else)
        mail.login(SENDER, MAIL_PASS)
        mail.sendmail(SENDER, RECEIVER, 'test2 email')
        mail.quit()