I’m new to graph API and I’m looking for help in solving a problem I’ve run into. I have an app registered at Azure with given permission User.Read
and Mail.Read
and have tried following different tutorials for reading an users email. However, the mailbox I’m trying to access is not the mailbox of the signed in user as seem to be the assumption in the tutorials, but an external mail account. How can I grant access to the application to access the external email’s mailbox without it being the signed in user? Is this even possible? The external email is added as a member of the group the app belongs to in Azure.
Following documentation from Microsoft I’ve tried using this for reading the email
from msgraph import GraphServiceClient
from msgraph.generated.users.item.messages.messages_request_builder import MessagesRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
scopes = ['User.Read']
# Multi-tenant apps can use "common",
# single-tenant apps must use the tenant ID from the Azure portal
tenant_id = 'common'
# Values from app registration
client_id = 'YOUR_CLIENT_ID'
# User name and password
username = '[email protected]'
password = 'Password1!'
# azure.identity
credential = UsernamePasswordCredential(
tenant_id=tenant_id,
client_id=client_id,
username=username,
password=password)
graph_client = GraphServiceClient(credential, scopes)
query_params = MessagesRequestBuilder.MessagesRequestBuilderGetQueryParameters(
select = ["sender","subject"],
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.me.messages.get(request_configuration = request_configuration)
But I don’t get anything out of this. I’ve also tried with msal and tokens
app = msal.ConfidentialClientApplication(
client_id=CLIENT_ID,
client_credential=CLIENT_SECRET,
authority=AUTHORITY)
result = None
result = app.acquire_token_silent(SCOPE, account=None)
if not result:
print("No suitable token exists in cache. Let's get a new one from Azure Active Directory.")
result = app.acquire_token_for_client(scopes=SCOPE)
if "access_token" in result:
# userID taken from Azure
endpoint = f'https://graph.microsoft.com/v1.0/users/{userId}/messages$select=sender,subject'
r = requests.get(endpoint,
headers={'Authorization': 'Bearer ' + result['access_token']})
if r.ok:
print('Retrieved emails successfully')
data = r.json()
for email in data['value']:
print(email['subject'] + ' (' + email['sender']
['emailAddress']['name'] + ')')
else:
print(r.json())
This gives me {‘error’: {‘code’: ‘ErrorAccessDenied’, ‘message’: ‘Access is denied. Check credentials and try again.’}}.
1