Send Alert EMails

11-18-2016 10:41 AM
Frequent Contributor

Just brainstorming right.  Looking for some sort of solution to Alert (email) individuals when my collected data meets certain criteria.  If some collected feature in a MapService or SDE FC is set to Yes or No, or some other specific value I want to grab that individual record(s) and email it to a few individuals.  

Has anyone done this?  Thanks

0 Kudos
2 Replies
MVP Honored Contributor

It might help to describe where you are stuck, and go from there. Have you started?

For sending email, I'd start here: 18.1.11. email: Examples — Python 2.7.12 documentation 

MVP Regular Contributor

Here's the basic template we use for scheduled task scripts. It includes a lot more than just sending an email but I wanted to show it in context. I have some tweaks planned but this basic structure has served us well for years. We also log the success or failure to a table in SDE so we can report on everything but I left the logging part out.

"""Brief description of script here.

More detailed description of script, dependencies, and purpose.

Followed by a change log.

# Required modules
import arcpy
import datetime
from email.mime.multipart import MIMEMultipart  ## Build email parts
from email.mime.text import MIMEText  ## Record email body type
import os
import smtplib  ## Send email message
from socket import gethostname

def main():
    # Connection variables
    ## SDE Connections
    sde_sdeconn = r"C:\GISConnections\SDE@GTEST.sde"
    gisviewer_sdeconn = r"C:\GISConnections\GISVIEWER@GTEST.sde"
    ## Network drive locations
    mytemp_gdb = r"\\mynas\BlakeT\Work\Temp.gdb"

    # Email variables
    addr_from = ""
    addr_to = ["", ""]
    addr_cc = []
    addr_bcc = []  ## BCC is not used in the MIMEMultipart message but will be sent with SMTP
    recipients = addr_to+addr_cc+addr_bcc
    ## Create email message container and set message parts
    msg_root = MIMEMultipart('alternative')
    msg_root['From'] = addr_from
    msg_root['To'] = ", ".join(addr_to)
    msg_root['Cc'] = ", ".join(addr_cc)
    msg_root['Subject'] = os.path.basename(__file__)

    # Opening lines of email message body
    msg = "{scriptName} (TaskID {tID}) ran on {hostComputer}".format(
        scriptName = os.path.basename(__file__),
        tID = taskID,
        hostComputer = gethostname()
    istring = " Started {} ".format("%Y-%m-%d %H:%M:%S"))
    msg += "\n\n{:~^64}\n\n".format(istring)

        arcpy.env.overwriteOutput = True  ## Optional

        """---------------- Main script processing code here ----------------"""
        # Get workspace factory
        ## This is the style for a secondary or inline comment
        msg += "Get workspace factory"
        msg += "\nStart  {}\n".format("%H:%M:%S"))
        if arcpy.GetMessages(1):  ## Write arcpy warning message
            msg += arcpy.GetMessages(1)
        msg += "Finish {}\n\n".format("%H:%M:%S"))

        # Complete email message with success
        ## Add closing line to email message
        istring = " Finished {} ".format("%Y-%m-%d %H:%M:%S"))
        msg += "{:~^64}\n\n".format(istring)

    except Exception as err:
        # Complete email message with error
        ## (sometimes the error has nothing in the .message property)
        if err.message and err.message in arcpy.GetMessages(2):
            ## All of the messages returned by the last ArcPy tool
            displayErr = "\n{}".format(arcpy.GetMessages())
            ## Non-ArcPy error message
            displayErr = "{}\n({})".format(
      "%Y-%m-%d %H:%M:%S")
        msg += displayErr

        # Cleanup
        arcpy.ClearWorkspaceCache_management()  ## Use if connecting to SDE

        # Close and send the email
        msg_body = MIMEText(msg, 'plain')  ## Record the MIME type of email message body as plain text
        msg_root.attach(msg_body)  ## Attach msg_body content to msg_root container
        s = smtplib.SMTP('COCMAIL01.CI.CHANDLER.AZ.US')
        s.set_debuglevel(1)  ## Print smtp debug info in Python interpreter (optional)
        s.sendmail(addr_from, recipients, msg_root.as_string())

# Script start
if __name__ == '__main__':

In reference to your question about monitoring data for certain criteria, you could schedule this script as a task in Windows for whatever interval you need. The script could check for your conditions and only send the email if the conditions are met.

0 Kudos