使用 mailkit 从 Exchange Online 检索邮件并以 appl 身份验证

问题描述 投票:0回答:1

我正在尝试使用 MailKit 连接到 Exchange Online。

我作为应用程序进行身份验证(使用 appl.id 和机密)。

我已经有了检索令牌的代码(使用 Graph API)

但是如何使用令牌对 MailKit imapClient 进行身份验证?

如果我想验证我使用的 HttpClient:

_HttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", AccessToken);

如果我想使用基本身份验证来验证 MailKit imapClient,我似乎可以这样做:

using (var imapClient = new ImapClient())
{
      imapClient.Connect("outlook.office365.com", 993, SecureSocketOptions.SslOnConnect);
      imapClient.Authenticate("username", "password");
      ...
}
c# mailkit exchange-online
1个回答
0
投票

我最近为这种情况设置了一个应用程序。以下是我使用 appId、Client Secret 和 TenantId 连接到交换服务的代码。我还需要补充一点,您需要使用 Microsoft Exchange Web 服务来访问 Microsoft Graph API(其中应用程序 ID 和客户端密钥已添加到云中),因为据我所知,MailKit 不支持它。您需要从 NuGet 添加 Microsoft.Exchange.WebServices dll。

    //Set up auth data
var cca = ConfidentialClientApplicationBuilder
    .Create("<ApplicationId>")
    .WithClientSecret("<ClientSecret>")
    .WithTenantId("<TenantId>")
    .Build();
var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
ExchangeService _ewsClient;
//Aquire Auth token
Task<AuthenticationResult> tsk = cca.AcquireTokenForClient(ewsScopes).ExecuteAsync();
tsk.Wait();
AuthenticationResult authResult = tsk.Result;

//Configure the ExchangeService with the access token.
_ewsClient = new ExchangeService();
_ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
_ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
_ewsClient.ImpersonatedUserId =
    new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "<EmailAddressOfAccount>");
//Include x-anchormailbox header
_ewsClient.HttpHeaders.Add("X-AnchorMailbox", "<EmailAddressOfAccount>");
© www.soinside.com 2019 - 2024. All rights reserved.