Click or drag to resize
MimeKit

ImapClient Class

An IMAP client that can be used to retrieve messages from a server.
Inheritance Hierarchy

Namespace:  MailKit.Net.Imap
Assembly:  MailKit (in MailKit.dll) Version: 2.10.0
Syntax
C#
public class ImapClient : MailStore, IImapClient, 
	IMailStore, IMailService, IDisposable

The ImapClient type exposes the following members.

Constructors
  NameDescription
Public methodCode exampleImapClient
Initializes a new instance of the ImapClient class.
Public methodCode exampleImapClient(IProtocolLogger)
Initializes a new instance of the ImapClient class.
Top
Properties
  NameDescription
Public propertyAppendLimit
Gets the maximum size of a message that can be appended to a folder.
Public propertyCode exampleAuthenticationMechanisms
Get the authentication mechanisms supported by the IMAP server.
(Overrides MailServiceAuthenticationMechanisms.)
Public propertyCode exampleCapabilities
Get the capabilities supported by the IMAP server.
Public propertyCheckCertificateRevocation
Get or set whether connecting via SSL/TLS should check certificate revocation.
(Inherited from MailService.)
Public propertyClientCertificates
Gets or sets the client SSL certificates.
(Inherited from MailService.)
Public propertyCode exampleInbox
Get the Inbox folder.
(Overrides MailStoreInbox.)
Public propertyInternationalizationLevel
Gets the internationalization level supported by the IMAP server.
Public propertyIsAuthenticated
Get whether or not the client is currently authenticated with the IMAP server.
(Overrides MailServiceIsAuthenticated.)
Public propertyIsConnected
Get whether or not the client is currently connected to an IMAP server.
(Overrides MailServiceIsConnected.)
Public propertyIsIdle
Get whether or not the client is currently in the IDLE state.
Public propertyIsSecure
Get whether or not the connection is secure (typically via SSL or TLS).
(Overrides MailServiceIsSecure.)
Public propertyLocalEndPoint
Get or set the local IP end point to use when connecting to the remote host.
(Inherited from MailService.)
Public propertyOtherNamespaces
Get the other namespaces.
(Overrides MailStoreOtherNamespaces.)
Public propertyPersonalNamespaces
Get the personal namespaces.
(Overrides MailStorePersonalNamespaces.)
Protected propertyProtocol
Get the protocol supported by the message service.
(Overrides MailServiceProtocol.)
Public propertyProtocolLogger
Get the protocol logger.
(Inherited from MailService.)
Public propertyProxyClient
Get or set the proxy client to use when connecting to a remote host.
(Inherited from MailService.)
Public propertyCode exampleRights
Get the access rights supported by the IMAP server.
Public propertyCode exampleServerCertificateValidationCallback
Get or sets a callback function to validate the server certificate.
(Inherited from MailService.)
Public propertySharedNamespaces
Get the shared namespaces.
(Overrides MailStoreSharedNamespaces.)
Public propertySslProtocols
Gets or sets the SSL and TLS protocol versions that the client is allowed to use.
(Inherited from MailService.)
Public propertySupportsQuotas
Get whether or not the mail store supports quotas.
(Overrides MailStoreSupportsQuotas.)
Public propertySyncRoot
Gets an object that can be used to synchronize access to the IMAP server.
(Overrides MailServiceSyncRoot.)
Public propertyCode exampleThreadingAlgorithms
Get the threading algorithms supported by the IMAP server.
(Overrides MailStoreThreadingAlgorithms.)
Public propertyTimeout
Get or set the timeout for network streaming operations, in milliseconds.
(Overrides MailServiceTimeout.)
Top
Methods
  NameDescription
