O365 - Microsoft Graph and Office 365 API made easy

2.1.9 · active · verified Thu Apr 09

The `o365` Python library provides a simple and Pythonic interface for interacting with Microsoft Graph and Office 365 APIs. It supports access to various services including Email, Calendar, Contacts, OneDrive, and SharePoint. The library handles OAuth authentication, token refreshing, and datetime conversions automatically. It is actively maintained, with the current stable version being 2.1.9, and receives regular updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to authenticate with Microsoft Graph using `o365` and then send a simple email. It uses environment variables for `CLIENT_ID`, `CLIENT_SECRET`, and `TENANT_ID` (if applicable) and shows how to set up `FileSystemTokenBackend` for persistent token storage. The default authentication flow is interactive, requiring user consent via a console-provided URL. Ensure your Azure AD application is registered with the correct redirect URI and API permissions (scopes).

import os
from O365 import Account
from O365.utils import FileSystemTokenBackend

CLIENT_ID = os.environ.get('O365_CLIENT_ID', 'your_client_id')
CLIENT_SECRET = os.environ.get('O365_CLIENT_SECRET', 'your_client_secret')
# Optional: TENANT_ID is required for 'credentials' auth_flow_type
TENANT_ID = os.environ.get('O365_TENANT_ID', None)

credentials = (CLIENT_ID, CLIENT_SECRET)

# Configure token storage. Create a 'o365_token' directory if it doesn't exist.
token_backend = FileSystemTokenBackend(token_path='o365_token', token_filename='o365_token.txt')

# Initialize Account with credentials and token backend
# For interactive login (default):
account = Account(credentials, token_backend=token_backend)

# For app-only login (client credentials flow):
# account = Account(credentials, token_backend=token_backend, auth_flow_type='credentials', tenant_id=TENANT_ID)

# Define necessary scopes for your application (e.g., Mail.ReadWrite, Mail.Send)
# You can use scope helpers: from O365.scopes import MSGraphScopeBuilder; scopes = MSGraphScopeBuilder.for_mail().build()
requested_scopes = ['basic', 'offline_access', 'Mail.ReadWrite', 'Mail.Send']

if not account.is_authenticated:
    print('Authenticating...')
    # The authenticate method will print a URL. Visit it, log in, and paste the redirect URL back.
    if account.authenticate(scopes=requested_scopes) is False:
        raise RuntimeError('Authentication Failed. Check your credentials, scopes, and token_path.')
    print('Authentication successful!')
else:
    print('Already authenticated.')

# Now you can interact with the O365 services, e.g., send an email
m = account.new_message()
m.to.add('recipient@example.com')
m.subject = 'Hello from O365 Python Library!'
m.body = "This is a test email sent using the o365 library."
if m.send():
    print('Email sent successfully!')
else:
    print('Failed to send email.')

view raw JSON →