Click or drag to resize

ImapClientConnectAsync Method (String, Int32, SecureSocketOptions, CancellationToken)

Asynchronously establish a connection to the specified IMAP server.

Namespace:  MailKit.Net.Imap
Assembly:  MailKit (in MailKit.dll) Version: 3.0.0
public override Task ConnectAsync(
	string host,
	int port = 0,
	SecureSocketOptions options = SecureSocketOptions.Auto,
	CancellationToken cancellationToken = default


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.

Return Value

Type: Task
An asynchronous task context.


IMailServiceConnectAsync(String, Int32, SecureSocketOptions, CancellationToken)
IMailServiceConnectAsync(String, Int32, SecureSocketOptions, CancellationToken)
ArgumentNullExceptionhost is null.
ArgumentOutOfRangeExceptionport is not between 0 and 65535.
ArgumentException The host is a zero-length string.
ObjectDisposedException The ImapClient has been disposed.
InvalidOperationException The ImapClient is already connected.
NotSupportedExceptionoptions was set to StartTls and the IMAP server does not support the STARTTLS extension.
OperationCanceledException The operation was canceled via the cancellation token.
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.
ImapCommandException An IMAP command failed.
ImapProtocolException An IMAP protocol error occurred.

Establishes a connection to the specified IMAP or IMAP/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 993. All other values will use a default port of 143.

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 993, 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.

public static void DownloadMessages ()
    using (var client = new ImapClient ()) {
        client.Connect ("", 993, SecureSocketOptions.SslOnConnect);

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

        client.Inbox.Open (FolderAccess.ReadOnly);

        var uids = client.Inbox.Search (SearchQuery.All);

        foreach (var uid in uids) {
            var message = client.Inbox.GetMessage (uid);

            // write the message to a file
            message.WriteTo (string.Format ("{0}.eml", uid));

        client.Disconnect (true);
See Also