smiley22 / S22.Imap

A free, easy-to-use and well-documented .NET library component for communicating with IMAP servers
http://smiley22.github.com/S22.Imap/Documentation/
MIT License
210 stars 112 forks source link

Connection doesn't restart after disruption to internet connection #170

Open Scylla2020 opened 3 years ago

Scylla2020 commented 3 years ago

I tried the example code below and turned internet connection off for about a minute then back on to test reconnection. Disrupting the connection gives the error Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. No more emails get fetched after that. How can I get the reconnection to always work?

using S22.Imap;
using System;

namespace ConsoleApplication1 {
    class Program {
        static AutoResetEvent reconnectEvent = new AutoResetEvent(false);
        static ImapClient client;

        static void Main(string[] args) {
            try {
                while (true) {
                    Console.Write("Connecting...");
                    InitializeClient();
                    Console.WriteLine("OK");

                    reconnectEvent.WaitOne();
                }
            } finally {
                if (client != null)
                    client.Dispose();
            }
        }

        static void InitializeClient() {
            // Dispose of existing instance, if any.
            if (client != null)
                client.Dispose();
            client = new ImapClient("imap.gmail.com", 993, "username", "password", AuthMethod.Login, true);
            // Setup event handlers.
            client.NewMessage += client_NewMessage;
            client.IdleError += client_IdleError;
        }

        static void client_IdleError(object sender, IdleErrorEventArgs e) {
            Console.Write("An error occurred while idling: ");
            Console.WriteLine(e.Exception.Message);

            reconnectEvent.Set();
        }

        static void client_NewMessage(object sender, IdleMessageEventArgs e) {
            Console.WriteLine("Got a new message, uid = " + e.MessageUID);
        }
    }
}