我想在 .net core 环境中阅读连接到我的 Azure 帐户的 Office 365 电子邮件。当我尝试访问 Azure 上的应用程序并使用以下代码阅读我的电子邮件时,出现“身份验证失败”错误。我将在下面的申请中向您授予我的权限。你能帮我看看问题出在哪里吗? API权限: Microsoft Graph: User.Read(委托)、IMAP.AccessAsUser.All(委托) Office 365 Exchange Online: IMAP.AccessAsApp(应用程序)
我的代码:
public async Task<List<ReceivedEMails>> ReadEmailsAsync()
{
var emailMessages = new List<ReceivedEMails>();
try
{
// OAuth2 configuration
var clientId = _configuration["EmailSettings:ClientId"];
var tenantId = _configuration["EmailSettings:TenantId"];
var clientSecret = _configuration["EmailSettings:ClientSecret"];
var userEmail = _configuration["EmailSettings:EmailAddress"];
var scope = new string[] { "https://outlook.office.com/.default" };
// Get Access Token
var cca = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}/v2.0"))
.Build();
var result = await cca.AcquireTokenForClient(scope).ExecuteAsync();
// Connect to IMAP server
using (var client = new MailKit.Net.Imap.ImapClient())
{
await client.ConnectAsync("outlook.office365.com", 993, true);
await client.AuthenticateAsync(new SaslMechanismOAuth2(userEmail, result.AccessToken)); //error:authentication failed.
// Select inbox
await client.Inbox.OpenAsync(FolderAccess.ReadOnly);
var items = await client.Inbox.FetchAsync(0, -1, MessageSummaryItems.Full | MessageSummaryItems.UniqueId);
foreach (var item in items)
{
var email = client.Inbox.GetMessage(item.UniqueId);
emailMessages.Add(new ReceivedEMails
{
EmailCode = email.MessageId,
EmailSubject = email.Subject,
EmailSender = email.From.Mailboxes.FirstOrDefault()?.Address,
EmailContent = email.TextBody,
CreatedDate = email.Date.DateTime
});
}
await client.DisconnectAsync(true);
}
}
catch (Exception ex)
{
throw new InvalidOperationException("Failed to read emails.", ex);
}
return emailMessages;
}
我想在 .net core 环境中阅读我的 Outlook 帐户中的电子邮件。我收到的错误是“身份验证失败”
Outlook Mail REST API 现已弃用,建议迁移现有应用程序以使用 Microsoft Graph。
2020 年 11 月 17 日宣布,Outlook REST API 2.0 版 已被弃用。 v2.0 REST 端点将完全 于 2022 年 11 月退役,v2.0 文档将在 不久后被删除。迁移现有应用程序以使用 Microsoft 图形。查看比较以开始迁移。
当使用Graph Api为特定用户列出消息时,根据OP的代码片段
var scope = new string[] { "https://outlook.office.com/.default" };
,恐怕OP正在尝试使用应用程序API权限,因此我们至少应该拥有权限Application: Mail.ReadBasic.All
并添加管理员同意。
然后我们可以使用客户端凭证流 + 此 api 的 Graph SDK 如下所示:
using Microsoft.Graph;
using Azure.Identity;
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenant_name.onmicrosoft.com";
var clientId = "aad_app_id";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var result = await graphClient.Users["{user-id}"].MailFolders["{mailFolder-id}"].Messages.GetAsync();