{"id":13325,"library":"imapflow","title":"IMAPFlow Client","description":"ImapFlow is a modern, promise-based IMAP client library for Node.js, designed to simplify interactions with IMAP servers without requiring deep protocol knowledge. It provides an async/await API, automatically handles various IMAP extensions (like CONDSTORE, QRESYNC, IDLE, COMPRESS), and supports message streaming, mailbox locking, and proxy configurations. The current stable version is `1.3.2`. Releases appear to be frequent, with multiple patch and minor versions released monthly, indicating active development and maintenance. Key differentiators include its automatic IMAP extension handling, built-in mailbox locking for concurrent access, and comprehensive TypeScript support, making it robust for complex email processing applications. It also features specific support for Gmail labels and raw search queries via X-GM-EXT-1.","status":"active","version":"1.3.2","language":"javascript","source_language":"en","source_url":"https://github.com/postalsys/imapflow","tags":["javascript","imap","email","mail","typescript"],"install":[{"cmd":"npm install imapflow","lang":"bash","label":"npm"},{"cmd":"yarn add imapflow","lang":"bash","label":"yarn"},{"cmd":"pnpm add imapflow","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"While CommonJS `require` works, the library promotes and ships with full TypeScript support, making ESM imports the idiomatic choice for modern Node.js projects.","wrong":"const ImapFlow = require('imapflow');","symbol":"ImapFlow","correct":"import { ImapFlow } from 'imapflow';"},{"note":"Always import types using `import type` to ensure they are stripped during compilation, preventing accidental runtime imports.","wrong":"import { ImapFlowOptions } from 'imapflow';","symbol":"ImapFlowOptions","correct":"import type { ImapFlowOptions } from 'imapflow';"},{"note":"Common error class provided by the library for specific IMAP-related issues.","symbol":"ImapFlowError","correct":"import { ImapFlowError } from 'imapflow';"}],"quickstart":{"code":"import { ImapFlow } from 'imapflow';\n\nconst client = new ImapFlow({\n    host: 'imap.example.com',\n    port: 993,\n    secure: true,\n    auth: {\n        user: 'user@example.com',\n        pass: process.env.IMAP_PASSWORD ?? '' // Use environment variable for security\n    }\n});\n\nconst main = async () => {\n    await client.connect();\n\n    let lock = await client.getMailboxLock('INBOX');\n    try {\n        // Fetch the latest message and print its source\n        let message = await client.fetchOne(client.mailbox.exists, { source: true });\n        if (message?.source) {\n          console.log('Latest message source:', message.source.toString());\n        } else {\n          console.log('No messages found in INBOX.');\n        }\n\n        // List subjects for all messages using an async iterator\n        console.log('\\nSubjects of all messages:');\n        for await (let msg of client.fetch('1:*', { envelope: true })) {\n            console.log(`${msg.uid}: ${msg.envelope?.subject || '(No Subject)'}`);\n        }\n    } finally {\n        // Ensure the mailbox lock is always released\n        lock.release();\n    }\n\n    await client.logout();\n    console.log('\\nDisconnected from IMAP server.');\n};\n\nmain().catch(error => {\n    console.error('An error occurred:', error);\n    // Ensure client disconnects on error if still connected\n    if (client.clientConnected) {\n        client.logout().catch(console.error);\n    }\n});","lang":"typescript","description":"This quickstart demonstrates connecting to an IMAP server, acquiring a mailbox lock, fetching the latest message's raw source, and iterating through all messages to log their subjects, ensuring proper resource cleanup."},"warnings":[{"fix":"Wrap operations requiring a mailbox lock in a `try...finally` block to guarantee `lock.release()` is called, even if errors occur.","message":"Always ensure to release mailbox locks obtained via `client.getMailboxLock()` using a `finally` block. Failing to release a lock can lead to resource exhaustion, preventing further operations on the mailbox until the connection is closed or timed out, potentially causing deadlocks or hangs.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Review the 'Configuration' and 'Quick Start' guides on imapflow.com, especially for services like Gmail, Outlook, and Yahoo, to ensure correct options and practices are applied.","message":"ImapFlow handles various IMAP extensions automatically, but misconfiguration or server-specific quirks (e.g., non-standard Gmail behavior) can still lead to unexpected results. Always consult the official documentation for advanced features or specific server integrations like Gmail.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Upgrade to the latest `imapflow` version (>=1.3.0) to benefit from fixes for unhandled promise rejections. Implement comprehensive error handling around `client.connect()`, `client.logout()`, and `IDLE` operations.","message":"Earlier versions might have specific race conditions or unhandled promise rejections during connection close or IDLE recovery, as indicated by recent bug fixes in `v1.2.13` and `v1.2.12`. While patched, always handle connection and disconnection errors robustly.","severity":"gotcha","affected_versions":"<1.2.13"},{"fix":"When performing complex search queries, especially with `OR` or `NOT` conditions, ensure they are properly parenthesized according to RFC 3501. Upgrade to `v1.2.16` or newer to get automatic parenthesization for compound conditions.","message":"Search conditions involving compound OR/NOT might require explicit parentheses for correct interpretation by the IMAP server (RFC 3501), as highlighted by a fix in `v1.2.16`.","severity":"gotcha","affected_versions":"<1.2.16"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Verify credentials. For Gmail, ensure 'Less secure app access' is enabled or use an App Password if 2FA is on. Double-check `auth.user` and `auth.pass` in the ImapFlow client configuration.","cause":"Incorrect username, password, or application-specific password (for services like Gmail).","error":"Error: Command 'LOGIN' failed: [AUTHENTICATIONFAILED] Authentication failed."},{"fix":"Use `client.listMailboxes()` to get a list of available mailboxes and verify the correct name. IMAP mailbox names are case-sensitive on some servers.","cause":"Attempting to select a mailbox that does not exist or is misspelled.","error":"Error: Command 'SELECT' failed: [CANNOT SELECT] Folder not found."},{"fix":"Ensure `new ImapFlow(...)` is called and `await client.connect()` successfully completes before performing any IMAP operations like `fetchOne` or `fetch`.","cause":"The `client` object was not properly initialized or `await client.connect()` was not called before attempting operations.","error":"TypeError: client.fetchOne is not a function"},{"fix":"Always `await` ImapFlow's promise-returning methods or attach a `.catch()` handler to them to prevent unhandled promise rejections. Wrap your main async logic in a function and call it with `.catch(console.error)`.","cause":"An asynchronous operation (e.g., `client.connect()`, `client.fetch()`) was not `await`ed, or its returned Promise was not chained with `.catch()` for error handling.","error":"Promise { <pending> } (unhandled promise rejection)"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null}