Microsoft Graph Python SDK

1.55.0 · active · verified Thu Apr 09

The Microsoft Graph Python SDK is a client library for interacting with the Microsoft Graph API, enabling Python applications to access data across Microsoft 365, Windows, and Enterprise Mobility + Security. It supports the v1.0 of Microsoft Graph and is asynchronous by default, designed for modern Python applications. The library is actively maintained with frequent releases, currently at version 1.55.0, and leverages the underlying `msgraph-core` library and `kiota-authentication-azure` for core functionalities and authentication.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `GraphServiceClient` using `ClientSecretCredential` for app-only authentication (daemon app scenario) and fetch messages for a specific user. It highlights the asynchronous nature of the SDK and the use of environment variables for sensitive credentials. Remember to replace placeholder values and ensure your application registration has the necessary API permissions (e.g., `Mail.Read.All`) and admin consent.

import asyncio
import os
from azure.identity.aio import ClientSecretCredential
from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider
from msgraph import GraphServiceClient
from msgraph.generated.models.message import Message

async def main():
    # Environment variables for client credentials flow
    tenant_id = os.environ.get('TENANT_ID', 'YOUR_TENANT_ID')
    client_id = os.environ.get('CLIENT_ID', 'YOUR_CLIENT_ID')
    client_secret = os.environ.get('CLIENT_SECRET', 'YOUR_CLIENT_SECRET')
    user_id = os.environ.get('USER_ID', 'YOUR_USER_ID') # User to fetch messages from

    # Ensure required environment variables are set
    if not all([tenant_id, client_id, client_secret, user_id]):
        print("Please set TENANT_ID, CLIENT_ID, CLIENT_SECRET, and USER_ID environment variables.")
        return

    # For app-only permissions, use the .default scope
    scopes = ['https://graph.microsoft.com/.default']

    # Create a credential object
    credential = ClientSecretCredential(
        tenant_id=tenant_id,
        client_id=client_id,
        client_secret=client_secret
    )

    # Create an authentication provider
    auth_provider = AzureIdentityAuthenticationProvider(credential, scopes=scopes)

    # Create a GraphServiceClient
    client = GraphServiceClient(auth_provider)

    try:
        # Fetch messages for a specific user
        # Note: This requires Mail.Read.All application permission or Mail.Read delegated permission for the user_id
        # if using delegated flow.
        messages_collection = await client.users.by_user_id(user_id).messages.get()

        if messages_collection and messages_collection.value:
            print(f"Successfully fetched {len(messages_collection.value)} messages for user {user_id}:")
            for msg in messages_collection.value:
                print(f"  Subject: {msg.subject}, From: {msg.sender.email_address.address}")
        else:
            print(f"No messages found for user {user_id}.")

    except Exception as e:
        print(f"Error fetching messages: {e}")

if __name__ == '__main__':
    asyncio.run(main())

view raw JSON →