-
Notifications
You must be signed in to change notification settings - Fork 423
Access Shared Mailboxes
Wombatpm edited this page Apr 26, 2023
·
2 revisions
This wasn't covered in the examples when I needed it, so I writing an entry for the next person. Below is the init function for a class I wrote. When I needed to deal with Shared Mailboxes I was stuck in how to access them. The solution required four changes
- Create an access token for an account that has access to the shared mailbox. You can't connect to a shared mailbox directly.
- Your scopes need to be expanded to include Shared permission. i.e. ReadWrite.Shared
- Your API permissions for your app in Azure must grant the Shared permissions
- You need to include the main_resource=[email protected] keyword in you initial call to Account
def __init__(self, app_data: ApplicationData):
"""Perform initialization steps"""
credentials = (app_data.app_id, app_data.secret)
# the default protocol will be Microsoft Graph
# the default authentication method will be "on behalf of a user"
self.scopes = [
"https://graph.microsoft.com/Mail.ReadWrite",
"https://graph.microsoft.com/Mail.Send",
"https://graph.microsoft.com/Mail.ReadWrite.Shared",
"https://graph.microsoft.com/Mail.Send.Shared",
"offline_access",
]
# Set up token storage and retrieval
token_backend = FileSystemTokenBackend(
token_path=app_data.tokenpath, token_filename=app_data.token
)
# Set up Account connection
self.account = Account(
credentials,
main_resource=app_data.main_resource,
tenant_id=app_data.tenant,
auth_flow_type="authorization",
scopes=self.scopes,
token_backend=token_backend,
)
# Check status. Is_authenticated will load token and request a refresh, if that fails
# the account is authenticated again and the user has to grant permissions.
if not self.account.is_authenticated:
if self.account.authenticate():
print("Authenticated!")
# This forces the generation of a refresh token which is good for 90 days
self.account.connection.refresh_token()
# Connect to the mailbox, then to the inbox folder.
self.count = 0
self.mailbox = self.account.mailbox()