Subject: How to implement OAUTH 2.0 in Outlook using Ultimate Mail Date: 2022-12-09 08:53:06 From: Alok Agrawal Source: implement-oauth-2-0-outlook-using-ultimate-mail ---------------------------------------------------------------------- Hi I'm trying to authenticate use OAUTH2 token based authentication for Outlook but not able to get authenticated. Whenever Authenticate is called using a token [**Authenticate(string Token, ImapAuthenticationMethod ImapAuthenticationMethod.OAuth2)**] it throws the following error ComponentPro.Net.Mail.ImapException: **AUTHENTICATE failed (NO).** at ComponentPro.Net.Mail.Imap.c_47d8efdd(String , ImapResponse , Boolean ) at ComponentPro.Net.Mail.Imap.c_56b07853(String ) at ComponentPro.Net.Mail.Imap.c_5e2380a4(String , String , ImapAuthenticationMethod , c_e ) at ComponentPro.Net.Mail.Imap.c_c224912a(String , String , ImapAuthenticationMethod ) at ComponentPro.Net.Mail.Imap.Authenticate(String token, ImapAuthenticationMethod method) I'm using the following code: try { var _task = Task.Run(() => { return GetAccessToken(); }); _task.Wait(); var tokenResult = _task.Result; AccessToken = tokenResult.AccessToken; MailClient = new Imap(); MailClient.Config = new ImapConfig() { AllowedTlsVersions = TlsSslVersion.TLS12 }; MailClient.Connect("outlook.office365.com", 993, SslSecurityMode.Implicit); string initAuthInfo = GenerateSASLToken(); MailClient.Authenticate(initAuthInfo, ImapAuthenticationMethod.OAuth20); if (MailClient.IsAuthenticated) ReadMailbox(); else throw new Exception($"User authentication failed."); } catch (Exception ex) { throw ex } finally { if (MailClient.IsConnected) MailClient.Disconnect(); } private async TaskGetAccessToken() { try { var confidentialClientApplication = ConfidentialClientApplicationBuilder .Create(ClientId) .WithClientSecret(ClientSecret) .WithTenantId(TenantId) .Build(); var scopes = new string[] { "https://outlook.office365.com/.default" }; return await confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync(); } catch (Exception ex) { throw; } } private string GenerateSASLToken() { string authData = string.Format("user={0}{1}auth=Bearer {2}{1}{1}", UserName, '\x1', AccessToken); return Convert.ToBase64String(Encoding.ASCII.GetBytes(authData)); } If I use the same credential (SASL token) and call the **SendCommand** the response received is **OK AUTHENTICATE completed.** MailClient.SendCommand("AUTHENTICATE", new object[2] { "XOAUTH2", initAuthInfo }); ImapResponse _response = MailClient.ReadResponse(); Regards ---------------------------------------------------------------------- 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