Select to view content in your preferred language

Notebook - Create a .csv from feature service - Send Email to a user with .csv attachment

784
5
Jump to solution
04-01-2024 10:45 AM
ChristopherMask
Regular Contributor

The code is generating the .csv, but I am lost when sending an email. Any help would be excellent. 

 

# Function to send an email with attachment

UserList = []
users = gis.users.search(max_users=10000)
#print(users)


emails_of_user = [member.email for member in users]
#print(emails_of_user)

# Find the user with the specified email address
unique_user = next((member for member in users if member.email == 'christopher.mask@ag.ok.gov'), None)

# Check if the user with the specified email is found
if unique_user:
print("Unique user found:")
print("Username:", unique_user.username)
print("Email:", unique_user.email)
group.notify(users=unique_user, subject= "Test Message", message="Testing the notification system",method="email")

else:
print("User with email not found.")

 

print results are:

CSV file exported successfully to: HistoricalFireOccurrence_VFD_LastMonth.csv
Unique user found:
Username: CMask_OKForestry
Email: christopher.mask@ag.ok.gov

 

Not even sure this can be done with notebook.

 

Best,

Christopher Mask

0 Kudos
1 Solution

Accepted Solutions
EdMorris
Esri Contributor

Hello

So, as I understand it, you now want to send an email using the ArcGIS API for Python?

You may want to have a look at the send_notification() method. It is found on the admin.UserManager class and can be used with ArcGIS Online. I think it is deprecated for ArcGIS Enterprise 10.9....

View solution in original post

5 Replies
EdMorris
Esri Contributor

Hello

So, as I understand it, you now want to send an email using the ArcGIS API for Python?

You may want to have a look at the send_notification() method. It is found on the admin.UserManager class and can be used with ArcGIS Online. I think it is deprecated for ArcGIS Enterprise 10.9....

ChristopherMask
Regular Contributor

The method worked and thank you for the insight. Is there a way to send an attachment in the email?

gis.users.send_notification([unique_user], "A new file has been created","Please download the new file", type = 'email')

 

0 Kudos
EdMorris
Esri Contributor

Hi

I'm not sure the API is capable of sending attachments when emails are generated by the API.

Perhaps you can embed a link to where your file is in your Portal, in your email using the following as a guide:

(3) New Line in notification and email - Esri Community

and then your user(s) can download it from the portal.

ChristopherMask
Regular Contributor

Sounds good. I have modified the code and created a task for the notebook to be executed at 12:00AM. Here is the final code and I appreciate the feedback, Ed.

 

from arcgis.gis import GIS
import datetime as dt
import pandas as pd
from datetime import datetime, timedelta

# Connect to your GIS
gis = GIS('home')

query = 'title: "HistoricalFireOccurrence" AND type: "Feature Service"'
search_results = gis.content.search(query=query, max_items=10)

HistoricalFireOccurrence_item = search_results[0]
HistoricalFireOccurrence_layer = HistoricalFireOccurrence_item.layers[0]

# Calculate the date range for the last month
end_date = datetime.now()
start_date = end_date - timedelta(days=31)

# Format the dates in a way that SQL can understand
start_date_str = start_date.strftime("%Y-%m-%d")
end_date_str = end_date.strftime("%Y-%m-%d")

# Define the where clause
where_clause = f"District = 'VFD' AND CreationDate BETWEEN '{start_date_str}' AND '{end_date_str}'"

# Retrieve features with the where clause applied
features = HistoricalFireOccurrence_layer.query(where=where_clause)

# Convert the features to a pandas DataFrame
df = features.df

# Export the DataFrame to a CSV file
csv_file_path = "HistoricalFireOccurrence_VFD_LastMonth.csv"
df.to_csv(csv_file_path, index=False)

print(f"CSV file exported successfully to: {csv_file_path}")

# Get the user you want to send the notification to
user1 = gis.users.get("CMask_OKForestry")
user2 = gis.users.get("cmask_noadmin")

# List of users to send the notification
recipients = [user1, user2]

# Check if the user with the specified email is found
if len(recipients) > 0:
messageSubject = 'This is a message from cmask_okforestry'
messageMessage = f'A new fire department file has been created and is ready to download. Please login to AGO. The file can be found by clicking Notebook, Open VFD Fire Occurrence Data Export, Click Files, Click on the file name to download: {csv_file_path}'
gis.users.send_notification(recipients, messageSubject, messageMessage, type='email')
else:
print("User with email not found.")

EdMorris
Esri Contributor

Good luck! I hope it does what you need it to do. Glad I could help a little bit.

Many thanks ed

0 Kudos