POST
|
Consistently getting this error when trying to modify the example "Deploy Automatic Notifications" notebook. I am using gmail and have enabled "allow less secure apps" in the gmail settings. I can successfully send notifications from local python (2.7) using the same parameters but keep getting an error when using AGOL Notebook. Any suggestions? def send_email_smtp(recipients, message,
subject="Message from your Notebook"):
"""Sends the `message` string to all of the emails in the
`recipients` list using the configured SMTP email server.
"""
try:
# Set up server and credential variables
smtp_server_url = "smtp.gmail.com"
smtp_server_port = 587
sender = "EmailAddress@gmail.com"
username = "EmailAddress@gmail.com"
password = secrets["smtp_email_password"]
server = smtplib.SMTP(smtp_server_url, smtp_server_port)
server.ehlo()
server.starttls() # Needed if TLS is required w/ SMTP server
server.login(username, password)
except Exception as e:
log.warning("Error setting up SMTP server, couldn't send " +
f"message to {recipients}")
raise e
# For each recipient, construct the message and attempt to send
did_succeed = True
for recipient in recipients:
try:
message_body = '\r\n'.join(['To: {}'.format(recipient),
'From: {}'.format(sender),
'Subject: {}'.format(subject),
'',
'{}'.format(message)])
message_body = message_body.encode("utf-8")
server.sendmail(sender, [recipient], message_body)
print(f"SMTP server returned success for sending email "\
f"to {recipient}")
except Exception as e:
log.warning(f"Failed sending message to {recipient}")
log.warning(e)
did_succeed = False
# Cleanup and return
server.quit()
return did_succeed ------------------------------------------------------------------------------------------------------ send_email_smtp(recipients = ['DifferentEmail@gmail.com'],
message = "Hello World!") ------------------------------------------------------------------------------------------------------ Full error: Error setting up SMTP server, couldn't send message to ['DifferentEmail@gmail.com'] ---------------------------------------------------------------------------OSError Traceback (most recent call last)<ipython-input-49-6f063c68c4ea> in <module> 1 send_email_smtp(recipients = ['DifferentEmail@gmail.com'],----> 2 message = "Hello World!")<ipython-input-48-2a35190fcbcd> in send_email_smtp(recipients, message, subject) 23 log.warning("Error setting up SMTP server, couldn't send " + 24 f"message to {recipients}")---> 25 raise e 26 27 # For each recipient, construct the message and attempt to send<ipython-input-48-2a35190fcbcd> in send_email_smtp(recipients, message, subject) 16 password = secrets["smtp_email_password"] 17 ---> 18 server = smtplib.SMTP(smtp_server_url, smtp_server_port) 19 server.ehlo() 20 server.starttls() # Needed if TLS is required w/ SMTP server/opt/conda/lib/python3.6/smtplib.py in __init__(self, host, port, local_hostname, timeout, source_address) 249 250 if host:--> 251 (code, msg) = self.connect(host, port) 252 if code != 220: 253 self.close()/opt/conda/lib/python3.6/smtplib.py in connect(self, host, port, source_address) 334 if self.debuglevel > 0: 335 self._print_debug('connect:', (host, port))--> 336 self.sock = self._get_socket(host, port, self.timeout) 337 self.file = None 338 (code, msg) = self.getreply()/opt/conda/lib/python3.6/smtplib.py in _get_socket(self, host, port, timeout) 305 self._print_debug('connect: to', (host, port), self.source_address) 306 return socket.create_connection((host, port), timeout,--> 307 self.source_address) 308 309 def connect(self, host='localhost', port=0, source_address=None):/opt/conda/lib/python3.6/socket.py in create_connection(address, timeout, source_address) 722 723 if err is not None:--> 724 raise err 725 else: 726 raise error("getaddrinfo returns an empty list")/opt/conda/lib/python3.6/socket.py in create_connection(address, timeout, source_address) 711 if source_address: 712 sock.bind(source_address)--> 713 sock.connect(sa) 714 # Break explicitly a reference cycle 715 err = NoneOSError: [Errno 99] Cannot assign requested address
... View more
04-23-2020
02:26 PM
|
0
|
6
|
4218
|
DOC
|
I am running into an issue where createDate is never greater than t despite there being features created within the time range. I suspect there is a difference between how the CreationDate field values are formatted vs the value of t but I am not sure what that is. Code: import urllib2, json, urllib, datetime, time, smtplib, requests from datetime import timedelta oidList = [] #Variables for your ArcGIS online account username = 'user' #AGOL UserName password = 'pass' #AGOL password #Variables hoursValue = 48 uniqueID = 'OBJECTID' # Feature Service URL URL = 'https://services.arcgis.com/URL/FeatureServer/0/query' # 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 = '' print("Token: " + str(token)) params = {'f': 'pjson', 'where': "1=1", 'outfields' : 'OBJECTID, CreationDate', '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']['CreationDate'] createDate = int(str(createDate)[0:-3]) t = datetime.datetime.now() - timedelta(hours=hoursValue) t = time.mktime(t.timetuple()) if createDate > t: oidList.append(str(feat['attributes'][uniqueID])) FROM = 'something@gmail.com' TO = ['something@something.com'] SUBJECT = 'New Service Requests' TEXT = "New service requests have been received. Please go to the Service Request Tracking app to review.\n\nhttps://appURLhere" message =""" 'Subject: New Service Requests Added'.format(SUBJECT, TEXT) From: %s To: %s Subject: %s %s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) gmailPwd = 'gmailpass' if len(oidList) > 0:
smtpObj = smtplib.SMTP(host='smtp.gmail.com', port= 587)
smtpObj.starttls()
smtpObj.login(FROM, gmailPwd)
smtpObj.sendmail(FROM, TO, message)
print "Successfully sent email"
smtpObj.quit()
else:
print "No new data found"
... View more
10-29-2019
06:44 AM
|
0
|
0
|
7023
|
DOC
|
Did you ever get this to return multiple records? I am running into the same issue.
... View more
04-27-2018
04:39 AM
|
1
|
0
|
19578
|
Title | Kudos | Posted |
---|---|---|
1 | 04-27-2018 04:39 AM |
Online Status |
Offline
|
Date Last Visited |
03-28-2024
12:23 PM
|