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.