O365 - Microsoft Graph and Office 365 API made easy
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
- breaking Version 2.1 introduced a breaking change by removing custom authentication in favor of `msal`. Existing applications will require a new authentication flow and older access tokens will no longer work.
- breaking Python 3.9 support was removed in version 2.1.7. Additionally, the 'Old Query' syntax was deprecated in favor of the new `QueryBuilder`.
- gotcha Microsoft deprecated basic authentication for Office 365 APIs on November 1st, 2018. `o365` exclusively uses OAuth authentication. Incorrect Azure AD application registration, insufficient API permissions (scopes), or an incorrect `tenant_id` (especially for client credentials flow) are common causes of authentication failures (e.g., 'AADSTS' errors).
- gotcha Authentication tokens contain sensitive information and must be securely stored. By default, `o365` attempts to store tokens, but custom token backends (e.g., `FileSystemTokenBackend`, `FirestoreTokenBackend`) are crucial for production environments to manage token persistence and protection.
Install
-
pip install O365
Imports
- Account
from O365 import Account
- FileSystemTokenBackend
from O365.utils import FileSystemTokenBackend
Quickstart
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.')