#! /Library/Frameworks/Python.framework/Versions/3.6/bin/python3 import smtplib from email.message import EmailMessage as Em #https://stackoverflow.com/questions/16683732/python-smtplib-security import requests from bs4 import BeautifulSoup as bs def emailer(usr, pwd, mailserv, port, msg): server = smtplib.SMTP(mailserv, port) server.ehlo() server.starttls() server.ehlo() server.login(usr,pwd) server.sendmail(msg['From'], msg['To'], msg.as_string()) server.close() def tester(url): try: s=requests.Session() checker=s.get(url) if not checker.ok: returncode = checker.status_code #returns integer of server status code https://www.w3.org/Protocols/HTTP/HTRESP.html print(returncode) soup = bs(page.text, 'html.parser') if returncode != 200 and str(returncode).startswith('2'): content = '{} returned status which is not code 200 (OK): {}'.format(URL, returncode) elif str(returncode).startswith('3'): content = '{} returned a redirect status: {}/'.format(URL, returncode) elif str(returncode).startswith('4'): content = '{} returned a not found status: {}.'.format(URL, returncode) elif str(returncode).startswith('5'): content = '{} returned an internal error: {}.'.format(URL, returncode) elif str(soup.title) != titletest: content = '{} title string has changed. Possible hacking attempt.'.format(URL) else: content = 'OK' return content except: content = 'Server {} appears to be down.'.format(URL) return content if __name__ == '__main__': USER = 'user@example.invalid' PASS = 'passwordabc123notreally' MAILSERVER = 'smtp.example.invalid' PORT = 587 URL='https://example.invalid' message = Em() message['Subject'] = '{} status warning'.format(URL) message['From'] = user message['To'] = 'recipient1@example.invalid, recipient2@example.invalid' titletest='Website Title' try: content=tester(URL) except: content = 'Server {} appears to be down.'.format(URL) #pass message.set_content(content) if content !='OK': emailer(USER, PASS, MAILSERVER, PORT, message)