Nuget MailKit and Microsoft.Identity.Client. code tested.
using MailKit.Net.Pop3;
using MailKit.Security;
using Microsoft.Identity.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MailKitTester
{
class Program
{
public static string getMSOauth2Token(string clientId, string clientSecret, string tenantId)
{
string token;
string authority = "https://login.microsoftonline.com/" + tenantId;
const string scope = "https://outlook.office365.com/.default";
IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(authority)
.Build();
string[] scopes = new string[]
{
scope,
"offline_access"
};
token = app.AcquireTokenForClient(scopes).ExecuteAsync().Result.AccessToken;
return token;
}
static void Main(string[] args)
{
string token = getMSOauth2Token("********", "********", "**********");
using (var client = new Pop3Client())
{
client.Connect("Outlook.office365.com", 995, SecureSocketOptions.SslOnConnect);
if (client.AuthenticationMechanisms.Contains("OAUTHBEARER") || client.AuthenticationMechanisms.Contains("XOAUTH2"))
{
var oauth2 = new SaslMechanismOAuth2("email address removed for privacy reasons", token);
client.Authenticate(oauth2);
}
var msgCount = client.Count;
client.Disconnect(true);
}
}
}
}