jstedfast/MailKit · error · ImapProtocolException

The IMAP server unexpectedly refused the connection.

Error message

The IMAP server unexpectedly refused the connection.

What it means

During connection greeting processing (synchronous path), ImapEngine reads the server's initial response; when it encounters an untagged BYE and no greeting text to surface, it throws this ImapProtocolException. The server sent BYE at handshake time, i.e. it refused the connection after TCP/TLS setup.

Solutions

  1. Retry with backoff — this is often transient (connection limits or restart).
  2. Inspect server logs for the BYE reason (max connections, shutdown, auth restrictions).
  3. Reduce concurrent IMAP connections or implement connection pooling/reuse in the client.
  4. Verify the host/port/SSL settings target the right service (imaps 993 vs starttls 143).

Example fix

// before
client.Connect(host, 993, true);
client.Authenticate(user, pass);

// after
for (int attempt = 0; attempt < 3; attempt++) {
    try {
        client.Connect(host, 993, true);
        break;
    } catch (ImapProtocolException ex) when (attempt < 2 && ex.Message.Contains("refused the connection")) {
        await Task.Delay(TimeSpan.FromSeconds(2 * (attempt + 1)));
    }
}
Defensive patterns

Strategy: retry

Try / catch

try { client.Connect(host, port, secure); } catch (ImapProtocolException ex) when (ex.Message.Contains("refused the connection")) { /* retry with backoff; check server-side caps */ }

Prevention

When it happens

Trigger: Server sends an untagged BYE as/instead of its greeting during Connect; typically rate limiting, 'max connections reached', or the server shutting down. Empty/odd greeting lines also route here.

Common situations: Server-side connection caps exceeded (e.g. Dovecot max connections per IP); server restarting mid-deploy; firewall/LB accepting TCP then the backend rejecting; hosting provider throttling.

Understand the failure class

Background: ECONNREFUSED and "connection refused" / "could not connect to server" errors: what they mean and how to fix them — this error's family across 44 libraries.

Related errors


AI-assisted analysis of jstedfast/MailKit@9d3859a785 (2026-09-15). Data as JSON: /api/errors/b12b017c88edf31c. Report an issue: GitHub.

Appendix: source

Thrown at MailKit/Net/Imap/ImapEngine.cs:806

				if (token.Type == ImapTokenType.OpenBracket) {
					var code = ParseResponseCode (false, cancellationToken);
					if (code.Type == ImapResponseCodeType.Alert) {
						OnAlert (code.Message);

						if (bye)
							throw new ImapProtocolException (code.Message);
					} else {
						text = code.Message;
					}
				} else if (token.Type != ImapTokenType.Eoln) {
					text = ReadLine (cancellationToken).TrimEnd ();
					text = token.Value.ToString () + text;

					if (bye)
						throw new ImapProtocolException (text);
				} else if (bye) {
					throw new ImapProtocolException ("The IMAP server unexpectedly refused the connection.");
				}

				DetectQuirksMode (text);

				State = state;
			} catch (Exception ex) {
				Disconnect (ex);
				throw;
			}
		}

		/// <summary>
		/// Takes possession of the <see cref="ImapStream"/> and reads the greeting.
		/// </summary>
		/// <param name="stream">The IMAP stream.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.

View on GitHub (pinned to 9d3859a785)