Send Email When a Feature is Added to an ArcGIS Online Hosted Feature Service

Document created by jskinner-esristaff Employee on Jun 2, 2017Last modified by jskinner-esristaff Employee on Jun 2, 2017
Version 2Show Document
  • View in full screen mode

With ArcGIS GeoEvent it is very easy to setup a notification when a new feature is added to an ArcGIS Online Hosted Feature Service.  Instructions can be found here.  If you do not have GeoEvent you can still accomplish this using Python.  Below is an example on how to do this. 

 

When editor tracking is enabled, new features are recorded in a field called 'created_date'.  The script queries this field within the service and compares the time to the current time (minus one hour).  If the time is greater than the current time, it will send an e-mail with a specified field's values for the new features.

 

Windows Task Scheduler can be setup to execute this script at a given interval (i.e. every hour).  This will report any new features within that last hour.

 

import urllib2, json, urllib, datetime, time, smtplib
from datetime import timedelta

# Variables
username = 'agol'        # AGOL Username
password = 'gis12345'    # AGOL Password

URL = 'http://services.arcgis.com/dlFJXQQtlabc4qUk/arcgis/rest/services/PropertyDamage/FeatureServer/0/query'       # Feature Service URL
uniqueID = 'OBJECTID'           # i.e. OBJECTID
dateField = 'created_date'      # Date field to query
hoursValue = 1                  # Number of hours to check when a feature was added

fromEmail = 'user1@esri.com' # Email sender
toEmail = 'manager1@esri.com'   # Email receiver
smtpServer = 'smtp.gis.com'    # SMPT Server Name
portNumber = 25                 # SMTP Server port

# Create empty list for uniqueIDs
oidList = []

# Generate AGOL token
try:
    print('Generating Token')
    tokenURL = 'https://www.arcgis.com/sharing/rest/generateToken'
    params = {'f': 'pjson', 'username': username, 'password': password, 'referer': 'http://www.arcgis.com'}
    req = urllib2.Request(tokenURL, urllib.urlencode(params))
    response = urllib2.urlopen(req)
    data = json.load(response)
    token = data['token']
except:
    token = ''

# Query service and check if created_date time is within the last hour
params = {'f': 'pjson', 'where': "1=1", 'outfields' : '{0}, {1}'.format(uniqueID, dateField), 'returnGeometry' : 'false', 'token' : token}
req = urllib2.Request(URL, urllib.urlencode(params))
response = urllib2.urlopen(req)
data = json.load(response)
for feat in data['features']:
    createDate = feat['attributes'][dateField]
    createDate = int(str(createDate)[0:-3])
    t = datetime.datetime.now() - timedelta(hours=hoursValue)
    t = time.mktime(t.timetuple())
    if createDate > t:
        oidList.append(feat['attributes'][uniqueID])

print(oidList)

# Email Info
FROM = fromEmail
TO = [toEmail]
SUBJECT = 'New Features Added'
TEXT = "Features with {0}s {1} were added.".format(uniqueID, oidList)

message = """\
From: %s
To: %s
Subject: %s

%s
"""
% (FROM, ", ".join(TO), SUBJECT, TEXT)

# If new features exist, send email
if len(oidList) > 0:
    smtpObj = smtplib.SMTP(host=smtpServer, port=portNumber)
    smtpObj.sendmail(FROM, TO, message)
    print "Successfully sent email"
    smtpObj.quit()
18 people found this helpful

Attachments

    Outcomes