Select to view content in your preferred language

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

54004
201
06-02-2017 05:46 AM

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

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 specified field values for the new feature(s).

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.

The below example is written for the Citizen Problem Report application.  It utilizes 2 fields (reqtype & status) when querying the service.  These variables can be commented out, or updated to reference different fields, if working with a different service:

JakeSkinner_0-1718898357689.png

The SUBJECT and TEXT variables in the sendEmail function can be updated to whatever you would like to include in the e-mail:

JakeSkinner_1-1718898385654.png

 

 

 

from arcgis.gis import GIS
from arcgis.features import FeatureLayer
import datetime, time, smtplib
from datetime import timedelta
from email.mime.text import MIMEText

# Variables
username = 'jskinner_rats'                                                                                      # AGOL Username
password = '********'                                                                                           # AGOL Password
fsURL = 'https://services.arcgis.com/dfRzIozUOVYoi65F/arcgis/rest/services/Requests/FeatureServer/0'            # Feature Service URL
dateField = 'created_date'                                                                                      # Date field to query
hours = 1                                                                                                       # Number of hours to check when a feature was added
fromEmail = 'no-reply@esri.com'                                                                                 # From e-mail address
toEmail = ['user1@esri.com', 'user2@esri.com']                                                                  # To e-mail address(es)
smtpServer = 'smtp.esri.com'                                                                                    # SMTP Server Name
portNumber = 25                                                                                                 # SMTP Server port

# Function to send email
def sendEmail():
    SUBJECT = 'Problem Reported'
    TEXT = f"{reqtype} was created with status {status}"
    smtpObj = smtplib.SMTP(host=smtpServer, port=portNumber)

    msg = MIMEText(TEXT)
    msg['Subject'] = SUBJECT
    msg['From'] = fromEmail
    msg['To'] = ", ".join(toEmail)

    smtpObj.sendmail(fromEmail, toEmail, msg.as_string())
    print("Successfully sent email")
    smtpObj.quit()

# Generate AGOL token
print('Connecting to AGOL')
gis = GIS('https://www.arcgis.com', username, password)

# Reference feature service from url
fLyr = FeatureLayer(fsURL)

# Query service and check if date field is within the last hour
print("Querying feature service")
queryResults = fLyr.query(where='1=1', out_fields="*", return_geometry=False)
for results in queryResults.features:
    if results.attributes[dateField] != None:
        createDate = results.attributes[dateField] / 1000
        reqtype = results.attributes['reqtype']
        status = results.attributes['status']
        t = datetime.datetime.now() - timedelta(hours=hours)
        t = time.mktime(t.timetuple())
        if createDate > t:
           sendEmail()

 

 

 

Attachments
Comments
JakeSkinner
Esri Esteemed Contributor

@James_Shreeve ,

Yes, you can dynamically use field values.  The query results are returning all field values, so you could do something similar to below.  The example is assigning an variable status with the value from a field called Status in the feature service, then using this in the e-mail message.

# Query service and check if date field is within the last hour
print("Querying feature service")
queryResults = fLyr.query(where='1=1', out_fields="*", return_geometry=False)
for results in queryResults.features:
    if results.attributes[dateField] != None:
        status = results.attributes['Status']
        emailMessage = f"Status is currently {status}"
        createDate = results.attributes[dateField] / 1000
        t = datetime.datetime.now() + timedelta(weeks=weeks_check)
        t = time.mktime(t.timetuple())
        if createDate > t:
            # Send e-mail
            print('Sending e-mail')
            allUsersGroup.notify(users=userList, subject=emailSubject, message=emailMessage)
Version history
Last update:
‎06-20-2024 08:50 AM
Updated by:
Contributors