public void Connect (Socket socket, string host, int port = 0, SecureSocketOptions options = SecureSocketOptions.Auto, CancellationToken cancellationToken = default (CancellationToken))
{
if (socket == null)
throw new ArgumentNullException (nameof (socket));
if (!socket.Connected)
throw new ArgumentException ("The socket is not connected.", nameof (socket));
if (host == null)
throw new ArgumentNullException (nameof (host));
if (host.Length == 0)
throw new ArgumentException ("The host name cannot be empty.", nameof (host));
if (port < 0 || port > 65535)
throw new ArgumentOutOfRangeException (nameof (port));
CheckDisposed ();
if (IsConnected)
throw new InvalidOperationException ("The SmtpClient is already connected.");
capabilities = SmtpCapabilities.None;
AuthenticationMechanisms.Clear ();
MaxSize = 0;
SmtpResponse response;
Stream stream;
bool starttls;
Uri uri;
ComputeDefaultValues (host, ref port, ref options, out uri, out starttls);
this.host = host;
if (options == SecureSocketOptions.SslOnConnect) {
var ssl = new SslStream (new NetworkStream (socket, true), false, ValidateRemoteCertificate);
try {
#if COREFX
ssl.AuthenticateAsClientAsync (host, ClientCertificates, SslProtocols, true).GetAwaiter ().GetResult ();
#else
ssl.AuthenticateAsClient (host, ClientCertificates, SslProtocols, true);
#endif
} catch {
ssl.Dispose ();
throw;
}
secure = true;
stream = ssl;
} else {
stream = new NetworkStream (socket, true);
secure = false;
}
if (stream.CanTimeout) {
stream.WriteTimeout = timeout;
stream.ReadTimeout = timeout;
}
ProtocolLogger.LogConnect (uri);
Stream = new SmtpStream (stream, socket, ProtocolLogger);
try {
// read the greeting
response = Stream.ReadResponse (cancellationToken);
if (response.StatusCode != SmtpStatusCode.ServiceReady)
throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);
// Send EHLO and get a list of supported extensions
Ehlo (cancellationToken);
if (options == SecureSocketOptions.StartTls && (capabilities & SmtpCapabilities.StartTLS) == 0)
throw new NotSupportedException ("The SMTP server does not support the STARTTLS extension.");
if (starttls && (capabilities & SmtpCapabilities.StartTLS) != 0) {
response = SendCommand ("STARTTLS", cancellationToken);
if (response.StatusCode != SmtpStatusCode.ServiceReady)
throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);
var tls = new SslStream (stream, false, ValidateRemoteCertificate);
#if COREFX
tls.AuthenticateAsClientAsync (host, ClientCertificates, SslProtocols, true).GetAwaiter ().GetResult ();
#else
tls.AuthenticateAsClient (host, ClientCertificates, SslProtocols, true);
#endif
Stream.Stream = tls;
secure = true;
// Send EHLO again and get the new list of supported extensions
Ehlo (cancellationToken);
}
connected = true;
} catch {
Stream.Dispose ();
secure = false;
Stream = null;
throw;
}
OnConnected ();
}
#endif