{"record":{"id":"69c43d94006adbe6","repo":"jstedfast/MailKit","slug":"the-imap-server-has-unexpectedly-disconnected","errorCode":null,"errorMessage":"The IMAP server has unexpectedly disconnected.","messagePattern":"The IMAP server has unexpectedly disconnected\\.","errorType":"exception","errorClass":"ImapProtocolException","httpStatus":null,"severity":"critical","filePath":"MailKit/Net/Imap/ImapStream.cs","lineNumber":321,"sourceCode":"\n\t\tint ReadAhead (int atleast, CancellationToken cancellationToken)\n\t\t{\n\t\t\tif (!AlignReadAheadBuffer (atleast, out int left, out int start, out int end))\n\t\t\t\treturn left;\n\n\t\t\ttry {\n\t\t\t\tvar network = Stream as NetworkStream;\n\t\t\t\tint nread;\n\n\t\t\t\tcancellationToken.ThrowIfCancellationRequested ();\n\n\t\t\t\tnetwork?.Poll (SelectMode.SelectRead, cancellationToken);\n\n\t\t\t\tif ((nread = Stream.Read (input, start, end - start)) > 0) {\n\t\t\t\t\tlogger.LogServer (input, start, nread);\n\t\t\t\t\tinputEnd += nread;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new ImapProtocolException (\"The IMAP server has unexpectedly disconnected.\");\n\t\t\t\t}\n\n\t\t\t\tif (network == null)\n\t\t\t\t\tcancellationToken.ThrowIfCancellationRequested ();\n\t\t\t} catch {\n\t\t\t\tIsConnected = false;\n\t\t\t\tthrow;\n\t\t\t}\n\n\t\t\treturn inputEnd - inputIndex;\n\t\t}\n\n\t\tasync ValueTask<int> ReadAheadAsync (int atleast, CancellationToken cancellationToken)\n\t\t{\n\t\t\tif (!AlignReadAheadBuffer (atleast, out int left, out int start, out int end))\n\t\t\t\treturn left;\n\n\t\t\ttry {","sourceCodeStart":303,"sourceCodeEnd":339,"githubUrl":"https://github.com/jstedfast/MailKit/blob/9d3859a7855e3e17582c07fd01972b8e262bf176/MailKit/Net/Imap/ImapStream.cs#L303-L339","documentation":"MailKit throws this ImapProtocolException from ImapStream.ReadAhead when reading from the socket returns 0 bytes or otherwise fails mid-command, meaning the TCP connection to the IMAP server dropped without a proper BYE response. Setting IsConnected=false, the ImapClient transitions to a disconnected state and the in-flight command fails.","triggerScenarios":"Server process crash/restart, idle connection killed by a NAT/firewall/load balancer, network outage, or server closing the connection during any read (ReadLine, token parsing, literal reads).","commonSituations":"Long-lived connections with NOOP keepalives disabled hitting idle timeouts; server maintenance windows; flaky mobile/VPN networks; reading a large message fetch when the server dies mid-literal.","solutions":["Reconnect: create/reconnect the ImapClient, re-authenticate, and re-select the folder, then retry the operation","Wrap long-running sessions with periodic NOOP keepalive (ImapClient's KeepAlive) to defeat idle timeouts","Implement retry logic that detects ImapProtocolException/ServiceNotConnected and rebuilds the connection","Check server logs and network path (NAT idle timeout, LB settings) if drops are frequent"],"exampleFix":"// before\nvar messages = folder.Fetch (0, -1, summary);\n// after\ntry {\n    var messages = folder.Fetch (0, -1, summary);\n} catch (ImapProtocolException) {\n    client.Disconnect (true);\n    client.Connect (host, port, useSsl);\n    client.Authenticate (user, pass);\n    folder = client.GetFolder (folderName);\n    folder.Open (FolderAccess.ReadOnly);\n    var messages = folder.Fetch (0, -1, summary);\n}","handlingStrategy":"retry","validationCode":"if (!client.IsConnected) { await ReconnectAsync (); }","typeGuard":null,"tryCatchPattern":"try { return await folder.FetchAsync (0, -1, summary); } catch (ImapProtocolException ex) { await ReconnectAsync (); return await folder.FetchAsync (0, -1, summary); }","preventionTips":["Enable keepalive NOOPs","Retry with reconnect on ImapProtocolException","Keep operations idempotent"],"tags":["imap","mailkit","network","connection-dropped","protocol-exception"],"backgroundTag":"connection-refused","analyzedSha":"9d3859a7855e3e17582c07fd01972b8e262bf176","analyzedAt":"2026-09-15T15:46:11.592Z","contentChangedAt":"2026-09-15T15:46:11.592Z","schemaVersion":2},"datasetVersion":"2026-09-15T23:17:13.987Z"}