### Install Sphinx for Documentation Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/overview.rst.txt Install the necessary Sphinx libraries to build the project's documentation. This command is for a console environment. ```console pip install sphinx sphinx-rtd-theme ``` -------------------------------- ### Working with the Schedule instance Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/calendar.rst.txt This snippet demonstrates how to initialize the Schedule object, get the default calendar, create a new event, set its properties (subject, location, start time, recurrence, reminder), and save it. ```APIDOC ## Working with the Schedule instance This section shows how to interact with the `Schedule` object to manage calendars and events. ### Usage ```python import datetime as dt # Assuming 'account' is an authenticated O365 account object # from O365 import Account # credentials = ('client_id', 'client_secret') # account = Account(credentials) schedule = account.schedule() calendar = schedule.get_default_calendar() new_event = calendar.new_event() # creates a new unsaved event new_event.subject = 'Recruit George Best!' new_event.location = 'England' # Naive datetimes will automatically be converted to timezone aware datetime objects # using the local timezone detected or the protocol provided timezone. new_event.start = dt.datetime(2019, 9, 5, 19, 45) # Set daily recurrence from Sept 5th to Sept 10th, 2019 new_event.recurrence.set_daily(1, end=dt.datetime(2019, 9, 10)) new_event.remind_before_minutes = 45 new_event.save() ``` ### Notes - Naive datetime objects for `start` and `end` times are automatically converted to timezone-aware objects. - The `recurrence` object allows setting various recurrence patterns, such as daily, weekly, monthly, and yearly. - `remind_before_minutes` sets a reminder for the event. ``` -------------------------------- ### Install python-o365 using uv Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/getting_started.rst.txt Installs the latest stable version of the o365 library using the uv package installer. Requires Python 3.10 or higher. ```console uv add o365 ``` -------------------------------- ### Initialize Storage and Get Drives Source: https://github.com/o365/python-o365/blob/master/docs/source/usage/onedrive.rst Initialize the Account and Storage instances to access OneDrive. Lists all available drives and retrieves the default drive. Also shows how to get root and special folders, and iterate through items. ```python account = Account(credentials=my_credentials) storage = account.storage() # here we get the storage instance that handles all the storage options. # list all the drives: drives = storage.get_drives() # get the default drive my_drive = storage.get_default_drive() # or get_drive('drive-id') # get some folders: root_folder = my_drive.get_root_folder() attachments_folder = my_drive.get_special_folder('attachments') # iterate over the first 25 items on the root folder for item in root_folder.get_items(limit=25): if item.is_folder: print(list(item.get_items(2))) # print the first to element on this folder. elif item.is_file: if item.is_photo: print(item.camera_model) # print some metadata of this photo elif item.is_image: print(item.dimensions) # print the image dimensions else: # regular file: print(item.mime_type) # print the mime type ``` -------------------------------- ### Install latest development version using uv Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/getting_started.rst.txt Installs the latest development version from GitHub using the uv package installer. This version may be unstable. ```console uv add "o365 @ git+https://github.com/O365/python-o365" ``` -------------------------------- ### Install python-o365 using pip Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/getting_started.rst.txt Installs the latest stable version of the o365 library from PyPI. Requires Python 3.10 or higher. ```console pip install o365 ``` -------------------------------- ### Install latest development version using pip Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/getting_started.rst.txt Installs the latest development version directly from the GitHub repository. This version may be unstable. ```console pip install git+https://github.com/O365/python-o365.git ``` -------------------------------- ### Get All Contacts and Specific Folder Source: https://github.com/o365/python-o365/blob/master/docs/latest/usage/addressbook.html Demonstrates how to get all contacts from the root personal contacts folder and retrieve a specific folder by name. It also shows how to create a draft message to all contacts in a folder and send it. ```python address_book = account.address_book() contacts = address_book.get_contacts(limit=None) # get all the contacts in the Personal Contacts root folder work_contacts_folder = address_book.get_folder(folder_name='Work Contacts') # get a folder with 'Work Contacts' name message_to_all_contats_in_folder = work_contacts_folder.new_message() # creates a draft message with all the contacts as recipients message_to_all_contats_in_folder.subject = 'Hallo!' message_to_all_contats_in_folder.body = """ George Best quote: If you'd given me the choice of going out and beating four men and smashing a goal in from thirty yards against Liverpool or going to bed with Miss World, it would have been a difficult choice. Luckily, I had both. """ message_to_all_contats_in_folder.send() ``` -------------------------------- ### tasks Source: https://github.com/o365/python-o365/blob/master/docs/latest/api/account.html Get an instance to read information from Microsoft ToDo. ```APIDOC ## tasks ### Description Get an instance to read information from Microsoft ToDo. ### Parameters * **resource** (str) - Defaults to parent main_resource ``` -------------------------------- ### Get Apps in Team Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/teams.html Retrieves a list of applications installed in a specified team. ```APIDOC ## GET /teams/{team_id}/apps ### Description Returns a list of apps of a specified team. ### Method GET ### Endpoint /teams/{team_id}/apps ### Parameters #### Path Parameters - **team_id** (string) - Required - The ID of the team to get the apps of. ### Response #### Success Response (200) - **value** (list[App]) - A list of App objects. #### Response Example { "value": [ { "id": "app_id_1", "displayName": "App Name 1" } ] } ``` -------------------------------- ### Configure Account with Proxy Server (Option 1) Source: https://github.com/o365/python-o365/blob/master/docs/latest/usage/account.html Illustrates setting up proxy server details directly during Account instantiation. This is useful for environments requiring a proxy to access external APIs. ```python account = Account(credentials=('my_client_id', 'my_client_secret'), proxy_server='myserver.com', proxy_port=8080, proxy_username='username', proxy_password='password') ``` -------------------------------- ### Get Protocol-Specific Scopes using Scope Helpers Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/getting_started.rst.txt Utilize scope helpers to abstract protocol details and retrieve the correct scope format for a given service. This example shows how to get scopes for 'message_all' using MSGraphProtocol. ```python protocol_graph = MSGraphProtocol() scopes_graph = protocol.get_scopes_for('message_all') # scopes here are: ['https://graph.microsoft.com/Mail.ReadWrite', 'https://graph.microsoft.com/Mail.Send'] account = Account(credentials, requested_scopes=scopes_graph) ``` -------------------------------- ### Working with the ToDo Instance Source: https://github.com/o365/python-o365/blob/master/docs/latest/usage/tasks.html Demonstrates how to initialize the ToDo instance, get the default folder, create a new task, set its subject and due date, save it, and then mark it as completed. ```python import datetime as dt # ... todo = account.tasks() #list current tasks folder = todo.get_default_folder() new_task = folder.new_task() # creates a new unsaved task new_task.subject = 'Send contract to George Best' new_task.due = dt.datetime(2020, 9, 25, 18, 30) new_task.save() #some time later.... new_task.mark_completed() new_task.save() # naive datetimes will automatically be converted to timezone aware datetime # objects using the local timezone detected or the protocol provided timezone # as with the Calendar functionality ``` -------------------------------- ### Create Sharepoint Instance and Connect to Site Source: https://github.com/o365/python-o365/blob/master/docs/latest/usage/sharepoint.html Instantiate an Account object and then create a Sharepoint instance to connect to a specific site. Ensure you have the correct authentication credentials. ```python from O365 import Account acct = Account(('app_id', 'app_pw')) sp_site = acct.sharepoint().get_site('root', 'path/tosite') ``` -------------------------------- ### Get Apps in Team - O365 Teams Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/teams.html Retrieves a list of applications installed in a specified team. Requires a valid `team_id`. ```python def get_apps_in_team(self, team_id): """ Returns a list of apps of a specified team :param team_id: the team_id of the team to get the apps of. :rtype: list[App] """ url = self.build_url( self._endpoints.get('get_apps_in_team').format(team_id=team_id)) response = self.con.get(url) if not response: return [] data = response.json() return [ self.app_constructor(parent=self, **{self._cloud_data_key: site}) for site in data.get('value', [])] ``` -------------------------------- ### Presence Management Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/teams.rst.txt This section covers how to retrieve and set the presence status of users. It includes examples for getting your own presence, another user's presence, and setting your own presence or preferred presence. ```APIDOC ## Presence Management ### Description This section covers how to retrieve and set the presence status of users. It includes examples for getting your own presence, another user's presence, and setting your own presence or preferred presence. ### Methods - `get_my_presence()`: Retrieves the presence status of the logged-in user. - `get_user_presence(user_id)`: Retrieves the presence status of a specified user. - `set_my_presence(client_id, availability, activity, duration)`: Sets the presence status for the logged-in user. - `set_my_user_preferred_presence(preferred_availability, preferred_activity, duration)`: Sets the preferred presence status for the logged-in user. ### Code Examples **Retrieve logged-in user's presence:** ```python from O365 import Account account = Account(('app_id', 'app_pw')) teams = account.teams() presence = teams.get_my_presence() ``` **Retrieve another user's presence:** ```python from O365 import Account account = Account(('app_id', 'app_pw')) teams = account.teams() user = account.directory().get_user("john@doe.com") presence2 = teams.get_user_presence(user.object_id) ``` **Set user's presence:** ```python from O365.teams import Activity, Availability # Assuming 'teams' is an authenticated Teams object status = teams.set_my_presence(CLIENT_ID, Availability.BUSY, Activity.INACALL, "1H") ``` **Set user's preferred presence:** ```python from O365.teams import PreferredActivity, PreferredAvailability # Assuming 'teams' is an authenticated Teams object status = teams.set_my_user_preferred_presence(PreferredAvailability.OFFLINE, PreferredActivity.OFFWORK, "1H") ``` ``` -------------------------------- ### Initializing Storage and Retrieving Drives Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/onedrive.rst.txt Demonstrates how to initialize the storage instance and retrieve a list of drives or the default drive. ```APIDOC ## Initializing Storage and Retrieving Drives ### Description This snippet shows how to get the storage instance from an authenticated account and then retrieve all available drives or the default drive. ### Method ```python account = Account(credentials=my_credentials) storage = account.storage() # List all drives drives = storage.get_drives() # Get the default drive my_drive = storage.get_default_drive() # or get_drive('drive-id') ``` ``` -------------------------------- ### Configure Account with Proxy Server (Option 1) Source: https://github.com/o365/python-o365/blob/master/docs/source/usage/account.rst Set up proxy server details, including server address, port, username, and password, during Account instantiation. ```python # Option 1 account = Account(credentials=('my_client_id', 'my_client_secret'), proxy_server='myserver.com', proxy_port=8080, proxy_username='username', proxy_password='password) ``` -------------------------------- ### Create SharePoint Instance and Connect to Site Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/sharepoint.rst.txt Initializes an Account object and connects to a specific SharePoint site. Ensure you have the correct app ID and secret. ```python #Create Sharepoint instance and connect to a site from O365 import Account acct = Account(('app_id', 'app_pw')) sp_site = acct.sharepoint().get_site('root', 'path/tosite') ``` -------------------------------- ### Instantiate Account with credentials Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/account.rst.txt Initialize an Account object with your client ID and secret for authentication. ```python from O365 import Account account = Account(credentials=('my_client_id', 'my_client_secret')) ``` -------------------------------- ### Shorthand GET Request Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/connection.html Provides a convenient shorthand for making a GET request using an OAuth session. It calls the `oauth_request` method with the 'get' method type. ```python def get(self, url, params=None, **kwargs): """ Shorthand for self.oauth_request(url, 'get') :param str url: url to send get oauth request to :param dict params: request parameter to get the service data :param kwargs: extra params to send to request api :return: Response of the request :rtype: requests.Response """ return self.oauth_request(url, 'get', params=params, **kwargs) ``` -------------------------------- ### Configure Account with Proxy Server (Option 2) Source: https://github.com/o365/python-o365/blob/master/docs/latest/usage/account.html Demonstrates setting the proxy server configuration after the Account object has been created using the `connection.set` method. ```python account = Account(credentials=('my_client_id', 'my_client_secret')) account.connection.set('myserver.com',8080,'username', 'password') ``` -------------------------------- ### Reminder Minutes Before Start Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/calendar.html Configure the number of minutes before an event starts that the reminder should be triggered. ```APIDOC ## Reminder Minutes Before Start ### Description Configure the number of minutes before an event starts that the reminder should be triggered. ### Getter Gets the current number of minutes set for the reminder. ### Setter Sets the reminder to trigger a specified number of minutes before the event starts. This action also enables the reminder. ### Type `int` ``` -------------------------------- ### Working with the ToDo instance Source: https://github.com/o365/python-o365/blob/master/docs/source/usage/tasks.rst This section demonstrates how to initialize the ToDo object, get the default task folder, create a new task, set its properties (subject, due date), save it, and mark it as completed. ```APIDOC ## Working with the ToDo instance ### Description Initialize the ToDo object, retrieve the default task folder, create a new task, set its subject and due date, save the task, and then mark it as completed. ### Method ```python import datetime as dt # ... todo = account.tasks() # list current tasks folder = todo.get_default_folder() new_task = folder.new_task() # creates a new unsaved task new_task.subject = 'Send contract to George Best' new_task.due = dt.datetime(2020, 9, 25, 18, 30) new_task.save() # some time later.... new_task.mark_completed() new_task.save() # naive datetimes will automatically be converted to timezone aware datetime # objects using the local timezone detected or the protocol provided timezone # as with the Calendar functionality ``` ``` -------------------------------- ### Webhook Notification Example Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/subscriptions.rst.txt An example of a webhook notification received when a change occurs for a subscribed resource. ```APIDOC ## Webhook Notification ### Description This is an example of a webhook notification that might be received when a change occurs for a subscribed resource, such as a new email arriving in the inbox. ### Response Example ```json { "value": [ { "subscriptionId": "548355f8-c2c0-47ae-aac7-3ad02b2dfdb12", "subscriptionExpirationDateTime": "2026-01-07T11:35:40.301594+00:00", "changeType": "created", "resource": "Users/12345678-a5c7-46da-8107-b25090a1ed66/Messages/=", "resourceData": { "@odata.type": "#Microsoft.Graph.Message", "@odata.id": "Users/12345678-a5c7-46da-8107-b25090a1ed66/Messages/=", "@odata.etag": "W/\"CQAAABYACCCoiRErLbiNRJDCFyMjq4khBBnH4N7A\"", "id": "=" }, "clientState": "abc123", "tenantId": "12345678-abcd-1234-abcd-1234567890ab" } ] } ``` ### Usage Validate the `clientState` for accuracy. If correct, the message can be acted upon as appropriate for the type of subscription. ``` -------------------------------- ### get Source: https://github.com/o365/python-o365/blob/master/docs/latest/api/connection.html Shorthand for making a GET request to a specified URL with optional query parameters and extra parameters. ```APIDOC ## GET /url ### Description Shorthand for self.oauth_request(url, ‘get’) ### Method GET ### Endpoint /url ### Parameters #### Path Parameters - **url** (str) - Required - url to send get oauth request to #### Query Parameters - **params** (dict) - Optional - request parameter to get the service data - **kwargs** (dict) - Optional - extra params to send to request api ### Response #### Success Response (200) - **Response** (requests.Response) - Response of the request ``` -------------------------------- ### Account Setup and OAuth Flows Source: https://context7.com/o365/python-o365/llms.txt Demonstrates setting up an Account object for different OAuth2 authentication flows: authorization code, client credentials, and password flow. Use 'authorization' for interactive apps, 'credentials' for daemons, and 'password' for non-production scenarios. ```python from O365 import Account from O365 import FileSystemTokenBackend # --- Interactive / Authorization Code flow (opens browser URL) --- credentials = ('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET') token_backend = FileSystemTokenBackend(token_path='.', token_filename='o365_token.txt') account = Account(credentials, token_backend=token_backend) if not account.is_authenticated: # Starts interactive OAuth; prints a URL, waits for the redirected URL account.authenticate( requested_scopes=['basic', 'message_all', 'calendar_all', 'onedrive_all'] ) # account.username → 'user@example.com' once authenticated # --- Client Credentials (daemon / service account, no user interaction) --- account_cc = Account( credentials, auth_flow_type='credentials', tenant_id='YOUR_TENANT_ID', ) account_cc.authenticate() # silently acquires a token using client secret # --- Password flow (not recommended for production) --- account_pw = Account( ('YOUR_CLIENT_ID',), # single-element tuple for public flow auth_flow_type='password', tenant_id='YOUR_TENANT_ID', username='user@example.com', password='secret', ) pw_account.authenticate(requested_scopes=['basic', 'mailbox']) # --- Check authenticated usernames in the token backend --- print(account.get_authenticated_usernames()) # ['user@example.com'] # --- Switch between multiple users --- account.username = 'another_user@example.com' ``` -------------------------------- ### Get and Create Folders - Python o365 Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/mailbox.rst.txt Demonstrates how to retrieve a specific folder by name, fetch its child folders with a limit, and create a new child folder. ```python mailbox = account.mailbox() archive = mailbox.get_folder(folder_name='archive') # get a folder with 'archive' name child_folders = archive.get_folders(25) # get at most 25 child folders of 'archive' folder for folder in child_folders: print(folder.name, folder.parent_id) new_folder = archive.create_child_folder('George Best Quotes') ``` -------------------------------- ### Get NamedRange Range Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/excel.html Retrieves the Range instance associated with this named range. Makes a GET request to the '/range' endpoint. ```python def get_range(self): """Returns the Range instance this named range refers to""" url = self.build_url(self._endpoints.get("get_range")) response = self.session.get(url) if not response: return None return self.range_constructor( parent=self, **{self._cloud_data_key: response.json()} ) ``` -------------------------------- ### Create a Plan Instance Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/planner.rst.txt Instantiate a planner and create a new plan within a specified group. Requires an authenticated account and group object ID. ```python from O365 import Account account = Account(('app_id', 'app_pw')) planner = account.planner() plan = planner.create_plan( owner="group_object_id", title="Test Plan" ) ``` -------------------------------- ### get Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/connection.html A shorthand method for making a GET request using an OAuth authenticated session. It simplifies the process of retrieving data. ```APIDOC ## get ### Description Shorthand for self.oauth_request(url, 'get'). ### Method GET ### Endpoint [URL provided in the `url` parameter] ### Parameters #### Path Parameters None #### Query Parameters * **params** (dict) - Optional - Request parameters to get the service data. #### Request Body None ### Parameters * **url** (str) - Required - The URL to send the GET request to. * **params** (dict) - Optional - Dictionary of URL parameters to append to the request. * **kwargs** - Optional - Extra parameters to send to the request API. ### Return Value * **Response** (requests.Response) - The response object from the GET request. ``` -------------------------------- ### Initialize FileSystemTokenBackend Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/utils/token.rst.txt Use FileSystemTokenBackend to store tokens on the local file system. This requires specifying a path and filename for token storage. ```python from O365 import Account, FileSystemTokenBackend token_backend = FileSystemTokenBackend(token_path=token_path, token_filename=token_filename) account = Account(credentials=('my_client_id', 'my_client_secret'), token_backend=token_backend) ``` -------------------------------- ### Get TableRow Range Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/excel.html Retrieves the range object associated with the entire table row. Makes a GET request to the '/range' endpoint. ```python def get_range(self): """Gets the range object associated with the entire row""" url = self.build_url(self._endpoints.get("get_range")) response = self.session.get(url) if not response: return None ``` -------------------------------- ### Initialize Storage and List Drives Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/onedrive.rst.txt Initialize the Storage instance and retrieve a list of available drives or the default drive. This is the starting point for all storage operations. ```python account = Account(credentials=my_credentials) storage = account.storage() # here we get the storage instance that handles all the storage options. # list all the drives: drives = storage.get_drives() # get the default drive my_drive = storage.get_default_drive() # or get_drive('drive-id') ``` -------------------------------- ### Create and Manage Folders Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/tasks.rst.txt Shows how to create a new task folder, rename an existing folder, and retrieve all tasks within a specific folder. ```python #create a new folder new_folder = todo.new_folder('Defenders') #rename a folder folder = todo.get_folder(folder_name='Strikers') folder.name = 'Forwards' folder.update() #list current tasks task_list = folder.get_tasks() for task in task_list: print(task) print('') ``` -------------------------------- ### Webhook Notification Example Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/subscriptions.rst.txt This is an example of a webhook notification received when a subscription event occurs, such as a new message being created. The client state should be validated for accuracy. ```json { "value": [ { "subscriptionId": "548355f8-c2c0-47ae-aac7-3ad02b2dfdb12", "subscriptionExpirationDateTime": "2026-01-07T11:35:40.301594+00:00", "changeType": "created", "resource": "Users/12345678-a5c7-46da-8107-b25090a1ed66/Messages/=", "resourceData": { "@odata.type": "#Microsoft.Graph.Message", "@odata.id": "Users/12345678-a5c7-46da-8107-b25090a1ed66/Messages/=", "@odata.etag": "W/\"CQAAABYACCCoiRErLbiNRJDCFyMjq4khBBnH4N7A\"", "id": "=" }, "clientState": "abc123", "tenantId": "12345678-abcd-1234-abcd-1234567890ab" } ] } ``` -------------------------------- ### Sharepoint.__init__ Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/sharepoint.html Initializes the Sharepoint API component. ```APIDOC ## __init__ ### Description Initializes the Sharepoint API component. It requires either a parent Account object or a connection object. ### Method ```python def __init__(self, *, parent=None, con=None, **kwargs) ``` ### Parameters #### Parameters - **parent** (Account) - Optional - The parent Account object. - **con** (Connection) - Optional - The connection object to use if no parent is specified. - **protocol** (Protocol) - Optional - The protocol to use if no parent is specified (passed via kwargs). - **main_resource** (str) - Optional - A specific resource to use instead of the parent's resource (passed via kwargs). ``` -------------------------------- ### Configure Account with proxy server Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/account.rst.txt Set up proxy server details during Account instantiation or using the connection object. ```python # Option 1 account = Account(credentials=('my_client_id', 'my_client_secret'), proxy_server='myserver.com', proxy_port=8080, proxy_username='username', proxy_password='password) # Option 2 account = Account(credentials=('my_client_id', 'my_client_secret')) account.connection.set('myserver.com',8080,'username', 'password') ``` -------------------------------- ### Set Recurrence Range Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/calendar.html Configures the start and end conditions for event recurrence. If no start date is provided, it defaults to today. You can specify an end date or a number of occurrences. ```python def set_range(self, start=None, end=None, occurrences=None): """ Set the range of recurrence :param date start: Start date of repetition :param date end: End date of repetition :param int occurrences: no of occurrences """ if start is None: if self.__start_date is None: self.__start_date = dt.date.today() else: self.start_date = start if end: self.end_date = end elif occurrences: self.__occurrences = occurrences self._track_changes() ``` -------------------------------- ### Get Single Folder by Name - Python o365 Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/mailbox.rst.txt Use the folder name to search for a direct child folder. If the folder is nested, you must first get its parent folder. ```python mail_folder = mailbox.get_folder(folder_name='Todo') ``` ```python mail_folder = (mailbox.get_folder(folder_name='Inbox') .get_folder(folder_name='Todo')) ``` -------------------------------- ### Initialize Account and Access Groups Source: https://github.com/o365/python-o365/blob/master/docs/latest/usage/group.html Demonstrates how to initialize an O365 Account and access the groups functionality. Ensure you have the correct app ID and secret. ```python from O365 import Account account = Account(('app_id', 'app_pw')) groups = account.groups() ``` -------------------------------- ### Create Planner Instance Source: https://github.com/o365/python-o365/blob/master/docs/latest/usage/planner.html Instantiate the Planner object using an authenticated O365 Account. This is the entry point for all Planner-related operations. ```python from O365 import Account account = Account(('app_id', 'app_pw')) planner = account.planner() ``` -------------------------------- ### AWS S3 Backend Initialization Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/utils/token.html Initializes the AWS S3 token backend. Requires the boto3 package to be installed. Sets up the S3 client with the provided bucket name and filename. ```python def __init__(self, bucket_name, filename): """ Init Backend :param str bucket_name: Name of the S3 bucket :param str filename: Name of the S3 file """ try: import boto3 except ModuleNotFoundError as e: raise Exception( "Please install the boto3 package to use this token backend." ) from e super().__init__() #: S3 bucket name. |br| **Type:** str self.bucket_name = bucket_name #: S3 file name. |br| **Type:** str self.filename = filename self._client = boto3.client("s3") ``` -------------------------------- ### O365.drive.Image.dimensions Source: https://github.com/o365/python-o365/blob/master/docs/latest/genindex.html Gets the dimensions of an image. ```APIDOC ## O365.drive.Image.dimensions ### Description Gets the dimensions of an image. ### Method Not specified (assumed to be an attribute) ### Endpoint Not specified ### Parameters None specified ### Request Example None specified ### Response None specified ``` -------------------------------- ### Initialize PlanDetails in O365 Planner Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/planner.html Initializes a PlanDetails object. Requires either a parent Plan object or a connection object. Sets up object_id, shared_with, category_descriptions, and etag from cloud data. ```python def __init__(self, *, parent=None, con=None, **kwargs): """A Microsoft O365 plan details :param parent: parent object :type parent: Plan :param Connection con: connection to use if no parent specified :param Protocol protocol: protocol to use if no parent specified (kwargs) :param str main_resource: use this resource instead of parent resource (kwargs) """ if parent and con: raise ValueError("Need a parent or a connection but not both") self.con = parent.con if parent else con cloud_data = kwargs.get(self._cloud_data_key, {}) self.object_id = cloud_data.get("id") # Choose the main_resource passed in kwargs over parent main_resource main_resource = kwargs.pop("main_resource", None) or \ (getattr(parent, "main_resource", None) if parent else None) main_resource = "{}{}".format(main_resource, "") super().__init__( protocol=parent.protocol if parent else kwargs.get("protocol"), main_resource=main_resource, ) self.shared_with = cloud_data.get(self._cc("sharedWith"), "") self.category_descriptions = cloud_data.get( self._cc("categoryDescriptions"), "" ) self._etag = cloud_data.get("@odata.etag", "") ``` -------------------------------- ### Get Single Webhook Subscription Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/subscriptions.html Retrieves a specific webhook subscription by its ID using a GET request to the Microsoft Graph API. Returns the subscription details as a JSON dictionary or None if the subscription is not found or the response is empty. ```python def get_subscription( self, subscription_id: str, *, params: Optional[Mapping[str, object]] = None, **request_kwargs, ) -> Optional[dict]: """Retrieve a single webhook subscription by id.""" if not subscription_id: raise ValueError("subscription_id must be provided.") if params is not None and not isinstance(params, Mapping): raise ValueError("params must be a mapping if provided.") url = self._build_subscription_url(subscription_id) response = self.con.get(url, params=params, **request_kwargs) if not response: return None return response.json() ``` -------------------------------- ### Create and Manage Tasks Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/tasks.rst.txt Demonstrates how to get the default task folder, create a new task, set its subject and due date, save it, and mark it as completed. Naive datetimes are automatically converted to timezone-aware objects. ```python import datetime as dt # ... todo = account.tasks() #list current tasks folder = todo.get_default_folder() new_task = folder.new_task() # creates a new unsaved task new_task.subject = 'Send contract to George Best' new_task.due = dt.datetime(2020, 9, 25, 18, 30) new_task.save() #some time later.... new_task.mark_completed() new_task.save() # naive datetimes will automatically be converted to timezone aware datetime # objects using the local timezone detected or the protocol provided timezone # as with the Calendar functionality ``` -------------------------------- ### O365.drive.Photo.iso Source: https://github.com/o365/python-o365/blob/master/docs/latest/genindex.html Gets the ISO information for the photo. ```APIDOC ## O365.drive.Photo.iso ### Description Gets the ISO information for the photo. ### Attribute iso ``` -------------------------------- ### O365.excel.WorkSheet.get_range Source: https://github.com/o365/python-o365/blob/master/docs/latest/genindex.html Gets a specific range from a worksheet. ```APIDOC ## O365.excel.WorkSheet.get_range ### Description Retrieves a specific range from the worksheet, identified by its address or coordinates. ### Method Not specified (likely a Python method call) ### Endpoint Not applicable (Python library method) ### Parameters - **range_address** (str) - Required - The address of the range (e.g., 'A1:B10'). ### Request Example ```python # Example usage (assuming worksheet is an instance of O365.excel.WorkSheet) selected_range = worksheet.get_range('C1:D5') ``` ### Response Returns the Excel range object. ``` -------------------------------- ### Initialize Account with Requested Scopes Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/getting_started.rst.txt Use this when you need to specify the exact permissions your application requires from the user. The scopes are passed during account initialization. ```python from O365 import Account credentials = ('client_id', 'client_secret') requested_scopes = ['Mail.ReadWrite', 'Mail.Send'] account = Account(credentials, requested_scopes=requested_scopes) account.authenticate() ``` -------------------------------- ### O365.utils.utils.Query.get_order Source: https://github.com/o365/python-o365/blob/master/docs/latest/genindex.html Gets the ordering criteria for a query. ```APIDOC ## O365.utils.utils.Query.get_order ### Description Retrieves the ordering parameters that have been applied to the query. ### Method Not specified (likely a Python method call) ### Endpoint Not applicable (Python library method) ### Parameters None explicitly documented. ### Request Example ```python # Example usage (assuming query is an instance of O365.utils.utils.Query) order_by = query.get_order() ``` ### Response Returns the ordering information for the query. ``` -------------------------------- ### Working with Folders and Items Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/onedrive.rst.txt Illustrates how to get the root folder, special folders, and iterate through items within a folder, including checking item types and accessing metadata. ```APIDOC ## Working with Folders and Items ### Description This section explains how to access the root folder, specific special folders (like 'attachments'), and how to list and process items (files and folders) within a drive. ### Method ```python # Get the root folder root_folder = my_drive.get_root_folder() # Get a special folder (e.g., 'attachments') attachments_folder = my_drive.get_special_folder('attachments') # Iterate over items in a folder for item in root_folder.get_items(limit=25): if item.is_folder: # Process sub-folder items print(list(item.get_items(2))) # print the first two elements on this folder. elif item.is_file: # Process file metadata if item.is_photo: print(item.camera_model) # print some metadata of this photo elif item.is_image: print(item.dimensions) # print the image dimensions else: # Regular file print(item.mime_type) # print the mime type ``` ``` -------------------------------- ### O365.excel.Range.get_last_row Source: https://github.com/o365/python-o365/blob/master/docs/latest/genindex.html Gets the last row of a range. ```APIDOC ## O365.excel.Range.get_last_row ### Description Determines and returns the last row occupied by the range. ### Method Not specified (likely a Python method call) ### Endpoint Not applicable (Python library method) ### Parameters None explicitly documented. ### Request Example ```python # Example usage (assuming excel_range is an instance of O365.excel.Range) last_row_index = excel_range.get_last_row() ``` ### Response Returns the index or identifier of the last row. ``` -------------------------------- ### O365.excel.Range.get_last_column Source: https://github.com/o365/python-o365/blob/master/docs/latest/genindex.html Gets the last column of a range. ```APIDOC ## O365.excel.Range.get_last_column ### Description Determines and returns the last column occupied by the range. ### Method Not specified (likely a Python method call) ### Endpoint Not applicable (Python library method) ### Parameters None explicitly documented. ### Request Example ```python # Example usage (assuming excel_range is an instance of O365.excel.Range) last_column_index = excel_range.get_last_column() ``` ### Response Returns the index or identifier of the last column. ``` -------------------------------- ### BaseTokenBackend Initialization Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/utils/token.html Initializes the BaseTokenBackend, setting up the token cache and an optional cryptography manager. ```python def __init__(self): super().__init__() self._has_state_changed: bool = False #: Optional cryptography manager. |br| **Type:** CryptographyManagerType self.cryptography_manager: Optional[CryptographyManagerType] = None ``` -------------------------------- ### O365.groups.Group.description Source: https://github.com/o365/python-o365/blob/master/docs/latest/genindex.html Gets or sets the description of a group. ```APIDOC ## O365.groups.Group.description ### Description Gets or sets the description of a group. ### Method Not specified (assumed to be an attribute) ### Endpoint Not specified ### Parameters None specified ### Request Example None specified ### Response None specified ``` -------------------------------- ### O365.drive.DriveItem.description Source: https://github.com/o365/python-o365/blob/master/docs/latest/genindex.html Gets or sets the description of a DriveItem. ```APIDOC ## O365.drive.DriveItem.description ### Description Gets or sets the description of a DriveItem. ### Method Not specified (assumed to be an attribute) ### Endpoint Not specified ### Parameters None specified ### Request Example None specified ### Response None specified ``` -------------------------------- ### Initialize Environment Token Backend Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/utils/token.html Initializes the token backend to use an environment variable for storing the token. If no name is provided, it defaults to 'O365TOKEN'. ```python def __init__(self, token_env_name=None): """ Init Backend :param str token_env_name: the name of the environmental variable that will hold the token """ super().__init__() #: Name of the environment token (Default - `O365TOKEN`). |br| **Type:** str self.token_env_name = token_env_name if token_env_name else "O365TOKEN" ``` -------------------------------- ### O365.address_book.Contact.department Source: https://github.com/o365/python-o365/blob/master/docs/latest/genindex.html Gets or sets the department of a contact. ```APIDOC ## O365.address_book.Contact.department ### Description Gets or sets the department of a contact. ### Method Not specified (assumed to be a property) ### Endpoint Not specified ### Parameters None specified ### Request Example None specified ### Response None specified ``` -------------------------------- ### Table.entire_range Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/excel.html Get the range of the entire table. ```APIDOC ## GET /range ### Description Get the range of the entire table. ### Method GET ### Endpoint /range ``` -------------------------------- ### Table.get_row_index Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/excel.html Get the index of a row in the table. ```APIDOC ## GET /rows/itemAt ### Description Get the index of a row in the table. ### Method GET ### Endpoint /rows/itemAt ### Parameters #### Query Parameters - **index** (int) - Required - The index of the row. ``` -------------------------------- ### Working with Calendar instances Source: https://github.com/o365/python-o365/blob/master/docs/source/usage/calendar.rst Illustrates how to retrieve a specific calendar, create a query for events, update a calendar's name, and fetch events within a date range, including recurring events. It also shows how to respond to events by accepting or declining. ```APIDOC ## Working with Calendar instances This section demonstrates how to interact with specific `Calendar` instances. ### Usage ```python calendar = schedule.get_calendar(calendar_name='Birthdays') builder = calendar.new_query() calendar.name = 'Football players birthdays' calendar.update() start_q = builder.greater_equal('start', dt.datetime(2018, 5, 20)) end_q = builder.less_equal('start', dt.datetime(2018, 5, 24)) birthdays = calendar.get_events( include_recurring=True, # include_recurring=True will include repeated events on the result set. start_recurring=start_q, end_recurring=end_q, ) for event in birthdays: if event.subject == 'George Best Birthday': # He died in 2005... but we celebrate anyway! event.accept("I'll attend!") # send a response accepting else: event.decline("No way I'm coming, I'll be in Spain", send_response=False) # decline the event but don't send a response to the organizer ``` ``` -------------------------------- ### Working with Calendar instances Source: https://github.com/o365/python-o365/blob/master/docs/latest/usage/calendar.html Illustrates how to retrieve a specific calendar, update its name, query events within a date range, and respond to invitations. ```APIDOC ## Working with Calendar instances ### Description This snippet demonstrates how to work with specific `Calendar` instances. It covers retrieving a calendar by name, updating its properties, creating a query builder to filter events by date, fetching events (including recurring ones), and responding to event invitations by accepting or declining. ### Code Example ```python import datetime as dt # Assuming 'schedule' is an authenticated O365 Schedule object # calendar = schedule.get_calendar(calendar_name='Birthdays') # builder = calendar.new_query() # calendar.name = 'Football players birthdays' # calendar.update() # start_q = builder.greater_equal('start', dt.datetime(2018, 5, 20)) # end_q = builder.less_equal('start', dt.datetime(2018, 5, 24)) # birthdays = calendar.get_events( # include_recurring=True, # include_recurring=True will include repeated events on the result set. # start_recurring=start_q, # end_recurring=end_q, # ) # for event in birthdays: # if event.subject == 'George Best Birthday': # # He died in 2005... but we celebrate anyway! # event.accept("I'll attend!") # send a response accepting # else: # event.decline("No way I'm coming, I'll be in Spain", send_response=False) # decline the event but don't send a response to the organizer ``` ### Notes - `include_recurring=True`: When querying events with `include_recurring=True`, you must provide `start` and `end` parameters. These parameters filter the events' start datetime and do not apply operations like `greater_equal` or `less` to the query itself. - Shared Calendars: Be aware of potential issues when working with shared calendars as documented by Microsoft Graph. - Event Attachments: Attachments cannot be added at event creation. You must save the event first, then attach the message, and save again. ``` -------------------------------- ### Table.get_column_index Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/excel.html Get the index of a column in the table. ```APIDOC ## GET /columns/itemAt ### Description Get the index of a column in the table. ### Method GET ### Endpoint /columns/itemAt ### Parameters #### Query Parameters - **index** (int) - Required - The index of the column. ``` -------------------------------- ### Event Type Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/calendar.html Get the type of the event. ```APIDOC ## Event Type ### Description Get the type of the event. ### Getter Returns the type of the event. ### Type `str` ``` -------------------------------- ### Directory.__init__ Source: https://github.com/o365/python-o365/blob/master/docs/latest/_modules/O365/directory.html Initializes the Directory object, representing the Active Directory. ```APIDOC ## __init__ ### Description Represents the Active Directory. ### Parameters #### Path Parameters - **parent** (Account) - Optional - The parent object. - **con** (Connection) - Optional - The connection to use if no parent is specified. - **protocol** (Protocol) - Optional - The protocol to use if no parent is specified (kwargs). ``` -------------------------------- ### Category.object_id Source: https://github.com/o365/python-o365/blob/master/docs/latest/api/category.html Gets the object ID of the category. ```APIDOC ## Category.object_id ### Description Gets the object ID of the category. ``` -------------------------------- ### Modular Account Usage Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/account.rst.txt Demonstrates how to use specific components like Connection, MSGraphProtocol, Message, and MailBox directly, instead of relying solely on the main Account class. ```python from O365 import Connection, MSGraphProtocol from O365.message import Message from O365.mailbox import MailBox protocol = MSGraphProtocol() requested_scopes = ['...'] con = Connection(('client_id', 'client_secret'), requested_scopes=requested_scopes) message = Message(con=con, protocol=protocol) # ... mailbox = MailBox(con=con, protocol=protocol) message2 = Message(parent=mailbox) # message will inherit the connection and protocol from mailbox when using parent. ``` -------------------------------- ### Category.name Source: https://github.com/o365/python-o365/blob/master/docs/latest/api/category.html Gets or sets the name of the category. ```APIDOC ## Category.name ### Description Gets or sets the name of the category. ``` -------------------------------- ### Creating a New Task Folder Source: https://github.com/o365/python-o365/blob/master/docs/latest/usage/tasks.html Shows how to create a new task folder within the ToDo instance. ```python #create a new folder new_folder = todo.new_folder('Defenders') ``` -------------------------------- ### Category.color Source: https://github.com/o365/python-o365/blob/master/docs/latest/api/category.html Gets or sets the color of the category. ```APIDOC ## Category.color ### Description Gets or sets the color of the category. ``` -------------------------------- ### Configure Account with a main resource Source: https://github.com/o365/python-o365/blob/master/docs/latest/_sources/usage/account.rst.txt Specify a 'main_resource' when initializing the Account to target a specific mailbox or user. ```python from O365 import Account account = Account(credentials=('my_client_id', 'my_client_secret'), main_resource='shared_mail@example.com') ```