Microsoft Graph - GraphServiceClient 使用另一个帐户读取电子邮件

Microsoft Graph - GraphServiceClient read email with another account

我需要阅读某封电子邮件但不同的帐户。

第一个示例有效

        string applicationClientID = "aaaaaaaaaaaaaaaaaaaa";
        string directoryTenantID = "dddddddddddddddddd";
        string secretID = "sssssssssssssssssssssss";

//例01:OK

        string email = "emailRead@outlook.com"; //WORKS: account 
        that will read the email = emailRead@outlook.com

//示例02:错误需要读取emailRead@outlook with account countService@outlook.com

        string email = "emailRead@outlook.com"; // DOES NOT WORK: 
        account that has permission to read email:  
        countService@outlook.com

        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();

//我收到以下消息:消息:已禁用对 OData 的访问。

我认为你的代码应该可以工作,除了 messages 应该是 Messages。这是我的测试结果。

首先,当我们要检查特定电子邮件帐户的电子邮件时,我们需要像您使用的那样使用客户端凭据流。

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["tinywang@hanxia.onmicrosoft.com"]
                        .MailFolders["inbox"]
                        .Messages
                        .Request()
                        .Expand("attachments")
                        .Top(20)
                        .GetAsync();
  • 问题可能出在应用程序访问策略上。
  • 一般情况下,如果您在 Microsoft 365 的 OAuth 中使用应用程序权限,您可以使用以下说明进一步缩小权限范围: Limiting application permissions to specific Exchange Online mailboxes
  • Microsoft Graph 应用程序的权限(您可能不需要所有这些):
    Mail.Read
    Mail.Read基本
    Mail.Read基本.全部
    Mail.Read写
    Mail.Send
    MailboxSettings.Read
    MailboxSettings.Read写入
    Calendars.Read
    Calendars.Read写
    Contacts.Read
    Contacts.Read写
  • 当 API 调用因指定的应用程序访问策略而被拒绝访问时,您可能会看到以下错误。
{
"error": {
    "code": "ErrorAccessDenied",
    "message": "Access to OData is disabled.",
    "innerError": {
        "request-id": "<request GUID is here>",
        "date": "<UTC date format here>"
    }
}

  • 如果您的应用程序的 Microsoft Graph API 调用 return 此错误,请与组织的 Exchange Online 管理员联系以确保您的应用程序有权访问邮箱资源。
  • 有用的 Powershell 命令:
    Test-ApplicationAccessPolicy
    Get-ApplicationAccessPolicy
    New-ApplicationAccessPolicy
    Remove-ApplicationAccessPolicy
    Set-ApplicationAccessPolicy