0

I have a script which performs selenium checks and then sends an email with screenshot using ms outlook. Script was working fine. The problem is, sometimes even though the test is successful(try block), it sends out an failure email(except block) and it is intermittent.

Sometimes I get smtplib.SMTPServerDisconnected: Server not connected or smtplib.SMTPServerDisconnected: Connection unexpectedly closed

I've added the below code to open a connection again in case if it is closed, but no luck.

        try:
            conn = server.noop()[0]
            print("---CONNECTION CODE---", conn)
            if conn != 250:
                server = smtplib.SMTP('mail.xxx.com', 587)

        except:
            pass

My Script:

class MyTesting:

def AutomationTesting(self):

    path = 'C:\\xxxx'

    try:
        ## Selemium test code

        msg['From'] = sender
        msg['To'] = ", ".join(receiver)
        msg['Subject'] = 'Automation Testing Success'

        body = 'Hello, \n\nAttached is the screenshot for the reference. \n \nRegards'
        msg.attach(MIMEText(body, 'plain'))
        attachment = open('C:\\{}'.format(filename), 'rb')

        part = MIMEBase('application', 'octet-stream')
        part.set_payload((attachment).read())
        # part.set_payload((attachment).read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', "attachment; filename= " + filename)

        msg.attach(part)

        server = smtplib.SMTP('mail.xxx.com', 587)

        conn = server.noop()[0]

        try:
            conn = server.noop()[0]
            print("---CONNECTION CODE---", conn)
            if conn != 250:
                server = smtplib.SMTP('mail.xxx.com', 587)

        except:
            pass

        server.starttls()
        server.login(sender, "Heavensdoor11")
        text = msg.as_string()
        server.sendmail(sender, receiver, text)
        # server.quit()
        time.sleep(4)
        print("Email sent.")
    except:
        print("Unable to test site.")

        file_write = open(log_file, "a+")
        file_write.write("automation failure {}\n".format(timestamp))
        file_write.close()

        filename_2 = 'Fidelity-Failure' + timestamp + '.png'
        driver.get_screenshot_as_file("C:\\{}".format(filename_2))
        sender = 'sender '
        # receiver = receiver '

        msg = MIMEMultipart()
        print("Sending an email to {} ...".format(receiver))

        msg['From'] = sender
        msg['To'] = ", ".join(receiver)
        msg['Subject'] = 'Automation Testing Failure'

        body = 'Hi Team, \n\nAutomation testing for customer has been failed.'
        msg.attach(MIMEText(body, 'plain'))
        attachment = open('C:\\{}'.format(filename_2), 'rb')

        part = MIMEBase('application', 'octet-stream')
        part.set_payload((attachment).read())
        # part.set_payload((attachment).read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', "attachment; filename= " + filename_2)

        msg.attach(part)

        server = smtplib.SMTP('mail.xxx.com', 587)

        server.starttls()
        server.login(sender, "mypassword")
        text = msg.as_string()
        server.sendmail(sender, receiver, text)
        # server.quit()
        time.sleep(4)
        print("Email sent.")


    finally:
        driver.close()

Any help is really appreciated.

stovfl
  • 14,998
  • 7
  • 24
  • 51
PRK
  • 411
  • 3
  • 6
  • 19
  • 1
    Having all the code inside one big "try" and not examining the exception properly is making this harder than it needs to be. To troubleshoot this, consider catching specific exceptions and dealing with them appropriately using the 'except (ExpectedException, OtherException) as e:' syntax. You may find something is throwing an exception that you weren't expecting! Or just remove the try/except completely for testing, to quickly isolate the problem statement(s). – Rob Bricheno Oct 11 '18 at 10:14
  • @rbricheno, Thank you for your input. I added the exception `(smtplib.SMTPServerDisconnected, smtplib.SMTPException)as e` but, still it gives me ` raise SMTPServerDisconnected("Connection unexpectedly closed")`. Any idea? – PRK Oct 11 '18 at 10:55
  • I wonder if you are hitting a rate limit or some othe restriction on your server? You can try `server.setdebuglevel(1)` after you have instantiated it to see the conversation between your client and the server as deescribed here https://stackoverflow.com/questions/17759860/python-2-smtpserverdisconnected-connection-unexpectedly-closed to see if that is the problem. – Rob Bricheno Oct 11 '18 at 14:17

0 Answers0