无法使用 Microsoft.Graph 发送电子邮件

Unable to send email using Microsoft.Graph

我正在尝试使用 Microsoft.Graph API 发送电子邮件,但是我收到一条错误消息,指出“请求的用户无效”。我能够很好地获得访问令牌,但是我永远无法发送电子邮件。

我试过 graphClient.Me.SendEmail 没用。我试图在应用程序上创建另一个用户,但没有成功。我试过管理员邮箱发送邮件,但没有成功。

var ccaOptions = new ConfidentialClientApplicationOptions
{
    ClientId = "my client id",
    TenantId = "my tenant id",
    ClientSecret = "my client secret",
    RedirectUri = "temp",

};

var cca = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(ccaOptions).Build();

var scopes = new string[]
{
    "https://graph.microsoft.com/.default"
};

var authResult = cca.AcquireTokenForClient(scopes).ExecuteAsync().Result;
string accessToken = authResult.AccessToken;
ClientCredentialProvider authProvider = new ClientCredentialProvider(cca);
GraphServiceClient graphClient = new GraphServiceClient(authProvider);

await graphClient.Users["my admin email"]
                .SendMail(message, null)
                .Request()
                .PostAsync();

以下是我作为管理员授予的权限。

对于这个问题,有两点你需要知道:

1. 您在代码中使用了客户端凭证流,因此访问令牌不包含任何用户身份。所以当你使用graphClient.Me.SendEmail时,它并不知道Me是谁。如果要使用graphClient.Me.SendEmail,则需要使用username/password

2.我在自己这边测试,重现了错误The requested user is invalid。当我们使用电子邮件地址(不在当前租户中)时,它会显示此错误消息。我们可以在您的代码中使用像 xxx@xxx.onmicrosoft.com 这样的电子邮件地址来发送电子邮件。我们不能使用任何其他电子邮件地址发送电子邮件,即使此电子邮件已添加到具有全局管理员角色的 Azure AD 中。当您在代码中使用 email xxx@xxx.onmicrosoft.com 发送电子邮件时,您可能会遇到错误 MailboxNotEnabledForRESTAPI Message: REST API is not yet supported for this mailbox. 这意味着该电子邮件没有 o365 许可证。您需要 assign 此用户的 o365 许可。