MailKit.Net.Smtp.SmtpClient.Connect C# (CSharp) Method

Connect() public method

Establish a connection to the specified SMTP or SMTP/S server using the provided socket.

Establishes a connection to the specified SMTP or SMTP/S server.

If the port has a value of 0, then the options parameter is used to determine the default port to connect to. The default port used with SecureSocketOptions.SslOnConnect is 465. All other values will use a default port of 25.

If the options has a value of SecureSocketOptions.Auto, then the port is used to determine the default security options. If the port has a value of 465, then the default options used will be SecureSocketOptions.SslOnConnect. All other values will use SecureSocketOptions.StartTlsWhenAvailable.

Once a connection is established, properties such as AuthenticationMechanisms and Capabilities will be populated.

The connection established by any of the Connect methods may be re-used if an application wishes to send multiple messages to the same SMTP server. Since connecting and authenticating can be expensive operations, re-using a connection can significantly improve performance when sending a large number of messages to the same SMTP server over a short period of time./
/// is null. /// -or- /// is null. /// /// is not between 0 and 65535. /// /// is not connected. /// -or- /// The is a zero-length string. /// /// The has been disposed. /// /// The is already connected. /// /// was set to /// /// and the SMTP server does not support the STARTTLS extension. /// /// The operation was canceled. /// /// An I/O error occurred. /// /// An SMTP command failed. /// /// An SMTP protocol error occurred. ///
public Connect ( StreamSocket socket, string host, int port, SecureSocketOptions options = SecureSocketOptions.Auto, CancellationToken cancellationToken = default(CancellationToken) ) : void
socket Windows.Networking.Sockets.StreamSocket The socket to use for the connection.
host string The host name to connect to.
port int The port to connect to. If the specified port is 0, then the default port will be used.
options SecureSocketOptions The secure socket options to when connecting.
cancellationToken System.Threading.CancellationToken The cancellation token.
return void
		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

Same methods

SmtpClient::Connect ( string host, int port, SecureSocketOptions options = SecureSocketOptions.Auto, CancellationToken cancellationToken = default(CancellationToken) ) : void

Usage Example

Example #1
3
        public void Send(EmailDependencies email)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(email.FromName, email.FromAddress));

                message.To.Add(new MailboxAddress(email.ToName, email.ToAddress));
                message.To.Add(new MailboxAddress(email.FromName, email.FromAddress));

                message.Subject = email.Title;
                message.Body = new TextPart("html") { Text = email.content };

                using (var client = new SmtpClient())
                {
                    client.Connect("mail.bizmonger.net", 587, false);

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate(Configuration.ServerEmail, Configuration.Password);

                    client.Send(message);
                    client.Disconnect(true);
                }
            }
            catch (Exception ex)
            {
                var errorMessage = ex.GetBaseException().Message;
                Debug.WriteLine(errorMessage);
            }
        }
All Usage Examples Of MailKit.Net.Smtp.SmtpClient::Connect