Chilkat.Imap Class Overview

Chilkat.Imap provides a complete client-side interface for working with IMAP mail servers. It supports secure connections, multiple authentication methods, mailbox management, message search, message retrieval, attachment handling, flags, quotas, IMAP IDLE notifications, S/MIME decryption support, proxies, and SSH tunneling.

What the Class Is Used For

Use Chilkat.Imap when an application needs to connect to an IMAP server and read, search, organize, copy, move, delete, or monitor email stored on the server. Unlike POP3, IMAP is mailbox-oriented: messages remain on the server and are accessed through folders such as INBOX, Sent, Archive, or custom folders.

Connect and Authenticate Connect over plain TCP, implicit SSL/TLS, STARTTLS, proxies, or SSH tunnels.
Select and Query Mailboxes Select folders, count messages, search by IMAP criteria, sort results, and retrieve UIDs.
Fetch Email and Attachments Download full messages, headers only, MIME source, message ranges, or specific attachments.
Manage Server State Set flags, mark messages deleted, expunge, copy, move, append, create folders, and rename folders.

Typical IMAP Workflow

  1. Configure connection settings such as Port, Ssl, StartTls, timeouts, proxy settings, or TLS requirements.
  2. Call Connect to open the TCP connection to the IMAP server.
  3. Call Login or LoginSecure. For OAuth 2.0, set AuthMethod = "XOAUTH2" and pass the access token as the password.
  4. Call SelectMailbox for read/write access, or ExamineMailbox for read-only access.
  5. Search or list messages using QueryMbx, FetchRange, FetchMsgSet, or single-message fetch methods.
  6. Process messages, attachments, flags, folders, or quotas as needed.
  7. Call Logout and Disconnect when finished.

Core Concepts

Concept Meaning Important APIs
Mailbox / Folder IMAP stores messages in named folders. The documentation uses mailbox and folder synonymously. SelectMailbox, ExamineMailbox, CreateMailbox, DeleteMailbox, RenameMailbox
Sequence Number A message’s temporary position in the selected mailbox. Sequence numbers begin at 1, not 0, and can change when messages are expunged. FetchRange, CopySequence
UID A stable server-assigned identifier for a message within a mailbox, as long as the mailbox’s UIDVALIDITY has not changed. UidValidity, UidNext, QueryMbx(..., bUid: true, ...)
Flags Server-side message state such as \Seen, \Deleted, \Answered, \Flagged, and custom flags. FetchFlags, SetFlag, SetFlags, StoreFlags, GetMailFlag
Expunge Setting the \Deleted flag does not immediately remove a message. The message is permanently removed only when expunged. Expunge, ExpungeAndClose

Major Feature Areas

Area What You Can Do Representative Members
Connection Setup Configure host, port, TLS mode, timeouts, IPv4/IPv6 preference, and local interface binding. Connect, Port, Ssl, StartTls, ConnectTimeout, ReadTimeout, ClientIpAddress, PreferIpv6
Authentication Authenticate with username/password, secure strings, XOAUTH2, NTLM, CRAM-MD5, PLAIN, or LOGIN. Login, LoginSecure, AuthMethod, AuthzId, Domain, LoggedInUser
Secure Credential Resolution Resolve credentials from Windows Credential Manager or Apple Keychain using Chilkat secret strings. EnableSecrets, Login, HttpProxyPassword, SocksPassword, SshAuthenticatePw
Mailbox Discovery and Management List folders, detect hierarchy separators, create, delete, rename, subscribe, and unsubscribe. MbxList, SeparatorChar, CreateMailbox, DeleteMailbox, RenameMailbox, Subscribe, Unsubscribe
Searching and Sorting Search the selected mailbox using IMAP search criteria, optionally returning UIDs and sorting results. QueryMbx, SearchCharset, SortCriteria, MessageSet
Fetching Messages Download headers, full messages, MIME source, ranges, chunks, or arbitrary message sets. FetchEmail, FetchRange, FetchMsgSet, FetchSingleAsMime, FetchSingleBd, FetchChunk2, PeekMode
Attachment Handling Automatically download attachments with messages, or defer attachment download and fetch them individually. AutoDownloadAttachments, FetchAttachment, FetchAttachmentBd, FetchAttachmentBytes, FetchAttachmentString, GetMailNumAttach
Flags and Message State Read or modify standard and custom IMAP flags, including seen, deleted, answered, flagged, and draft state. FetchFlags, SetFlag, SetFlags, SetMailFlag, StoreFlags, RefetchMailFlags
Copy, Move, Append, Delete Copy or move messages between mailboxes, append MIME messages to a folder, and permanently remove deleted messages. Copy, CopyMultiple, MoveMessages, AppendMail, AppendMime, Expunge
Real-Time Updates Use IMAP IDLE to receive server notifications for new messages, flag changes, expunges, and mailbox counts. IdleStart, IdleCheck, IdleDone
S/MIME and Certificates Provide certificate and private-key sources for decrypting encrypted email or using client TLS certificates. AddPfxSourceFile, AddPfxSourceData, SetDecryptCert, SetDecryptCert2, UseCertVault, SetSslClientCert
Diagnostics Inspect raw IMAP commands, responses, session logs, TLS details, and detailed failure text. LastErrorText, LastCommand, LastResponse, LastResponseCode, KeepSessionLog, SessionLog

Secure Connections and TLS

The class supports both common IMAP TLS models:

Mode Typical Port Settings Description
Implicit SSL/TLS 993 Ssl = true
StartTls = false
The TLS connection is established immediately when connecting to the server.
STARTTLS 143 Ssl = false
StartTls = true
The connection starts as plain IMAP and is upgraded to TLS using the IMAP STARTTLS command.

