{"record":{"id":"33c73709f1ea0419","repo":"jstedfast/MailKit","slug":"the-smtpclient-must-be-connected-before-you-can-authenticate","errorCode":null,"errorMessage":"The SmtpClient must be connected before you can authenticate.","messagePattern":"The SmtpClient must be connected before you can authenticate\\.","errorType":"exception","errorClass":"ServiceNotConnectedException","httpStatus":null,"severity":"error","filePath":"MailKit/Net/Smtp/SmtpClient.cs","lineNumber":999,"sourceCode":"\t\t\t\t// Try sending HELO instead...\n\t\t\t\tresponse = SendEhlo (connecting, \"HELO\", cancellationToken);\n\n\t\t\t\tif (response.StatusCode != SmtpStatusCode.Ok)\n\t\t\t\t\tthrow new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);\n\t\t\t} else {\n\t\t\t\tUpdateCapabilities (response);\n\t\t\t}\n\t\t}\n\n\t\tvoid ValidateArguments (SaslMechanism mechanism)\n\t\t{\n\t\t\tif (mechanism == null)\n\t\t\t\tthrow new ArgumentNullException (nameof (mechanism));\n\n\t\t\tCheckDisposed ();\n\n\t\t\tif (!IsConnected)\n\t\t\t\tthrow new ServiceNotConnectedException (\"The SmtpClient must be connected before you can authenticate.\");\n\n\t\t\tif (IsAuthenticated)\n\t\t\t\tthrow new InvalidOperationException (\"The SmtpClient is already authenticated.\");\n\n\t\t\tif ((capabilities & SmtpCapabilities.Authentication) == 0)\n\t\t\t\tthrow new NotSupportedException (\"The SMTP server does not support authentication.\");\n\n\t\t\tmechanism.ChannelBindingContext = Stream.Stream as IChannelBindingContext;\n\t\t\tmechanism.Uri = new Uri ($\"smtp://{uri.Host}\");\n\t\t}\n\n\t\t/// <summary>\n\t\t/// Authenticate using the specified SASL mechanism.\n\t\t/// </summary>\n\t\t/// <remarks>\n\t\t/// <para>Authenticates using the specified SASL mechanism.</para>\n\t\t/// <para>For a list of available SASL authentication mechanisms supported by the server,\n\t\t/// check the <see cref=\"AuthenticationMechanisms\"/> property after the service has been","sourceCodeStart":981,"sourceCodeEnd":1017,"githubUrl":"https://github.com/jstedfast/MailKit/blob/9d3859a7855e3e17582c07fd01972b8e262bf176/MailKit/Net/Smtp/SmtpClient.cs#L981-L1017","documentation":"MailKit's SmtpClient.Authenticate (SASL mechanism overload) throws ServiceNotConnectedException because IsConnected is false when Authenticate is called. The client requires a completed Connect (and typically EHLO negotiation) before any AUTH command can be sent. This is a strict state-machine guard: authentication without a live socket is meaningless.","triggerScenarios":"Calling SmtpClient.Authenticate(string mechanismName, string user, string password) or Authenticate(SaslMechanism, ...) without calling Connect first, or after the connection has been dropped by the server or network.","commonSituations":"Forgetting the Connect call (or commenting it out in refactored code); Connect succeeding but the server dropping the connection before Authenticate; reusing a client instance after Disconnect/Dispose; async/await code paths where an exception during Connect is swallowed and execution continues to Authenticate.","solutions":["Call SmtpClient.Connect(host, port, SecureSocketOptions) and check it succeeds before calling Authenticate.","Wrap the whole connect/authenticate/send sequence in try-catch so a failed Connect aborts the flow instead of falling through to Authenticate.","If reusing the client, check client.IsConnected (and !client.IsDisposed) before Authenticate, or create a fresh SmtpClient instance."],"exampleFix":"// before\nvar client = new SmtpClient();\nclient.Authenticate(\"user\", \"pass\"); // throws ServiceNotConnectedException\n\n// after\nvar client = new SmtpClient();\nclient.Connect(\"smtp.example.com\", 465, SecureSocketOptions.SslOnConnect);\nclient.Authenticate(\"user\", \"pass\");","handlingStrategy":"try-catch","validationCode":"if (client == null || client.IsDisposed || !client.IsConnected)\n    throw new InvalidOperationException(\"SmtpClient must be connected before authenticating.\");","typeGuard":null,"tryCatchPattern":"try {\n    client.Authenticate(mechanism);\n} catch (ServiceNotConnectedException) {\n    // reconnect then retry authenticate\n    client.Connect(host, port, SecureSocketOptions.StartTls);\n    client.Authenticate(mechanism);\n}","preventionTips":["Always call Connect immediately before Authenticate in the same method.","Never swallow exceptions from Connect.","Assert client.IsConnected in debug builds before authenticating."],"tags":["smtp","mailkit","connection-state","authentication"],"backgroundTag":"authentication-required","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"}