Public methodAuthenticate(ICredentials, CancellationToken)
Authenticate using the supplied credentials.
(Inherited from MailService.)
Public methodAuthenticate(SaslMechanism, CancellationToken)
Authenticate using the specified SASL mechanism.
(Overrides MailServiceAuthenticate(SaslMechanism, CancellationToken).)
Public methodCode exampleAuthenticate(String, String, CancellationToken)
Authenticate using the specified user name and password.
(Inherited from MailService.)
Public methodAuthenticate(Encoding, ICredentials, CancellationToken)
Authenticate using the supplied credentials.
(Overrides MailServiceAuthenticate(Encoding, ICredentials, CancellationToken).)
Public methodAuthenticate(Encoding, String, String, CancellationToken)
Authenticate using the specified user name and password.
(Inherited from MailService.)
Public methodAuthenticateAsync(ICredentials, CancellationToken)
Asynchronously authenticate using the supplied credentials.
(Inherited from MailService.)
Public methodAuthenticateAsync(SaslMechanism, CancellationToken)
Asynchronously authenticate using the specified SASL mechanism.
(Overrides MailServiceAuthenticateAsync(SaslMechanism, CancellationToken).)
Public methodAuthenticateAsync(String, String, CancellationToken)
Asynchronously authenticate using the specified user name and password.
(Inherited from MailService.)
Public methodAuthenticateAsync(Encoding, ICredentials, CancellationToken)
Asynchronously authenticate using the supplied credentials.
(Overrides MailServiceAuthenticateAsync(Encoding, ICredentials, CancellationToken).)
Public methodAuthenticateAsync(Encoding, String, String, CancellationToken)
Asynchronously authenticate using the specified user name and password.
(Inherited from MailService.)
Public methodCompress
Enable compression over the IMAP connection.
Public methodCompressAsync
Asynchronously enable compression over the IMAP connection.
Public methodCode exampleConnect(Uri, CancellationToken)
Establish a connection to the specified mail server.
(Inherited from MailService.)
Public methodConnect(String, Int32, Boolean, CancellationToken)
Establish a connection to the specified mail server.
(Inherited from MailService.)
Public methodCode exampleConnect(String, Int32, SecureSocketOptions, CancellationToken)
Establish a connection to the specified IMAP server.
(Overrides MailServiceConnect(String, Int32, SecureSocketOptions, CancellationToken).)
Public methodConnect(Stream, String, Int32, SecureSocketOptions, CancellationToken)
Establish a connection to the specified IMAP or IMAP/S server using the provided stream.
(Overrides MailServiceConnect(Stream, String, Int32, SecureSocketOptions, CancellationToken).)
Public methodConnect(Socket, String, Int32, SecureSocketOptions, CancellationToken)
Establish a connection to the specified IMAP or IMAP/S server using the provided socket.
(Overrides MailServiceConnect(Socket, String, Int32, SecureSocketOptions, CancellationToken).)
Public methodConnectAsync(Uri, CancellationToken)
Asynchronously establish a connection to the specified mail server.
(Inherited from MailService.)
Public methodConnectAsync(String, Int32, Boolean, CancellationToken)
Asynchronously establish a connection to the specified mail server.
(Inherited from MailService.)
Public methodCode exampleConnectAsync(String, Int32, SecureSocketOptions, CancellationToken)
Asynchronously establish a connection to the specified IMAP server.
(Overrides MailServiceConnectAsync(String, Int32, SecureSocketOptions, CancellationToken).)
Public methodConnectAsync(Stream, String, Int32, SecureSocketOptions, CancellationToken)
Asynchronously establish a connection to the specified IMAP or IMAP/S server using the provided stream.
(Overrides MailServiceConnectAsync(Stream, String, Int32, SecureSocketOptions, CancellationToken).)
Public methodConnectAsync(Socket, String, Int32, SecureSocketOptions, CancellationToken)
Asynchronously establish a connection to the specified IMAP or IMAP/S server using the provided socket.
(Overrides MailServiceConnectAsync(Socket, String, Int32, SecureSocketOptions, CancellationToken).)
Protected methodCreateImapFolder
Instantiate a new ImapFolder.
Protected methodDefaultServerCertificateValidationCallback
The default server certificate validation callback used when connecting via SSL or TLS.
(Inherited from MailService.)
Public methodDisableNotify
Disable any previously requested notification events from the IMAP server.
Public methodDisableNotifyAsync
Asynchronously disable any previously requested notification events from the IMAP server.
Public methodCode exampleDisconnect
Disconnect the service.
(Overrides MailServiceDisconnect(Boolean, CancellationToken).)
Public methodCode exampleDisconnectAsync
Asynchronously disconnect the service.
(Overrides MailServiceDisconnectAsync(Boolean, CancellationToken).)
Public methodDispose
Releases all resource used by the MailService object.
(Inherited from MailService.)
Protected methodDispose(Boolean)
Releases the unmanaged resources used by the ImapClient and optionally releases the managed resources.
(Overrides MailServiceDispose(Boolean).)
Public methodEnableQuickResync
Enable the QRESYNC feature.
(Overrides MailStoreEnableQuickResync(CancellationToken).)
Public methodEnableQuickResyncAsync
Asynchronously enable the QRESYNC feature.
(Overrides MailStoreEnableQuickResyncAsync(CancellationToken).)
Public methodEnableUTF8
Enable the UTF8=ACCEPT extension.
Public methodEnableUTF8Async
Asynchronously enable the UTF8=ACCEPT extension.
Public methodEquals
Determines whether the specified object is equal to the current object.
(Inherited from Object.)
Protected methodFinalize
Releases unmanaged resources and performs other cleanup operations before the MailService is reclaimed by garbage collection.
(Inherited from MailService.)
Public methodGetFolder(FolderNamespace)
Get the folder for the specified namespace.
(Overrides MailStoreGetFolder(FolderNamespace).)
Public methodGetFolder(SpecialFolder)
Get the specified special folder.
(Overrides MailStoreGetFolder(SpecialFolder).)
Public methodGetFolder(String, CancellationToken)
Get the folder for the specified path.
(Overrides MailStoreGetFolder(String, CancellationToken).)
Public methodGetFolderAsync
Asynchronously get the folder for the specified path.
(Overrides MailStoreGetFolderAsync(String, CancellationToken).)
Public methodGetFolders(FolderNamespace, Boolean, CancellationToken)
Get all of the folders within the specified namespace.
(Inherited from MailStore.)
Public methodGetFolders(FolderNamespace, StatusItems, Boolean, CancellationToken)
Get all of the folders within the specified namespace.
(Overrides MailStoreGetFolders(FolderNamespace, StatusItems, Boolean, CancellationToken).)
Public methodGetFoldersAsync(FolderNamespace, Boolean, CancellationToken)
Asynchronously get all of the folders within the specified namespace.
(Inherited from MailStore.)
Public methodGetFoldersAsync(FolderNamespace, StatusItems, Boolean, CancellationToken)
Asynchronously get all of the folders within the specified namespace.
(Overrides MailStoreGetFoldersAsync(FolderNamespace, StatusItems, Boolean, CancellationToken).)
Public methodGetHashCode
Serves as the default hash function.
(Inherited from Object.)
Public methodGetMetadata(IEnumerableMetadataTag, CancellationToken)
Gets the specified metadata.
(Inherited from MailStore.)
Public methodGetMetadata(MetadataTag, CancellationToken)
Gets the specified metadata.
(Overrides MailStoreGetMetadata(MetadataTag, CancellationToken).)
Public methodGetMetadata(MetadataOptions, IEnumerableMetadataTag, CancellationToken)
Gets the specified metadata.
(Overrides MailStoreGetMetadata(MetadataOptions, IEnumerableMetadataTag, CancellationToken).)
Public methodGetMetadataAsync(IEnumerableMetadataTag, CancellationToken)
Asynchronously gets the specified metadata.
(Inherited from MailStore.)
Public methodGetMetadataAsync(MetadataTag, CancellationToken)
Asynchronously gets the specified metadata.
(Overrides MailStoreGetMetadataAsync(MetadataTag, CancellationToken).)
Public methodGetMetadataAsync(MetadataOptions, IEnumerableMetadataTag, CancellationToken)
Asynchronously gets the specified metadata.
(Overrides MailStoreGetMetadataAsync(MetadataOptions, IEnumerableMetadataTag, CancellationToken).)
Public methodGetType
Gets the Type of the current instance.
(Inherited from Object.)
Public methodCode exampleIdentify
Identify the client implementation to the server and obtain the server implementation details.
Public methodIdentifyAsync
Asynchronously identify the client implementation to the server and obtain the server implementation details.
Public methodCode exampleIdle
Toggle the ImapClient into the IDLE state.
Public methodIdleAsync
Asynchronously toggle the ImapClient into the IDLE state.
Protected methodMemberwiseClone
Creates a shallow copy of the current Object.
(Inherited from Object.)
Public methodCode exampleNoOp
Ping the IMAP server to keep the connection alive.
(Overrides MailServiceNoOp(CancellationToken).)
Public methodCode exampleNoOpAsync
Asynchronously ping the IMAP server to keep the connection alive.
(Overrides MailServiceNoOpAsync(CancellationToken).)
Public methodNotify
Request the specified notification events from the IMAP server.
Public methodNotifyAsync
Asynchronously request the specified notification events from the IMAP server.
Protected methodOnAlert
Raise the alert event.
(Inherited from MailStore.)
Protected methodOnAuthenticated
Raise the authenticated event.
(Inherited from MailService.)
Protected methodOnConnected
Raise the connected event.
(Inherited from MailService.)
Protected methodOnDisconnected
Raise the disconnected event.
(Inherited from MailService.)
Protected methodOnFolderCreated
Raise the folder created event.
(Inherited from MailStore.)
Protected methodOnMetadataChanged
Raise the metadata changed event.
(Inherited from MailStore.)
Public methodSetMetadata
Sets the specified metadata.
(Overrides MailStoreSetMetadata(MetadataCollection, CancellationToken).)
Public methodSetMetadataAsync
Asynchronously gets the specified metadata.
(Overrides MailStoreSetMetadataAsync(MetadataCollection, CancellationToken).)
Public methodToString
Returns a string that represents the current object.
(Inherited from Object.)
Top
Events
  NameDescription