Additional TLS-related properties include SslProtocol, SslAllowedCiphers, RequireSslCertVerify, SslServerCertVerified, TlsVersion, TlsCipherSuite, and TlsPinSet.

Practical note: AutoFix is enabled by default and adjusts common TLS settings based on the selected port. For example, port 993 implies implicit SSL/TLS, while port 143 implies a non-SSL socket unless STARTTLS is explicitly enabled.

Searching Mailboxes

Searches are performed against the currently selected mailbox. Use QueryMbx to send IMAP search criteria and receive a MessageSet. The result can contain either UIDs or sequence numbers, depending on the bUid argument.

Search Need Recommended Approach
Stable message references Request UIDs by passing bUid = true.
Non-English search text Leave SearchCharset at its default UTF-8 unless a specific server requires different behavior.
Sorted results Set SortCriteria, but only if the IMAP server supports the SORT capability.
New message detection Use the special new-email criteria to detect messages received since the mailbox was selected or since the previous check.

Fetching Email Efficiently

Chilkat.Imap provides several ways to retrieve messages depending on how much data the application needs.

Task Use Notes
Fetch one email or header FetchEmail Can retrieve either the full email or header only.
Fetch a message range FetchRange Uses sequence numbers. The first message is sequence number 1.
Fetch a search result set FetchMsgSet Downloads messages identified by a MessageSet.
Fetch raw MIME text FetchSingleAsMime or FetchSingleAsMimeSb Useful when preserving the exact MIME source matters.
Fetch MIME as binary data FetchSingleBd Stores the complete MIME in a BinData object.
Attachment behavior: When AutoDownloadAttachments is false, message fetches can avoid downloading attachments initially. The attachment metadata is still available, and individual attachments can be downloaded later with the FetchAttachment* methods. Signed or encrypted messages are always downloaded in full.

Flags, Deletion, and Expunge

IMAP deletion is a two-step process. First, mark the message with the \Deleted flag. Later, call Expunge to permanently remove all messages marked as deleted from the selected mailbox.

Operation Method
Read flags for one message FetchFlags
Set or clear one flag on one message SetFlag
Set or clear one flag on many messages SetFlags
Set or clear multiple flags at once StoreFlags
Apply flags using the UID embedded in a fetched email object SetMailFlag
Permanently remove deleted messages Expunge or ExpungeAndClose

Advanced Capabilities

Capability Description Relevant Members
IMAP IDLE Receive near-real-time notifications for new messages, expunges, flag changes, and mailbox counts without repeatedly polling the server. IdleStart, IdleCheck, IdleDone
Threading Use the IMAP THREAD command to group related messages using algorithms such as ORDEREDSUBJECT or REFERENCES. QueryThread
Quota Management Query or set mailbox quota information when the server supports the IMAP QUOTA extension. GetQuota, GetQuotaRoot, SetQuota
Raw IMAP Commands Send custom IMAP commands directly when a server-specific feature is not wrapped by a higher-level method. SendRawCommand, SendRawCommandB, SendRawCommandC, RawCommandBd
SSH Tunneling Route IMAP traffic through an SSH tunnel, either opened by the IMAP object or shared from another Chilkat SSH/Socket object. SshOpenTunnel, SshAuthenticatePw, SshAuthenticatePk, UseSsh, UseSshTunnel
Proxy Support Connect through HTTP, SOCKS4, or SOCKS5 proxies, including proxy authentication. HttpProxyHostname, HttpProxyPort, SocksHostname, SocksVersion, SocksUsername

Debugging and Troubleshooting

The class exposes both high-level error information and low-level protocol details. When a method fails, LastErrorText should usually be the first diagnostic property checked.

Diagnostic Need Use
Detailed explanation of the last operation LastErrorText
Last raw IMAP command sent LastCommand
Last raw server response LastResponse
IMAP response code such as AUTHENTICATIONFAILED LastResponseCode
In-memory command/response transcript Set KeepSessionLog = true, then read SessionLog.
Connection health IsConnected for last-known state, CheckConnection for socket state, and Noop for an actual IMAP round trip.
Connection failures: A failed Connect call may be caused by external factors outside the IMAP protocol itself, such as firewalls, antivirus software, blocked ports, DNS issues, proxy configuration, or server-side security rules.

Best Practices

Recommendation Reason
Prefer UIDs for long-lived references. Sequence numbers can change as messages are expunged. UIDs are the safer choice when storing message references across operations or sessions.
Use PeekMode when reading should not mark messages as seen. Normal fetching can affect server-side flags. Peek mode avoids unintentionally setting \Seen.
Use headers-only or deferred attachments for large mailboxes. Setting AutoDownloadAttachments = false can greatly reduce bandwidth and memory usage.
Check server capabilities before using optional IMAP extensions. Features such as SORT, MOVE, QUOTA, IDLE, and THREAD depend on server support.
Use LastErrorText and session logging for support cases. IMAP failures often depend on the exact server command and response. The diagnostic properties expose those details.
Use secure secret storage instead of embedding passwords in code. EnableSecrets allows credentials to be resolved from Windows Credential Manager or Apple Keychain at runtime.

Summary

Chilkat.Imap is a full-featured IMAP client class for applications that need reliable server-side email access and management. It covers the complete lifecycle of IMAP work: connecting securely, authenticating, selecting folders, searching, downloading messages and attachments, managing flags, moving and copying messages, appending MIME, monitoring changes with IDLE, and troubleshooting server interactions with detailed diagnostics.