How to use Mailkit with OAuth2 in an ASP.NET MVC application on Azure AD?

99 Views Asked by At

My situation is an ASP.NET MVC application that need to send emails. My email is Office 365

I tried these steps https://github.com/jstedfast/MailKit/blob/master/ExchangeOAuth2.md

On Azure AD as permission, I have Microsoft Graph and Microsoft Exchange Online.

How configure the permissions on AD for that work with mailkit?

Thanks in advance

1

There are 1 best solutions below

0
Naveen Sharma On

Configure the below API permissions on Azure AD to authenticate mailkit:

Go to Azure AD application -> Add a permission -> APIs my organization uses -> Office 365 Exchange Online

enter image description here

Assign application and delegated API permissions based on your application:

enter image description here

And add grant access to the user:

Add-MailboxPermission -Identity "[email protected]" -User ServicePrincipalID -AccessRights FullAccess

Make use of below code to authenticate:

var confidentialClientApplication = ConfidentialClientApplicationBuilder.Create (clientId)
    .WithAuthority ($"https://login.microsoftonline.com/{tenantId}/v2.0")
    .WithCertificate (certificate) // or .WithClientSecret (clientSecret)
    .Build ();
 
var scopes = new string[] {
    // For IMAP and POP3, use the following scope
    "https://ps.outlook.com/.default"

    // For SMTP, use the following scope
    // "https://outlook.office365.com/.default"
};

var authToken = await confidentialClientApplication.AcquireTokenForClient (scopes).ExecuteAsync ();
var oauth2 = new SaslMechanismOAuth2 (accountEmailAddress, authToken.AccessToken);

using (var client = new ImapClient ()) {
    await client.ConnectAsync ("outlook.office365.com", 993, SecureSocketOptions.SslOnConnect);
    await client.AuthenticateAsync (oauth2);
    await client.DisconnectAsync (true);
}

Reference:

MailKit/ExchangeOAuth2.md at master · jstedfast/MailKit · GitHub