{"record":{"id":"bc14dc1791227831","repo":"jstedfast/MailKit","slug":"specified-argument-was-out-of-the-range-of-valid-values","errorCode":null,"errorMessage":"Specified argument was out of the range of valid values. (Parameter 'port')","messagePattern":"Specified argument was out of the range of valid values\\. \\(Parameter 'port'\\)","errorType":"exception","errorClass":"ArgumentOutOfRangeException","httpStatus":null,"severity":"error","filePath":"MailKit/MailService.cs","lineNumber":1021,"sourceCode":"\t\t/// <exception cref=\"System.Net.Sockets.SocketException\">\n\t\t/// A socket error occurred trying to connect to the remote host.\n\t\t/// </exception>\n\t\t/// <exception cref=\"System.IO.IOException\">\n\t\t/// An I/O error occurred.\n\t\t/// </exception>\n\t\t/// <exception cref=\"ProtocolException\">\n\t\t/// A protocol error occurred.\n\t\t/// </exception>\n\t\tpublic Task ConnectAsync (string host, int port, bool useSsl, CancellationToken cancellationToken = default)\n\t\t{\n\t\t\tif (host == null)\n\t\t\t\tthrow new ArgumentNullException (nameof (host));\n\n\t\t\tif (host.Length == 0)\n\t\t\t\tthrow new ArgumentException (\"The host name cannot be empty.\", nameof (host));\n\n\t\t\tif (port < 0 || port > 65535)\n\t\t\t\tthrow new ArgumentOutOfRangeException (nameof (port));\n\n\t\t\treturn ConnectAsync (host, port, useSsl ? SecureSocketOptions.SslOnConnect : SecureSocketOptions.StartTlsWhenAvailable, cancellationToken);\n\t\t}\n\n\t\t/// <summary>\n\t\t/// Authenticate using the supplied credentials.\n\t\t/// </summary>\n\t\t/// <remarks>\n\t\t/// <para>Authenticates using the supplied credentials.</para>\n\t\t/// <para>If the server supports one or more SASL authentication mechanisms, then\n\t\t/// the SASL mechanisms that both the client and server support (not including any\n\t\t/// OAUTH mechanisms) are tried in order of greatest security to weakest security.\n\t\t/// Once a SASL authentication mechanism is found that both client and server support,\n\t\t/// the credentials are used to authenticate.</para>\n\t\t/// <para>If the server does not support SASL or if no common SASL mechanisms\n\t\t/// can be found, then the default login command is used as a fallback.</para>\n\t\t/// <note type=\"tip\">To prevent the usage of certain authentication mechanisms,\n\t\t/// simply remove them from the <see cref=\"AuthenticationMechanisms\"/> hash set","sourceCodeStart":1003,"sourceCodeEnd":1039,"githubUrl":"https://github.com/jstedfast/MailKit/blob/9d3859a7855e3e17582c07fd01972b8e262bf176/MailKit/MailService.cs#L1003-L1039","documentation":"MailService.ConnectAsync validates the port argument before opening a connection. A ArgumentOutOfRangeException is thrown when port is negative or greater than 65535, since those are not valid TCP port values. This is a fail-fast guard so you never attempt a network connection with an unusable port.","triggerScenarios":"Calling ConnectAsync(host, port) or ConnectAsync(host, port, useSsl) with a port < 0 or port > 65535, e.g. a port parsed from config as -1, a missing config defaulting to 0-minus, or an integer overflow when combining host:port.","commonSituations":"Config files with an unset/placeholder port (e.g. -1 meaning 'unset'), string parsing that yields a sentinel value, or a user typo like 99999 for an SMTP/IMAP port.","solutions":["Verify the port number is within 0-65535 before calling ConnectAsync","Fix the configuration value or default that produced the invalid port","If a port variable may be 'unset', use -1 only with APIs that accept it and pass a valid port here","Clamp or validate parsed user input before constructing the connection call"],"exampleFix":"// before\nint port = int.Parse(config[\"Port\"]); // -1 when missing\nawait client.ConnectAsync(host, port);\n// after\nint port = int.Parse(config[\"Port\"]);\nif (port < 0 || port > 65535) throw new InvalidOperationException(\"SMTP port is not configured\");\nawait client.ConnectAsync(host, port);","handlingStrategy":"validation","validationCode":"if (port < 0 || port > 65535) throw new ArgumentOutOfRangeException(nameof(port), port, \"Port must be between 0 and 65535\");\nawait client.ConnectAsync(host, port, cancellationToken);","typeGuard":"bool IsValidPort(int port) => port >= 0 && port <= 65535;","tryCatchPattern":"try { await client.ConnectAsync(host, port, ct); }\ncatch (ArgumentOutOfRangeException ex) when (ex.ParamName == \"port\") { logger.LogError(ex, \"Invalid port {Port} for host {Host}\", port, host); throw new ConfigurationException(\"Invalid mail server port\", ex); }","preventionTips":["Validate port values at config-load time, before any connection attempt","Never use -1 or other sentinels as a port value for ConnectAsync","Parse ports with TryParse and range-check the result","Keep port values as dedicated validated types in your config layer"],"tags":["mailkit","argument-validation","network","port"],"backgroundTag":"argument-out-of-range","analyzedSha":"9d3859a7855e3e17582c07fd01972b8e262bf176","analyzedAt":"2026-09-15T15:46:11.592Z","contentChangedAt":"2026-09-15T15:46:11.592Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}