Use IMAP with ModernAuthentication

Hi Team,

I have a worry to use ModernAuthentication with Aspose.Email.
I register my application in azure directory as a “delegate authentication”
I have settings for the authentication :

client_id = “client-id-from-registration”,
tenant_id = “tenant-id-from-registration”,
scopes = “Sign in to Outlook

To retrieve the token, I wrote thing like this :

private readonly IPublicClientApplication _clientApplication;

_clientApplication = PublicClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantId)
.WithRedirectUri(“http://localhost”)
.Build();

var result = await _confidentialClientApplication.AcquireTokenByUsernamePassword(_scopes, “email”, “pwd”))
.ExecuteAsync();

where email and pwd are credentials for my mail box.

The system generates the token, but if I use the generated token like this ;

using ImapClient client = new()
{
Host = host,
Username = username,
Password = result.AccessToken,
Port = port,
SecurityOptions = useSsl ? SecurityOptions.SSLAuto : SecurityOptions.None,
Timeout = 30000
};

        bool isValidCredentials = false;

        try
        {
            isValidCredentials = await client.ValidateCredentialsAsync();
        }
        catch (Exception ex)
        {
              throw ex;               
        }

        return isValidCredentials;

The method always pass through Exception. And this exception said only : “connect failure”

If I change AcquireTokenByUsernamePassword with AcquireTokenInteractive, the token isn’t generated with a message like : client-secret is required.

I don’t understand why things are not working… Any ideas ?

Hi @JEREMY_JANIS,

We understand your concern. Please see the project that shows an example of using modern authentication. ModernAuthenticationImapSmtp.zip (3.9 KB)

I hope it helps. Please share your feedback after trying.

Hi @margarita.samodurova,

Thanks a lot, this helped me a lot :slight_smile:
I was able to connect to my professional account with the access_token and retrieve my emails with aspose

Hi @JEREMY_JANIS,

I’m happy it worked.

If you ever have any other questions, please, feel free to ask.