Mailkit connect to Office365 programmatically

Viewed 1330

I need to get emails from my Office365 account programmatically (C#). I decided to use Mailkit and to create an application password on Azure portal. I registered a new app, set its Redirect Uri and gave it some permissions:

Permissions

I then created a client secret to access the account without user interaction.

Now, here is my code:

var opt = new ConfidentialClientApplicationOptions()
{
    ClientId = "xxx_clientid",
    TenantId = "xx_tenant_id",
    ClientSecret = "xxx_client_secret_value",
    RedirectUri = "http://localhost",
};

var scopes = new string[] {
    "email",
    "offline_access",
    "https://outlook.office.com/IMAP.AccessAsUser.All", // Only needed for IMAP
    //"https://outlook.office.com/POP.AccessAsUser.All",  // Only needed for POP
    //"https://outlook.office.com/SMTP.Send", // Only needed for SMTP
};

var app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(opt).Build();
var authToken = await app.AcquireTokenForClient(scopes).ExecuteAsync(); // <--- Exception
var oauth2 = new SaslMechanismOAuth2(authToken.Account.Username, authToken.AccessToken);

using (var client = new ImapClient(new ProtocolLogger("imapLog.txt")))
{
    client.Connect("outlook.office365.com", 993, SecureSocketOptions.SslOnConnect);
    //client.AuthenticationMechanisms.Remove("XOAUTH2");
    client.Authenticate(oauth2);
    var inbox = client.Inbox;
    inbox.Open(MailKit.FolderAccess.ReadOnly);
    Console.WriteLine("Total messages: {0}", inbox.Count);
    Console.WriteLine("Recent messages: {0}", inbox.Recent);
    client.Disconnect(true);
}

Running the code I get this exception: Microsoft.Identity.Client.MsalServiceException: 'AADSTS70011: The provided request must include a 'scope' input parameter. The provided value for the input parameter 'scope' is not valid. The scope email offline_access https://outlook.office.com/IMAP.AccessAsUser.All is not valid.

I tried following the guide found on GitHub: Using OAuth2 With Exchange

The problem is that I need to use an app password instead.

0 Answers
Related