Skip to content

Instantly share code, notes, and snippets.

@basilhayek
Last active May 30, 2023 04:16
Show Gist options
  • Select an option

  • Save basilhayek/f2589cf27dc2ad0b1a7f65df12cfb034 to your computer and use it in GitHub Desktop.

Select an option

Save basilhayek/f2589cf27dc2ad0b1a7f65df12cfb034 to your computer and use it in GitHub Desktop.
A simple python script to check URLs and send email alerts if there are any exceptions. Originally created as a keepalive to ping web apps on PythonAnywhere to keep them from sleeping. Thanks to ogrigas for the inspiration.
import requests
urls = [
"http://www.google.com",
"http://www.yahoo.com",
]
def send_mail(sender, recipient, subject, message, password, smtpserver):
from smtplib import SMTP
from email.mime.text import MIMEText
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipient
server = SMTP(smtpserver)
server.ehlo()
server.starttls()
server.login(sender, password)
server.sendmail(sender, [recipient], msg.as_string())
server.quit()
def send_alert(url, e, errtype):
subject = "{} for {}".format(errtype, url)
message = str(e)
send_mail('[email protected]', '[email protected]', subject, message,
'accountpassword', 'smtp.gmail.com:587')
# The above assumes you are using gmail; it is recommended to get an app-
# specific password at https://myaccount.google.com/u/0/apppasswords
for url in urls:
try:
r = requests.get(url)
r.raise_for_status()
# Want to ensure that any HTTP error gets handled as an exception
except requests.exceptions.HTTPError as e:
send_alert(url, e, 'HTTPError')
# Catch the base class exception to broadly handle all exceptions
except requests.exceptions.RequestException as e:
send_alert(url, e, 'Exception')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment