Retrieving mails from Exchange online using mailkit and authenticate as appl

87 views Asked by At

I'm trying to connect to Exchange Online with MailKit.

I authenticate as application (using appl.id and secret).

I already have the code to retrieve the token (using Graph API)

But how do I authenticate the MailKit imapClient using the token?

If I want to authenticate a HttpClient I use:

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

If I wanted to authenticate the MailKit imapClient using basic authentication it seems I could do:

using (var imapClient = new ImapClient())
{
      imapClient.Connect("outlook.office365.com", 993, SecureSocketOptions.SslOnConnect);
      imapClient.Authenticate("username", "password");
      ...
}
1

There are 1 answers

1
mainframe007 On

I have recently setup an application for this situation. The following is my code to connect to the exchange service using the appId, Client Secret, and TenantId. I also need to add you need to use the Microsoft Exchange web service to access the Microsoft Graph API (Where the app id and client secret was added in the cloud) because MailKit does not support it from what I know. You need to add the Microsoft.Exchange.WebServices dll from NuGet.

    //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>");