I am working on writing a python test using unittest and selenium webdriver to test if our server is down, and to send an email to notify me if it is not. I am currently working on implementing just the email functionality. This is my current code. When run, the program seems to run, but never ends, and never sends the email. (i.e. in the command line the program seems as though it is running as it doesn't give any errors and you have to escape the "running" program before you can enter another command). My current code is:
#tests for if server is up and notifies if it is not
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
import time
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.action_chains import ActionChains
from urllib.request import urlopen
from html.parser import HTMLParser
import smtplib
class PythonOrgSearch(unittest.TestCase):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.login("email@gmail.com", "password")
msg = "Testing if server is down"
server.sendmail("email@gmail.com", "email@gmail.com", msg)
if __name__ == "__main__":
unittest.main()
I am unsure why this does not work, and would appreciate any insight. Thank you!
When changing the code as suggested, I got the following error:
Traceback (most recent call last):
File "testServerIsUp.py", line 14, in <module>
class PythonOrgSearch(unittest.TestCase):
File "testServerIsUp.py", line 18, in PythonOrgSearch
server.starttls() #and this method to begin encryption of messages
File "C:\Users\663255\AppData\Local\Programs\Python\Python36\lib\smtplib.py", line 751, in starttls
"STARTTLS extension not supported by server.")
smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server.
You need to start a conversation with the mail server and enable encryption:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls() #and this method to begin encryption of messages
server.login("email@gmail.com", "password")
msg = "Testing if server is down"
server.sendmail("email@gmail.com", "email@gmail.com", msg)
Since the smtplib.SMTP()
call was not successful, you can try SMTP_SSL
on port 465:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login("email@gmail.com", "password")
msg = "Testing if server is down"
server.sendmail("email@gmail.com", "email@gmail.com", msg)