Python: Send Email via Microsoft Graph API

Raymond Raymond visibility 13,319 event 2021-09-11 access_time 3 years ago language English

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.


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"{tenant_id}"

app = msal.ConfidentialClientApplication(

scopes = [""]

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

if not result:
        "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'{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 =,
                      headers={'Authorization': 'Bearer ' + result['access_token']}, json=email_msg)
    if r.ok:
        print('Sent email successfully')

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:



Load Microsoft 365 SharePoint List Data in Python

Send mail

More from Kontext
info Last modified by Raymond 3 years ago copyright This page is subject to Site terms.
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts