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


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:

    	var _task = Task.Run(() => { return GetAccessToken(); });
    	var tokenResult = _task.Result;
    	AccessToken = tokenResult.AccessToken;
    	MailClient = new Imap();
    	MailClient.Config = new ImapConfig() { AllowedTlsVersions = TlsSslVersion.TLS12 };
    	MailClient.Connect("", 993, SslSecurityMode.Implicit);
    	string initAuthInfo = GenerateSASLToken();
    	MailClient.Authenticate(initAuthInfo, ImapAuthenticationMethod.OAuth20);
    	if (MailClient.IsAuthenticated)
    		throw new Exception($"User authentication failed.");
    catch (Exception ex)
    	throw ex
    	if (MailClient.IsConnected)
    private async Task GetAccessToken()
    		var confidentialClientApplication = ConfidentialClientApplicationBuilder
    		var scopes = new string[] { "" };
    		return await confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync();
    	catch (Exception ex)
    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();



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