Sending email on feature service edit

5046
23
Jump to solution
07-17-2018 06:55 AM
joerodmey
MVP Alum

I'm looking to have an email sent out each time my hosted feature service (on AGOL) has my status field altered. This status field is set to "not complete" by default, and as its completed it changes to "complete". When this happens I want an email sent out.

I've been playing around with webhooks and services likes Microsoft Flow and Integromat but not having too much success.

Any ideas?

Tags (1)
0 Kudos
1 Solution

Accepted Solutions
DougBrowning
MVP Esteemed Contributor

Ok I got it after some searching.  GMAIL is much different.

Do this

change this line #server = smtplib.SMTP(emailSMTP)

to server = smtplib.SMTP_SSL(emailSMTP,465)

Remove the port number from the top so change emailSMTP = "smtp.gmail.com:587"

 to just emailSMTP = "smtp.gmail.com"

Change this line #server.starttls() 

to server.ehlo()

Add your username and pass to the lines

smtpusername = "you@gmail.com"
smtppassword = "pass"

Oh and the big one is go to https://myaccount.google.com/lesssecureapps?pli=1 then enable access!!

It now works.

View solution in original post

23 Replies
JakeSkinner
Esri Esteemed Contributor
joerodmey
MVP Alum

Hi Jake,

Played around with it a bit but keep getting this error:

0 Kudos
JakeSkinner
Esri Esteemed Contributor

You didn't attach the error you are receiving.  Can you also post your updated code?

0 Kudos
joerodmey
MVP Alum

Error picture attached to my previous reply.

Updated code (with a few omissions):

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

# Variables
username = 'OMIT'        # AGOL Username
password = 'OMIT'    # AGOL Password

URL = 'https://services8.arcgis.com/XWI9YRo0bQGkCetU/arcgis/rest/services/service_OMIT6b3cc03bba146dc6d/Fea.....'       # 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 = 'OMIT' # Email sender
toEmail = 'OMIT'   # Email receiver
smtpServer = 'OMIT'    # 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()

0 Kudos
JakeSkinner
Esri Esteemed Contributor

Can you share the service to a Group and invite my user account (jskinner_CountySandbox)?  I can take a look.

0 Kudos
joerodmey
MVP Alum

Sent invite

0 Kudos
JakeSkinner
Esri Esteemed Contributor

Try changing your fields to the following:

uniqueID = 'objectid'
dateField = 'EditDate'
0 Kudos
joerodmey
MVP Alum

No luck Jake

0 Kudos
JakeSkinner
Esri Esteemed Contributor

I added a feature and then ran the following:

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

# Variables
username = 'test'        # AGOL Username
password = 'test'    # AGOL Password

URL = 'https://services8.arcgis.com/XWI9YRo0bQGkCetU/arcgis/rest/services/service_e543c2e23b6d40a6b3cc03bba...'       # Feature Service URL
uniqueID = 'objectid'           # i.e. OBJECTID
dateField = 'EditDate'      # Date field to query
hoursValue = 1                  # Number of hours to check when a feature was added

fromEmail = 'test@esri.com' # Email sender
toEmail = 'test@esri.com'   # Email receiver
smtpServer = 'smtp.test.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()

I then received an e-mail:

Features with objectids [1034] were added.