Python code
endpoint = f'https://graph.microsoft.com/v1.0/users/{user_id}/messages'
# Fetch the read emails
response = requests.get(endpoint, headers=headers)
if response.status_code != 200:
print(f"Failed to fetch emails: {response.text}")
exit(1)
# Process the emails
emails = response.json().get('value', [])
for email in emails:
email_id = email['id']
email_has_attachments = email['hasAttachments']
sub = email['subject']
email_isRead = email['isRead']
email_from = email['from']
email_sender = email['sender']
# Check if the email has attachments
if email_has_attachments :
print(f"Email from has {email_from['emailAddress']['name']}, email address {email_from['emailAddress']['address']} has attachments.")
# Fetch the attachments
attachments_endpoint = endpoint + f"/{email_id}/attachments"
attachments_response = requests.get(attachments_endpoint, headers=headers)
if attachments_response.status_code != 200:
print(f"Failed to fetch attachments: {attachments_response.text}")
continue
attachments_response_json = attachments_response.json().get('value', [])
for attachment in attachments_response_json:
# Check if the attachment is an Excel file
attachment_name = attachment['name']
if attachment_name.endswith('.xlsx'):
print(f"Downloading Excel attachment: {attachment_name}")
attachment_id = attachment['id']
download_attachment_endpoint = attachments_endpoint + f"/{attachment_id}" # /$value
headers = {
"Authorization": f"Bearer {access_token}",
"ContentType": "application/octet-stream"
}
download_attachment_response = requests.get(attachments_endpoint, headers=headers)
if download_attachment_response.status_code == 200:
print(f' Saving file : {attachment_name}')
with open(download_folder + f'/{attachment_name}', 'wb') as _f:
_f.write(download_attachment_response.content)
After running the above python code, the email attachment is saved on my device but when i open it in excel it shows this dialog box (above image).