Subject: How to authenticate IMAP client with Office 365 using Oauth2 Date: 2022-10-14 21:28:18 From: Ciprian Malaia Source: authenticate-imap-client-office-365-using-oauth2 ---------------------------------------------------------------------- I'm trying to get our IMAP client, that has been using username and password authentication, to use OAuth2.0 when connecting to Office 365. I've been looking at your example on how to use OAuth 2.0 with Gmail - [How to implement OAUTH 2.0 in Gmail using Ultimate Mail][1]. Also, I have been following the steps on [this][2] Microsoft page for obtaining the access token with client credentials flow. I can obtain the access token ok, I then convert it to SASL XOAUTH2 format, but when trying to authenticate the IMAP client it always fails with error "AUTHENTICATE failed (NO)" Here is my code: var accessToken = TokenService.GetToken(TenantId, ClientId, ClientSecret); if (string.IsNullOrEmpty(accessToken)) { throw new ApplicationException("Failed to retrieve access token."); } var rawSaslToken = string.Format("user={0}{2}auth=Bearer {1}{2}{2}", UserEmail, accessToken, '\x1'); var saslToken = Convert.ToBase64String(Encoding.ASCII.GetBytes(rawSaslToken)); var imapClient = new Imap(); imapClient.Connect("outlook.office365.com", 993, SslSecurityMode.Implicit); imapClient.Authenticate(saslToken, ImapAuthenticationMethod.OAuth20); I use the scope "https://outlook.office365.com/.default" when obtaining the access token, as per Microsoft page instructions. I added API permission "IMAP.AccessAsApp" and granted Admin consent. I've also configured my Azure app to have access to the user mailbox. Any help would be appreciated. [1]: https://www.componentpro.com/blog/details/implement-oauth-2-0-gmail-using-ultimate-mail [2]: https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth#register-your-application ---------------------------------------------------------------------- Note: This question has been asked on the Q&A forum of Thang Dang's fraudulent ComponentPro brand If you purchased anything from ComponentPro, you have been scammed. Contact the payment processor who sold you the license and ask for your money back. Back to ComponentPro Q&A Forum Index