I need to read a certain email but a different account.
The first example works
string applicationClientID = "aaaaaaaaaaaaaaaaaaaa";
string directoryTenantID = "dddddddddddddddddd";
string secretID = "sssssssssssssssssssssss";
//Example 01: OK
string email = "[email protected]"; //WORKS: account
that will read the email = [email protected]
//Example 02: Error need to read emailRead@outlook with account [email protected]
string email = "[email protected]"; // DOES NOT WORK:
account that has permission to read email:
[email protected]
var credentials = new ClientSecretCredential(
directoryTenantID, applicationClientID, secretID,
new TokenCredentialOptions { AuthorityHost =
AzureAuthorityHosts.AzurePublicCloud });
GraphServiceClient graphServiceClient = new
GraphServiceClient(credentials);
var inboxMessages = await graphServiceClient
.Users[email]
.MailFolders["inbox"]
.messages
.Request()
.Expand("attachments")
.Top(20)
.GetAsync();
//I get the following message: Message: Access to OData is disabled.
CodePudding user response:
I think your code should work, except messages
should be Messages
. Here's my test result.
Firstly, when we want to check emails for a specific email account, we need to use client credential flow just like you used.
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenant_name.onmicrosoft.com";
var clientId = "azure_ad_appid";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var inboxMessages = await graphClient
.Users["[email protected]"]
.MailFolders["inbox"]
.Messages
.Request()
.Expand("attachments")
.Top(20)
.GetAsync();
CodePudding user response:
- The problem might be with the Application Access Policy.
- Generally, if you use Application Permissions in OAuth for Microsoft 365, you can use the following instructions to further narrow down the permissions: Limiting application permissions to specific Exchange Online mailboxes
- Permissions for Microsoft Graph applications (You might not require all of these):
Mail.Read
Mail.ReadBasic
Mail.ReadBasic.All
Mail.ReadWrite
Mail.Send
MailboxSettings.Read
MailboxSettings.ReadWrite
Calendars.Read
Calendars.ReadWrite
Contacts.Read
Contacts.ReadWrite - When an API call is refused access due to a specified application access policy, you may see the following error.
{
"error": {
"code": "ErrorAccessDenied",
"message": "Access to OData is disabled.",
"innerError": {
"request-id": "<request GUID is here>",
"date": "<UTC date format here>"
}
}
- If your app's Microsoft Graph API calls return this error, check with the organization's Exchange Online administrator to make sure your app has authorization to access the mailbox resource.
- Helpful Powershell commands :
Test-ApplicationAccessPolicy
Get-ApplicationAccessPolicy
New-ApplicationAccessPolicy
Remove-ApplicationAccessPolicy
Set-ApplicationAccessPolicy