Public eventAlert
Occurs when a remote message store receives an alert message from the server.
(Inherited from MailStore.)
Public eventAuthenticated
Occurs when the client has been successfully authenticated.
(Inherited from MailService.)
Public eventConnected
Occurs when the client has been successfully connected.
(Inherited from MailService.)
Public eventDisconnected
Occurs when the client gets disconnected.
(Inherited from MailService.)
Public eventFolderCreated
Occurs when a folder is created.
(Inherited from MailStore.)
Public eventMetadataChanged
Occurs when metadata changes.
(Inherited from MailStore.)
Top
Remarks
The ImapClient class supports both the "imap" and "imaps" protocols. The "imap" protocol makes a clear-text connection to the IMAP server and does not use SSL or TLS unless the IMAP server supports the STARTTLS extension. The "imaps" protocol, however, connects to the IMAP server using an SSL-wrapped connection.
Examples
C#
public static void DownloadMessages ()
{
    using (var client = new ImapClient ()) {
        client.Connect ("imap.gmail.com", 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);
    }
}
Examples
C#
public static void DownloadBodyParts ()
{
    using (var client = new ImapClient ()) {
        client.Connect ("imap.gmail.com", 993, SecureSocketOptions.SslOnConnect);

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

        client.Inbox.Open (FolderAccess.ReadOnly);

        // search for messages where the Subject header contains either "MimeKit" or "MailKit"
        var query = SearchQuery.SubjectContains ("MimeKit").Or (SearchQuery.SubjectContains ("MailKit"));
        var uids = client.Inbox.Search (query);

        // fetch summary information for the search results (we will want the UID and the BODYSTRUCTURE
        // of each message so that we can extract the text body and the attachments)
        var items = client.Inbox.Fetch (uids, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure);

        foreach (var item in items) {
            // determine a directory to save stuff in
            var directory = Path.Combine (baseDirectory, item.UniqueId.ToString ());

            // create the directory
            Directory.CreateDirectory (directory);

            // IMessageSummary.TextBody is a convenience property that finds the 'text/plain' body part for us
            var bodyPart = item.TextBody;

            // download the 'text/plain' body part
            var body = (TextPart) client.Inbox.GetBodyPart (item.UniqueId, bodyPart);

            // TextPart.Text is a convenience property that decodes the content and converts the result to
            // a string for us
            var text = body.Text;

            File.WriteAllText (Path.Combine (directory, "body.txt"), text);

            // now iterate over all of the attachments and save them to disk
            foreach (var attachment in item.Attachments) {
                // download the attachment just like we did with the body
                var entity = client.Inbox.GetBodyPart (item.UniqueId, attachment);

                // attachments can be either message/rfc822 parts or regular MIME parts
                if (entity is MessagePart) {
                    var rfc822 = (MessagePart) entity;

                    var path = Path.Combine (directory, attachment.PartSpecifier + ".eml");

                    rfc822.Message.WriteTo (path);
                } else {
                    var part = (MimePart) entity;

                    // note: it's possible for this to be null, but most will specify a filename
                    var fileName = part.FileName;

                    var path = Path.Combine (directory, fileName);

                    // decode and save the content to a file
                    using (var stream = File.Create (path))
                        part.Content.DecodeTo (stream);
                }
            }
        }

        client.Disconnect (true);
    }
}
See Also