Python: Send Email via Microsoft Graph API

Raymond Raymond event 2021-09-11 visibility 16,498
more_vert
Python: Send Email via Microsoft Graph API

In article Load Microsoft 365 SharePoint List Data in Python, I provided detailed steps to load SharePoint List data through msal package. For details about how to install required Python packages and also to setup , refer to the SharePoint article. 

Setup permission

We need to add permissions for sending emails: Mail.Send. This permission allows you to send emails as any user.

2021091131356-image.png

After adding the permission, make sure you also provide consent for the application.

Create the script to send email

With user token and users ready, we can now use them to send email in a Python client application.

Add a python script with the following content:

import json
import msal

import requests

client_id = '***'
client_secret = '***'
tenant_id = '***'
authority = f"https://login.microsoftonline.com/{tenant_id}"

app = msal.ConfidentialClientApplication(
    client_id=client_id,
    client_credential=client_secret,
    authority=authority)

scopes = ["https://graph.microsoft.com/.default"]

result = None
result = app.acquire_token_silent(scopes, account=None)

if not result:
    print(
        "No suitable token exists in cache. Let's get a new one from Azure Active Directory.")
    result = app.acquire_token_for_client(scopes=scopes)

# if "access_token" in result:
#     print("Access token is " + result["access_token"])


if "access_token" in result:
    userId = "***"
    endpoint = f'https://graph.microsoft.com/v1.0/users/{userId}/sendMail'
    toUserEmail = "***"
    email_msg = {'Message': {'Subject': "Test Sending Email from Python",
                             'Body': {'ContentType': 'Text', 'Content': "This is a test email."},
                             'ToRecipients': [{'EmailAddress': {'Address': toUserEmail}}]
                             },
                 'SaveToSentItems': 'true'}
    r = requests.post(endpoint,
                      headers={'Authorization': 'Bearer ' + result['access_token']}, json=email_msg)
    if r.ok:
        print('Sent email successfully')
    else:
        print(r.json())
else:
    print(result.get("error"))
    print(result.get("error_description"))
    print(result.get("correlation_id"))

Remember to replace the highlighted variables accordingly. For user ID of email account, you can find it in Azure Active Directory or Microsoft 365 admin center.

Run the script and the email will sent successfully:

2021091161744-image.png

References

Load Microsoft 365 SharePoint List Data in Python

Send mail

More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts