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.
Install & Compatibility
Where this runs
tested against v2.1.9 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
44MB installed
● package 44MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
Account
✓ from O365 import Account
FileSystemTokenBackend
✓ from O365.utils import FileSystemTokenBackend
Used for persisting authentication tokens to the filesystem.
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.')
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'O365'
The `o365` library, or one of its components, is not found because it's either not installed, installed in a different Python environment, or there's a mismatch in the import statement's casing or package name (e.g., confusing `O365` with `office365-REST-Python-Client`).
fixEnsure the `O365` package is installed in your current Python environment using `pip install O365`. Verify that your import statements use the correct casing, for example: `from O365 import Account`.
AADSTS700016: Application with identifier 'x' was not found in the directory 'y'.
This Azure AD error indicates that the client application (identified by its client ID) is either not correctly registered in Microsoft Entra ID (Azure AD), is registered in a different tenant than specified, or has not been consented to by an administrator or user in the target directory.
fixVerify that your `client_id` and `tenant_id` precisely match the Azure AD application registration, ensure the application is registered in the correct Microsoft Entra tenant, and confirm that all necessary API permissions have been granted and consented by an administrator.
Authentication unsuccessful
This general authentication failure often occurs due to Microsoft's deprecation of Basic Authentication, or when the OAuth 2.0 authentication flow is incorrectly configured (e.g., wrong client secret, invalid redirect URI, insufficient scopes), preventing the application from acquiring a valid access token.
fixEnsure you are using OAuth 2.0 for authentication. Verify your Azure AD app registration settings, including client ID, client secret, redirect URIs, and requested scopes. Make sure the authentication flow (e.g., interactive consent for 'on behalf of a user' flow or 'credentials' flow for daemon apps) is correctly implemented in your code.
AttributeError: 'NoneType' object has no attribute 'text'
This error typically means an operation (such as an API call to retrieve an item or a property) returned `None` instead of the expected object, and you subsequently tried to access an attribute (like 'text') on that `None` object. This can happen if the requested resource doesn't exist, access is denied, or the API call failed to return data.
fixAdd checks in your code to verify that the object returned by an `o365` operation is not `None` before attempting to access its attributes. Debug the specific API call to ensure the resource exists and proper permissions are in place, for example: `if message and message.body:`.
Audit
Dependencies
requestsrequiredHTTP client for API requests.
msalrequiredMicrosoft Authentication Library for token acquisition.
beautifulsoup4requiredHTML parsing for certain operations.
python-dateutilrequiredDate and time utilities.
tzlocalrequiredDetermining local timezone.
tzdatarequiredTimezone data, especially for newer Python versions.