Free Support Forum - aspose.com

Fetching mails through IMAP gets errors

Hi,

I am using Aspose to fetch mails iteratively after a pool interval of >= 30 seconds for an email account using Microsoft Oauth authentication. And below is the code to define the mail settings

protected override async Task OnGetClientAsync()
{

        try
        {
            var client = new ImapClient(Settings.Host, Settings.Port)
            {
                SecurityOptions = Settings.UseSsl ? SecurityOptions.SSLAuto : SecurityOptions.Auto,
                UseAuthentication = true,
                UseDefaultCredentials = false
            };

            //Set timeout.
            if (Settings.Timeout != null)
            {
                client.Timeout = Settings.Timeout.Value;
            }

            switch (Settings.Authentication)
            {
                case BasicAuthentication auth:
                    client.Username = auth.GetFullUsername();
                    client.Password = auth.Password;
                    client.UseAuthentication = !auth.UseOpenRelay;
                    break;
                case GoogleOAuthAuthentication auth:
                    client.Username = auth.Username;
                    client.AccessToken = await GoogleOAuthAuthentication.CreateAccessTokenAsync(auth).ConfigureAwait(false);
                    break;
                case MicrosoftOAuthAuthentication auth:
                    ITokenProvider tokenProvider = new AzureTokenProvider(auth.TenantId, auth.AppId, auth.Username, auth.Secret, auth.Scopes.ToArray());
                    client.Username = auth.Username;
                    client.TokenProvider = tokenProvider;
                    break;
                default:
                    throw new NotSupportedException($"Authentication of type {Settings.Authentication?.GetType().Name ?? "undefined"} is not supported for {nameof(ImapMailClient)}.");
            }

            // Select the correct folder from the settings.
            client.SelectFolder(Settings.FolderName);

            // Return the client.
            WriteLog(BaseLogType.Success, $"{nameof(ImapMailClient)} successfully created.");
            return client;
        }
        catch (Exception ex)
        {
            WriteLog(BaseLogType.Error, $"An error occured while creating {nameof(ImapMailClient)}: {ex}");
            throw;
        }
    }

Here the code line " client.SelectFolder(Settings.FolderName); " throws the exception below

/**********************************************************************/

An error occured while creating ImapMailClient: TimeoutException: The operation ‘Connect’ terminated. Timeout ‘100000’ has been reached.
at #=zKsMZoQj7V8171J04kxP4KAui0J22.#=zxd769ac=(IAsyncResult #=zFBSKbgk=)
at #=zKsMZoQj7V8171J04kxP4KAui0J22.#=zoIFp4rM=()
at #=zCnpIhNu9ggZ6Em3x4Onn$N0iPaWQ.#=zPhsfbaLMbyEb(Int32 #=zDtVxeBo=, #=zfCU2qSy0a2_ihcIx82G4kNbg87UQ3qUIXQ== #=zzrMQxkc=)
at #=zKsMZoQj7V8171J04kxP4KAui0J22.#=zc20PShB5S7PN()
at #=zw$jR9sEqiBJWrRnUtmyNZMOwUM11wCi7dPd9oat6w$51.#=zc20PShB5S7PN()
at #=z4QXz97stZN24l4rqXV3xqGGnA9czZjxGMOdxPeiBI$1K…ctor(EmailClient #=zVtlkI7c=, String #=z9AND5dU=, Nullable1 #=zdYSWcIIDDBvN) at Aspose.Email.Clients.Imap.ImapClient.BeginSelectFolder(IConnection connection, String folderName, Nullable1 readOnly, AsyncCallback callback, Object state)
at Aspose.Email.Clients.Imap.ImapClient.SelectFolder(IConnection connection, String folderName, Nullable1 readOnly) at Aspose.Email.Clients.Imap.ImapClient.SelectFolder(String folderName) at Onguard.Email.Clients.ImapMailClient.<OnGetClientAsync>d__7.MoveNext() 2021-03-18 5:29:25 PM Error : An error occured while connecting ImapClient: TimeoutException: The operation 'Connect' terminated. Timeout '100000' has been reached. at #=zKsMZoQj7V8171J04kxP4KAui0J22.#=zxd769ac=(IAsyncResult #=zFBSKbgk=) at #=zKsMZoQj7V8171J04kxP4KAui0J22.#=zoIFp4rM=() at #=zCnpIhNu9ggZ6Em3x4Onn$N0iPaWQ.#=zPhsfbaLMbyEb(Int32 #=zDtVxeBo=, #=zfCU2qSy0a2_ihcIx82G4kNbg87UQ3qUIXQ== #=zzrMQxkc=) at #=zKsMZoQj7V8171J04kxP4KAui0J22.#=zc20PShB5S7PN() at #=zw$jR9sEqiBJWrRnUtmyNZMOwUM11wCi7dPd9oat6w$51.#=zc20PShB5S7PN() at #=z4QXz97stZN24l4rqXV3xqGGnA9czZjxGMOdxPeiBI$1K..ctor(EmailClient #=zVtlkI7c=, String #=z9AND5dU=, Nullable1 #=zdYSWcIIDDBvN)
at Aspose.Email.Clients.Imap.ImapClient.BeginSelectFolder(IConnection connection, String folderName, Nullable1 readOnly, AsyncCallback callback, Object state) at Aspose.Email.Clients.Imap.ImapClient.SelectFolder(IConnection connection, String folderName, Nullable1 readOnly)
at Aspose.Email.Clients.Imap.ImapClient.SelectFolder(String folderName)
at Onguard.Email.Clients.ImapMailClient.d__7.MoveNext()
— End of stack trace from previous location where exception was thrown —
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Onguard.Email.Clients.MailClient2.<OnGetClientAsyncInternal>d__7.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Onguard.Email.Clients.MailClient2.get_Client()
at Onguard.Email.Clients.ImapMailClient.ConnectAsync()

