dylanh0

E-Mail Notifications From Python Scripts

Blog Post created by dylanh0 on Apr 11, 2019

If you are a GIS Manager, DB Admin, or do GIS for any type of organization, you probably have scripts scheduled to run overnight. We had been writing text file logs, but we have built up so many scheduled scripts that it has become impractical to go through all the logs for all of the scripts each day to ensure they are working properly.

 

Here is a little module I wrote and some sample code that I put in the except block of our scheduled server scripts so that if any fail we will receive an e-mail immediately, and more importantly, know exactly which log to check.

 

################### Custom Module: Saved as EmailService.py ########################
# Saved as EmailService.py

import smtplib

class EmailService(object):

    def __init__(self):
        self.YOUREMAIL = 'your e-mail address which messages will be sent from'

    def configMessage(self, subject, body):
        self.msg = 'Subject: {0}\n{1}'.format(subject, body)
        return self.msg

    def sendEmail(self, recip_email):
        # Do a Google search for smtp settings for your e-mail provider
        self.smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
        self.smtpObj.ehlo()
        self.smtpObj.starttls()
        # We created a special gmail account just for this purpose and hard coded
        # the password here
        self.smtpObj.login(self.YOUREMAIL, 'YOUR PASSWORD')
        self.smtpObj.sendmail(self.YOUREMAIL, recip_email, self.msg)
        self.smtpObj.quit()


################################ Example of Use ####################################
import EmailService as ES

try:
    # Your scheduled script code

except Exception as e:
    log_file.write(e)

    service = ES.EmailService()
    subject = 'SUBJECT'
    body = 'Body of e-mail'
    recip = 'Recipient e-mail address'

service.configMessage(subject, body)
service.sendEmail(recip)

Outcomes