Registry / communication / o365

o365

JSON →
library2.1.9pypypi✓ verified 52d ago

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.

communicationcrm-productivityauth-security
pip install O365
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
musl
glibc
py 3.10
✓ —
✓ 3.93s
py 3.11
✓ —
✓ 3.83s
py 3.12
✓ —
✓ 3.38s
py 3.13
✓ —
✓ 3.3s
py 3.9
4/5 runs
4/5 runs
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.')
Debug
Known issues
breakingVersion 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.
fix
Re-authenticate all existing `o365` applications to obtain new tokens. Ensure `msal` is correctly installed as a dependency.
affects: >=2.1.0
breakingPython 3.9 support was removed in version 2.1.7. Additionally, the 'Old Query' syntax was deprecated in favor of the new `QueryBuilder`.
fix
Upgrade your Python environment to 3.10 or newer. If using the old query style, migrate to `QueryBuilder` for future compatibility, although the old query remains interchangeable for other methods for now.
affects: >=2.1.7
gotchaMicrosoft 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).
fix
Ensure your application is registered in Azure AD with the 'Web' platform and a redirect URI (e.g., `http://localhost:8000`). Grant the necessary delegated or application permissions (scopes, e.g., `Mail.ReadWrite`, `Mail.Send`, `offline_access`). For `auth_flow_type='credentials'`, you must provide the `tenant_id` and ensure appropriate application permissions are granted.
affects: All versions
gotchaAuthentication 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.
fix
Implement a `TokenBackend` appropriate for your environment (e.g., `FileSystemTokenBackend` for local storage or cloud-specific backends) and ensure that the token storage location is protected. Consider using a `cryptography_manager` with your `TokenBackend` for encryption.
affects: All versions
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`).
fix
Ensure 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.
fix
Verify 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.
fix
Ensure 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.
fix
Add 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:`.
Upgrade
Version history
2.1.9latest on PyPI
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.
Agent activity
78 hits · last 30 days
node
8
seranking-bot
4
ahrefsbot
2
Amazon
1
Resources