Search code examples
c#imapmailkit

C# mailkit imap idle reconnect connection reset by peer


Example program on github page for imap idle throws connection reset by peer after 9 minutes when connected to gmail imap server. Running dotnet core console app on raspberry Pi 3 connected to a mobile hotspot internet connection

The code works perfectly for any other network or pc. It dont work only when the raspberry is connected to the mobile hotspot

The code works fine on first connection. It only breaks and throws connection reset by peer on this single function

private void IdleLoop(object state) {
            IdleState idle = (IdleState) state;
            lock (idle.Client.SyncRoot) {
                while (!idle.IsCancellationRequested) {
                    using (CancellationTokenSource timeout = new CancellationTokenSource()) {
                        using (Timer timer = new Timer(9 * 60 * 1000)) {
                            timer.Elapsed += (sender, e) => timeout.Cancel();
                            timer.AutoReset = false;
                            timer.Enabled = true;

                            try {
                                idle.SetTimeoutSource(timeout);

                                if (idle.Client.Capabilities.HasFlag(ImapCapabilities.Idle)) {

                                    //TODO ERROR
                                    idle.Client.Idle(timeout.Token, idle.CancellationToken);
                                }
                                else {
                                    Logger.Log("Issuing NoOp command to IMAP servers...");
                                    idle.Client.NoOp(idle.CancellationToken);
                                    WaitHandle.WaitAny(new[] { timeout.Token.WaitHandle, idle.CancellationToken.WaitHandle });
                                    Logger.Log("NoOp completed!");
                                }
                            }
                            catch (OperationCanceledException) {
                                break;
                            }
                            catch (ImapProtocolException) {
                                break;
                            }
                            catch (ImapCommandException) {
                                break;
                            }
                            finally {
                                idle.SetTimeoutSource(null);
                            }
                        }
                    }
                }
            }
        }

Solution

  • Mobile hotspots aren't a reliable internet connection, hence the "connection reset by peer" error you are getting.

    You could try reducing the timeout duration, but ultimately, what you'll need to do is re-connect when you get that error (it's unavoidable - even on a more reliable internet connection it can happen).