Click or drag to resize
MimeKit

SmtpClientConnect Method (String, Int32, SecureSocketOptions, CancellationToken)

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

Namespace:  MailKit.Net.Smtp
Assembly:  MailKit (in MailKit.dll) Version: 2.3.0
Syntax
C#
public override void Connect(
	string host,
	int port = 0,
	SecureSocketOptions options = SecureSocketOptions.Auto,
	CancellationToken cancellationToken = null
)

Parameters

host
Type: SystemString
The host name to connect to.
port (Optional)
Type: SystemInt32
The port to connect to. If the specified port is 0, then the default port will be used.
options (Optional)
Type: MailKit.SecuritySecureSocketOptions
The secure socket options to when connecting.
cancellationToken (Optional)
Type: System.ThreadingCancellationToken
The cancellation token.

Implements

IMailServiceConnect(String, Int32, SecureSocketOptions, CancellationToken)
Exceptions
ExceptionCondition
ArgumentNullExceptionhost is null.
ArgumentOutOfRangeExceptionport is not between 0 and 65535.
ArgumentException The host is a zero-length string.
ObjectDisposedException The SmtpClient has been disposed.
InvalidOperationException The SmtpClient is already connected.
NotSupportedExceptionoptions was set to StartTls and the SMTP server does not support the STARTTLS extension.
OperationCanceledException The operation was canceled.
SocketException A socket error occurred trying to connect to the remote host.
SslHandshakeException An error occurred during the SSL/TLS negotiations.
IOException An I/O error occurred.
SmtpCommandException An SMTP command failed.
SmtpProtocolException An SMTP protocol error occurred.
Remarks

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 SslOnConnect is 465. All other values will use a default port of 25.

If the options has a value of 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 SslOnConnect. All other values will use StartTlsWhenAvailable.

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

Note Note
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.
Examples
C#
public static void SendMessage (MimeMessage message)
{
    using (var client = new SmtpClient ()) {
        client.Connect ("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect);

        client.Authenticate ("username", "password");

        client.Send (message);

        client.Disconnect (true);
    }
}
See Also