/**********************************************************************/

And sometimes the code below for creating the connection

    public override Task<bool> ConnectAsync()
    {
        try
        {
            if (Client?.ConnectionState == ConnectionState.Open)
            {
                return Task.FromResult(true);
            }
            return Task.FromResult(Client.CreateConnection() != null);
        }
        catch (Exception ex)
        {
            WriteLog(BaseLogType.Error, $"An error occured while connecting {nameof(ImapClient)}: {ex}");
            return Task.FromResult(false);
        }
    }

too throws an error below

Error : An error occured while creating ImapMailClient: AsposeException: AE_18_1_0002 NO [ALERT] Too many simultaneous connections. (Failure) ---> AsposeException: AE_18_1_0002 NO [ALERT] Too many simultaneous connections. (Failure)

even though using the preexisting open connection has been checked for.

Aspose.Email assembly version used (20.11.0.0)

Please help resolving the issues.

Thanks & Regards,
Yogesh

@yogesh.chhabra,
Thank you for the issue description. To my regret, I cannot use your code example to investigate the problem. Please share a simple standalone project.

Hi Andrey,

Here is the sample code i am attaching. TC it doesn’t have the Aspose.Total.lic.
And here is the exception shot that occurs

Thanks & Regards,
Yogesh

@yogesh.chhabra,
Thank you for the project sample. I have logged the issue in our tracking system with ID EMAILNET-40165 for further investigation. I will inform you about any progress.

Hi Andrey,

Thanks for the updates. Can we have some time estimates of the proposed solution or the idea to fix the issue. Please update.

Thanks & Regards,
Yogesh Chhabra

@yogesh.chhabra,
I requested an estimated time from our development team for the issue solution. I will inform you as soon as I know.

@yogesh.chhabra,
The fix will be available in Aspose.Email 20.3 at the end of the month.

Hi Andrey,
Thanks for the updates, and another thing to make sure is in the new version, both the issues mentioned will be resolved.

  1. Timeout exception
  2. Too many simultaneous connections.

and a small confusion to clear, is it the version 20.3 or else as i am presently using version 20.11.0.0 of Aspose.Email

Thanks & Regards,
Yogesh

@yogesh.chhabra,
Thank you for the additional information. We will take it into account.

@yogesh.chhabra,

I’m sorry for my mistake. I meant Aspose.Email 21.3.

@Andrey_Potapov
No probs. Still a big thanks for the updates.

@yogesh.chhabra,
Our development team investigated the issue and found no bugs. The reason is the limit of simultaneous connections on the server-side.

  1. The error with the message “AE_18_1_0002 NO [ALERT] Too many simultaneous connections” comes from the server. It means that there are too many IMAP connections opened for a given user. As we can see from the command identifier “AE_18_1_0002”, there were 18 ImapClient instances created. Each ImapClient instance has at least one active connection. There should not be more than 15 simultaneous connections. It is limited by the server. You should make sure that the ImapClient.Dispose method called for all unnecessary ImapClient instances.

  2. Also, as we can see from the code snippet you provided, you call the ImapClient.CreateConnection method without using the returned connection object. To use such a connection, you should save it to a variable and then provide it to ImapClient’s methods as a parameter. For example:

var connection = Client.CreateConnection();
await Client.SelectFolderAsync(connection, Settings.FolderName);

By the way, in your case, there is no reason to call the CreateConnection method. ImapClient always restores the main connection if it is necessary and possible. You don’t have to do it yourself.

  1. You’ve also provided the stack trace with the TimeoutException. This exception was thrown during the “Connect” operation execution. The server should send a greeting message to the ImapClient when a new connection is established. In your case, there are too many simultaneous connections, so the server does not send any greetings messages to the new one during the expected amount of time. That’s why the TimeoutException was thrown. We are going to improve this logic in the next version of Aspose.Email, so this exception will be more informative.

@Andrey_Potapov
I have updated the code as per the mentioned points,

  1. I have created and disposed the ImapMailClient object, within the work loop.

  2. I have commented the CreateConnection statement and used the Main connection, assigned it to a global variable and used the same as parameter to various functions except SelectFolder as this function is called at the creation of Client object.

  3. Will observe the improvement in the next version of Aspose.Email

And For an information, i have updated just 2 files listed below:

  1. ImapMailClient.cs
  2. ImapClientTests.cs

The updated statements have the comments alongside as //COMMENTS …

This hopefully would have resolved the Simultaneous Connections issue, (rest will be sure after a complete, thorough testing as the issue was occurring at QA end)

Rest looking ahead for the updates in the new version for Timeout related issue.

The code updates are referred here as :

Please have a look at.

Thanks & Regards,
Yogesh Chhabra

@yogesh.chhabra,
You have described the changes you are made. Could you please describe the remaining issues besides TimeoutException?

@Andrey_Potapov
Presently as per the testing and analysis, there are no issues besides the below mentioned:

  1. Too many simultaneous connections (seems resolved with code updates, confirm after QA verification)
  2. Connect timeout

Rest if any other issue occurs will let you know for sure.

Thanks & Regards,
Yogesh

@yogesh.chhabra,
We cannot use that link to download the Code Sample_ConnectionUpdates.zip file and check your changes. Could you fix the link, please?

@Andrey_Potapov
Please check it now. The code is available for download.

Thanks,

@Andrey_Potapov
Hoping for the new version of the package Aspose.Email as per the words.
please update.

Thanks,

@yogesh.chhabra,
Thank you, our development team will check your changes.

@yogesh.chhabra,
Our developers checked your project example. Your code should not throw errors.