ImapFlow
repository·master·Indexed 19 days ago
https://github.com/postalsys/imapflowA modern, promise-based IMAP client library for Node.js featuring an async/await API and automatic handling of IMAP extensions such as CONDSTORE, QRESYNC, IDLE, and COMPRESS. It supports message streaming via async iterators, built-in mailbox locking for concurrent access, TypeScript, and specialized support for Gmail labels and raw searches.
What's inside imapflow
- ImapFlow is a modern, easy-to-use IMAP client library for Node.js. It features an async/await API, automatic handling of IMAP extensions (like CONDSTORE, QRESYNC, IDLE, and COMPRESS), and supports message streaming via async iterators. It also includes built-in mailbox locking for safe concurrent access, TypeScript support, proxy support (SOCKS and HTTP CONNECT), and specialized support for Gmail (labels and raw search via X-GM-EXT-1).
Install ImapFlow via npm
masterTo use ImapFlow in your Node.js project, install it using npm:
npm install imapflowQuick start with ImapFlow
masterImapFlow provides a promise-based API for interacting with IMAP servers. To use it, instantiate
ImapFlowwith connection details, call.connect(), and use mailbox locks to ensure safe concurrent access to mailboxes. Always release locks in afinallyblock to prevent deadlocks.const { ImapFlow } = require('imapflow'); const client = new ImapFlow({ host: 'imap.example.com', port: 993, secure: true, auth: { user: 'user@example.com', pass: 'password' } }); const main = async () => { await client.connect(); let lock = await client.getMailboxLock('INBOX'); try { // fetch latest message let message = await client.fetchOne(client.mailbox.exists, { source: true }); console.log(message.source.toString()); // list subjects for all messages for await (let message of client.fetch('1:*', { envelope: true })) { console.log(`${message.uid}: ${message.envelope.subject}`); } } finally { // always release the lock lock.release(); } await client.logout(); }; main().catch(console.error);Enable IMAP extensions and compression
masterImapFlow automatically negotiates several extensions during the session startup to optimize performance:
- Compression: If supported by the server and not explicitly disabled via
disableCompression: true, ImapFlow negotiates theCOMPRESScommand and useszlibDEFLATE (RFC 4978) for both incoming and outgoing data. - Automatic Extension Enabling: ImapFlow attempts to enable extensions like
CONDSTORE,UTF8=ACCEPT, andQRESYNC(ifqresync: trueis in options). It also attempts to enableIMAP4rev2by default. - IMAP4rev2 Fallback: If a server rejects
IMAP4rev2but supports other extensions, ImapFlow will retry theENABLEcommand withoutIMAP4rev2to ensure other features are not lost.
- Compression: If supported by the server and not explicitly disabled via
Handle socket timeouts and IDLE recovery
masterImapFlow uses an inactivity watchdog to monitor the socket. If a socket timeout occurs:
- During IDLE: ImapFlow attempts to recover the connection by sending a
NOOPcommand and then returning to theIDLEstate. If recovery fails, the connection is closed. - During other operations: The connection is closed immediately, and an error with
code: 'ETIMEOUT'is emitted.
This mechanism ensures that long-running
IDLEsessions are maintained or gracefully recovered if the transport becomes inactive.- During IDLE: ImapFlow attempts to recover the connection by sending a
How mailbox locks work and how to release them
masterA mailbox lock provides exclusive access to a specific mailbox path. When you call
getMailboxLock(), the request is queued. Once the previous lock is released, the next lock in the queue is granted.When a lock is granted, it returns an object containing the
pathand areleasefunction. Callingrelease()allows the next queued operation to proceed.Diagnostic Warning: If a lock is held longer than the configured
maxLockHoldTime, ImapFlow will emit a warning log indicating the lock was held for a long time. This is controlled by themaxLockHoldTimeoption in the client configuration.let lock = await client.getMailboxLock('INBOX'); // ... perform operations ... lock.release();Handle MS365/Office 365 throttling errors
masterWhen interacting with Microsoft 365 (Office 365) servers, the server may return a
BADresponse indicating rate limiting. ImapFlow detects this and parses the suggested backoff time from the response text (e.g.,"tag BAD Request is throttled. Suggested Backoff Time: 92415 milliseconds").If throttling is detected, the command will fail with an error containing:
code:ETHROTTLEthrottleReset: The number of milliseconds to wait before retrying.
Note: ImapFlow caps the automatic wait at 5 minutes to prevent connections from hanging indefinitely.
Handle connection errors and BYE reasons
masterWhen a connection is lost or closed by the server, ImapFlow may emit a
closeevent. If the server sent an untaggedBYEresponse, the error thrown during subsequent operations or the connection teardown will include areasonproperty containing the server's explanation (e.g., "Too many connections").Common error codes include:
NoConnection: The connection is not available.GREETING_TIMEOUT: Failed to receive a greeting from the server within the configuredgreetingTimeout.
Manage mailbox locks with getMailboxLock()
masterTo perform operations on a mailbox that require exclusive access (to prevent state conflicts), use
getMailboxLock(path). This returns aMailboxLockObjectwhich contains areleasefunction. You must callrelease()to free the mailbox for other operations.Important: Always use a
try...finallyblock to ensure the lock is released even if an error occurs during your operations.let lock = await client.getMailboxLock('INBOX'); try { // perform mailbox operations here } finally { // ensure the lock is released lock.release(); }Configure the ImapFlow client connection options
masterWhen instantiating
ImapFlow, you can provide an options object to configure the connection, authentication, and behavior.Connection & Security
host: Hostname of the IMAP server (defaults to'localhost').port: Port number (defaults to993ifsecure: true, otherwise143).secure: Iftrue, establishes a direct TLS connection. Iffalse, attempts to upgrade via STARTTLS.doSTARTTLS:true: Forces STARTTLS upgrade. Fails if not supported.false: Disables STARTTLS entirely.undefined(default): Attempts STARTTLS if supported; otherwise continues unencrypted.
servername: Server name for SNI or when using an IP address ashost.proxy: Proxy URL (supportshttp://,https://,socks://,socks4://,socks4a://,socks5://).connectionTimeout: Max time (ms) for DNS, proxy, and TCP/TLS handshake (default:90000).greetingTimeout: Max time (ms) to wait for server greeting (default:16000).socketTimeout: Max inactivity period (ms) before terminating connection (default:300000).
Authentication
auth.user: Username.auth.pass: Password.auth.accessToken: OAuth2 access token.auth.loginMethod: Optional method (e.g.,"LOGIN","AUTH=LOGIN","AUTH=PLAIN").auth.authzid: Authorization identity for SASL PLAIN (admin impersonation).
Advanced & Extensions
qresync: Enables QRESYNC support.disableBinary: Iftrue, ignores the BINARY extension.disableIMAP4rev2: Iftrue, opts out of IMAP4rev2 mode.maxIdleTime: Breaks and restarts IDLE every X milliseconds.missingIdleCommand: Command to use if server lacks IDLE (default:"NOOP").disableAutoIdle: Iftrue, does not start IDLE automatically.disableAutoEnable: Iftrue, does not automatically enable supported extensions.disableCompression: Iftrue, does not useCOMPRESS=DEFLATE.
Configure ImapFlow connection options
masterWhen instantiating the
ImapFlowclient, you provide anImapFlowOptionsobject to define connection, authentication, and protocol behavior.Key configuration areas include:
- Connection:
host,port,secure(usetruefor TLS), andproxy(supportshttp:,https:,socks:,socks4:,socks4a:,socks5:). - Authentication: The
authobject requiresuserand eitherpass(for regular auth) oraccessToken(for OAuth2). You can also specifyloginMethod(e.g.,'LOGIN','AUTH=LOGIN','AUTH=PLAIN') andauthzidfor SASL PLAIN delegation. - Timeouts: Control connection lifecycle with
connectionTimeout(DNS/TCP/TLS handshake),greetingTimeout, andsocketTimeout. - Protocol Extensions: Enable or disable specific behaviors like
qresync,disableCompression,disableBinary, ordisableIMAP4rev2.
const client = new ImapFlow({ host: 'imap.example.com', port: 993, secure: true, auth: { user: 'user@example.com', pass: 'your-password' } });- Connection:
Configure STARTTLS and secure connections
masterImapFlow supports two ways to establish a secure connection:
- Direct TLS: Set
secure: truein your configuration. This establishes a TLS connection immediately upon connecting. - STARTTLS: Set
doSTARTTLS: truein your configuration. This starts a plaintext connection and then upgrades it to TLS using the IMAPSTARTTLScommand.
Important Constraints:
- You cannot set both
secure: trueanddoSTARTTLS: true. Doing so will throw a misconfiguration error. - If
doSTARTTLS: trueis set and the server does not support theSTARTTLScapability, the connection attempt will fail.
- Direct TLS: Set