Ошибка при отправке электронной почты с использованием Python - PullRequest
0 голосов
/ 11 октября 2018

У меня есть скрипт, который выполняет проверку селена, а затем отправляет электронное письмо со скриншотом, используя ms outlook.Скрипт работал нормально.Проблема в том, что иногда, даже если тест успешен (попробуйте заблокировать), он отправляет сообщение об ошибке (кроме блока), и он прерывистый.

Иногда я получаю smtplib.SMTPServerDisconnected: Server not connected или smtplib.SMTPServerDisconnected: Connection unexpectedly closed

Я добавил приведенный ниже код, чтобы снова открыть соединение в случае, если оно закрыто, но не повезло.

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

        except:
            pass

Мой сценарий:

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()

Любая помощьочень ценится.

...