### Complete ImapFlow Example Source: https://imapflow.com/docs/getting-started/quick-start A full example demonstrating connection, listing mailboxes, selecting INBOX, fetching recent messages with envelope and flags, and logging out. ```javascript const { ImapFlow } = require('imapflow'); const client = new ImapFlow({ host: 'imap.example.com', port: 993, secure: true, auth: { user: 'user@example.com', pass: 'your-password' } }); async function main() { // Connect await client.connect(); console.log('Connected'); // List mailboxes let mailboxes = await client.list(); console.log('Mailboxes:', mailboxes.map(m => m.path).join(', ')); // Select INBOX let lock = await client.getMailboxLock('INBOX'); try { console.log(`INBOX has ${client.mailbox.exists} messages`); if (client.mailbox.exists > 0) { // Fetch latest 10 messages (or all if less than 10) let messages = await client.fetchAll('*:-10', { envelope: true, flags: true }); for (let message of messages) { const seen = message.flags.has('\Seen') ? '' : '[UNREAD] '; console.log(`${seen}${message.uid}: ${message.envelope.subject}`); } } } finally { lock.release(); } // Logout await client.logout(); console.log('Disconnected'); } main().catch(console.error); ``` -------------------------------- ### Complete ImapFlow Configuration Example Source: https://imapflow.com/docs/guides/configuration A comprehensive example demonstrating how to configure ImapFlow with various options including connection details, authentication, TLS settings, timeouts, client identification, IDLE behavior, and extensions. ```javascript const { ImapFlow } = require('imapflow'); const client = new ImapFlow({ // Connection host: 'imap.example.com', port: 993, secure: true, servername: 'mail.example.com', // Authentication auth: { user: 'user@example.com', pass: 'password' }, // TLS tls: { rejectUnauthorized: true, minVersion: 'TLSv1.2' }, // Proxy (optional) // proxy: 'socks://proxy.example.com:1080', // Logging (uses Pino by default, set to false to disable) // logger: false, // Timeouts connectionTimeout: 90000, greetingTimeout: 16000, socketTimeout: 300000, // Client identification clientInfo: { name: 'My Email Client', version: '1.0.0' }, // IDLE behavior disableAutoIdle: false, maxIdleTime: 300000, // Extensions disableCompression: false, disableBinary: false, qresync: false }); ``` -------------------------------- ### Install ImapFlow with npm Source: https://imapflow.com/docs Install the ImapFlow library using npm. This is the first step to using ImapFlow in your Node.js project. ```bash npm install imapflow ``` -------------------------------- ### Install ImapFlow with yarn Source: https://imapflow.com/docs/getting-started/installation Use this command to install ImapFlow if you are using yarn as your package manager. ```bash yarn add imapflow ``` -------------------------------- ### Install ImapFlow with npm Source: https://imapflow.com/docs/getting-started/installation Use this command to install ImapFlow if you are using npm as your package manager. ```bash npm install imapflow ``` -------------------------------- ### Complete ImapFlow Example Source: https://imapflow.com/docs/guides/basic-usage Connect to an IMAP server, list mailboxes, and fetch the latest message from INBOX. Ensure locks are released and errors are handled. ```javascript const { ImapFlow } = require('imapflow'); async function main() { const client = new ImapFlow({ host: 'imap.example.com', port: 993, secure: true, auth: { user: 'user@example.com', pass: 'password' }, logger: false // Disable logging for cleaner output }); // Handle connection events client.on('error', err => { console.error('Connection error:', err); }); client.on('close', () => { console.log('Connection closed'); }); try { // Connect await client.connect(); console.log('Connected to', client.host); // List mailboxes let mailboxes = await client.list(); console.log('Available mailboxes:'); for (let mailbox of mailboxes) { console.log(` ${mailbox.path} ${mailbox.specialUse || ''}`); } // Work with INBOX let lock = await client.getMailboxLock('INBOX'); try { console.log(` INBOX has ${client.mailbox.exists} messages`); if (client.mailbox.exists > 0) { // Fetch latest message let message = await client.fetchOne('*', { envelope: true, flags: true }); console.log(' Latest message:'); console.log(' Subject:', message.envelope.subject); console.log(' From:', message.envelope.from[0]?.address); console.log(' Date:', message.envelope.date); console.log(' Read:', message.flags.has('\Seen')); } } finally { lock.release(); } // Logout await client.logout(); console.log(' Disconnected'); } catch (err) { console.error('Error:', err); client.close(); } } main(); ``` -------------------------------- ### Verify ImapFlow Installation Source: https://imapflow.com/docs/getting-started/installation Run this command after installation to check if ImapFlow is correctly installed and to view its version. ```bash npm list imapflow ``` -------------------------------- ### Basic ImapFlow Usage Example Source: https://imapflow.com/docs Connect to an IMAP server, select a mailbox, fetch the latest message, and log out. Ensure you have the necessary credentials and server details. ```javascript 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 () => { // Connect and authenticate await client.connect(); // Select a mailbox let lock = await client.getMailboxLock('INBOX'); try { // Fetch latest message let message = await client.fetchOne('*', { envelope: true, source: true }); console.log(message.envelope.subject); } finally { lock.release(); } // Logout await client.logout(); }; main().catch(console.error); ``` -------------------------------- ### Initialize ImapFlow Client with TypeScript Source: https://imapflow.com/docs/getting-started/installation Example of how to import and initialize the ImapFlow client with TypeScript. Ensure your Node.js version is 20.0 or higher. ```typescript import { ImapFlow } from 'imapflow'; const client: ImapFlow = new ImapFlow({ host: 'imap.example.com', port: 993, secure: true, auth: { user: 'user@example.com', pass: 'password' } }); ``` -------------------------------- ### Gmail Labels Example Source: https://imapflow.com/docs/examples/fetching-messages Demonstrates how to work with Gmail labels, including fetching messages with labels, adding, and removing them. Requires Gmail host, port, and OAuth2 authentication. Labels are managed using `useLabels: true` option. ```javascript async function gmailLabelsExample() { const client = new ImapFlow({ host: 'imap.gmail.com', port: 993, secure: true, auth: { user: 'your.email@gmail.com', accessToken: 'your-oauth2-token' // Gmail requires OAuth2 } }); await client.connect(); let lock = await client.getMailboxLock('[Gmail]/All Mail'); try { // Fetch messages with labels let messages = await client.fetchAll('1:10', { envelope: true, labels: true }); for (let message of messages) { console.log('Subject:', message.envelope.subject); console.log('Labels:', message.labels ? Array.from(message.labels) : 'none'); } // Add a Gmail label — labels are managed via the regular flag methods // by passing `useLabels: true` in the options. await client.messageFlagsAdd('12345', ['MyLabel'], { uid: true, useLabels: true }); // Remove a Gmail label await client.messageFlagsRemove('12345', ['OldLabel'], { uid: true, useLabels: true }); // Search using Gmail's raw syntax let important = await client.search({ gmraw: 'is:important has:attachment' }, { uid: true }); console.log(`Found ${important.length} important messages with attachments`); } finally { lock.release(); } await client.logout(); } ``` -------------------------------- ### listTree(options) Source: https://imapflow.com/docs/api/imapflow-client Gets mailboxes organized as a tree structure. Options are the same as the `list()` method. ```APIDOC ## listTree(options) ### Description Gets mailboxes organized as a tree structure. Options are the same as the `list()` method. ### Parameters #### Query Parameters * `options` (Object) - Same as list() ### Returns Promise ### Example ```javascript let tree = await client.listTree(); function printTree(node, indent = '') { if (node.path) { console.log(indent + node.name); } if (node.folders) { for (let folder of node.folders) { printTree(folder, indent + ' '); } } } printTree(tree); ``` ``` -------------------------------- ### Search and Fetch Messages Source: https://imapflow.com/docs/guides/fetching-messages Combine search criteria with fetching operations to retrieve specific messages. This example demonstrates searching for unseen messages from a particular sender and then fetching their subjects. ```javascript let lock = await client.getMailboxLock('INBOX'); try { // Search for unseen messages from a specific sender let uids = await client.search({ seen: false, from: 'important@example.com' }, { uid: true }); console.log(`Found ${uids.length} matching messages`); // Fetch the found messages if (uids.length > 0) { let messages = await client.fetchAll(uids, { envelope: true, bodyStructure: true }, { uid: true }); for (let message of messages) { console.log('Subject:', message.envelope.subject); } } } finally { lock.release(); } ``` -------------------------------- ### Find Old Messages to Archive Source: https://imapflow.com/docs/guides/searching Locate old messages that have been read and are candidates for archiving. This example finds messages older than six months that have been marked as seen. ```javascript let sixMonthsAgo = new Date(); sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6); let uids = await client.search({ before: sixMonthsAgo, seen: true }, { uid: true }); ``` -------------------------------- ### Gmail-Specific Search with Raw Syntax Source: https://imapflow.com/docs/guides/fetching-messages Utilize Gmail's raw search syntax for advanced filtering. This example shows how to search for messages with attachments that are larger than 5MB. ```javascript // Use Gmail's raw search syntax let uids = await client.search({ gmraw: 'has:attachment larger:5M' }, { uid: true }); ``` -------------------------------- ### Nested Complex Queries Source: https://imapflow.com/docs/guides/searching Construct complex search queries by combining OR, NOT, and AND logic. This example finds messages from Alice or Bob that are not flagged and are unseen. ```javascript // (From Alice OR From Bob) AND NOT flagged AND unseen let uids = await client.search({ or: [ { from: 'alice@example.com' }, { from: 'bob@example.com' } ], not: { flagged: true }, seen: false }, { uid: true }); ``` -------------------------------- ### Comprehensive Error Handling Source: https://imapflow.com/docs/guides/basic-usage Implement robust error handling for IMAP operations using try/catch blocks. This example shows how to catch general errors and check for specific error properties like 'authenticationFailed', 'code', and 'responseStatus'. ```javascript async function main() { try { await client.connect(); let lock = await client.getMailboxLock('INBOX'); try { let message = await client.fetchOne('*', { envelope: true }); console.log(message.envelope.subject); } finally { lock.release(); } await client.logout(); } catch (err) { console.error('IMAP Error:', err.message); console.error('Error code:', err.code); // Handle specific errors if (err.authenticationFailed) { console.error('Invalid credentials'); } if (err.code === 'NoConnection') { console.error('Not connected to server'); } if (err.responseStatus === 'NO') { console.error('Server rejected the command'); } } } ``` -------------------------------- ### Complex AND Search Source: https://imapflow.com/docs/guides/searching Combine multiple search criteria using AND logic by including them in a single search object. This example searches for unseen messages from a specific sender that are larger than 10KB. ```javascript // Unseen AND from specific sender AND larger than 10KB let uids = await client.search({ seen: false, from: 'boss@example.com', larger: 10 * 1024 }, { uid: true }); ``` -------------------------------- ### Fetch Full RFC822 Message Source Source: https://imapflow.com/docs/guides/fetching-messages Get the complete raw message source in RFC822 format. Useful for debugging or detailed analysis. ```javascript let message = await client.fetchOne('*', { source: true }); console.log('Raw message:', message.source.toString()); ``` -------------------------------- ### getQuota(path) Source: https://imapflow.com/docs/api/imapflow-client Gets quota information for a mailbox. Defaults to 'INBOX' if no path is provided. Returns false if the server does not support the QUOTA extension or the path does not exist. ```APIDOC ## getQuota(path) ### Description Gets quota information for a mailbox. Defaults to `INBOX` if no path is provided. ### Parameters #### Path Parameters * `path` (String) - Optional mailbox path (defaults to `'INBOX'`) ### Returns Promise - `false` if the server does not support the QUOTA extension or the path does not exist ### Example ```javascript let quota = await client.getQuota('INBOX'); if (quota && quota.storage) { console.log(`Used: ${quota.storage.used}/${quota.storage.limit} bytes`); } ``` ``` -------------------------------- ### Fetch Partial Message Source Source: https://imapflow.com/docs/guides/fetching-messages Retrieve a portion of the raw message source, specified by start position and maximum length. Efficient for large messages. ```javascript let message = await client.fetchOne('*', { source: { start: 0, maxLength: 1000 // First 1000 bytes only } }); ``` -------------------------------- ### Fetch Messages from Specific Sender Source: https://imapflow.com/docs/examples/fetching-messages Searches for and fetches messages from a specified sender email address. This example demonstrates using the `search` method with a `from` parameter and then `fetchAll` to retrieve the message envelopes. Requires an active client connection and mailbox lock. ```javascript async function fetchFromSender(senderEmail) { await client.connect(); let lock = await client.getMailboxLock('INBOX'); try { // Search for messages from specific sender let uids = await client.search({ from: senderEmail }, { uid: true }); console.log(`Found ${uids.length} messages from ${senderEmail}`); // Use fetchAll for safety when you might want to process further let messages = await client.fetchAll(uids, { envelope: true }, { uid: true }); for (let message of messages) { console.log(`${message.uid}: ${message.envelope.subject}`); } } finally { lock.release(); } await client.logout(); } fetchFromSender('important@example.com').catch(console.error); ``` -------------------------------- ### Fetch All Messages and Add Flags - IMAPFlow Client Source: https://imapflow.com/docs/api/imapflow-client Fetches all messages within a specified range and returns them as an array. This method is safer for processing but consumes more memory. The example then adds '\Seen' flags to each fetched message. ```javascript let messages = await client.fetchAll('1:100', { envelope: true }); for (let message of messages) { await client.messageFlagsAdd(message.uid, ['\Seen'], { uid: true }); } ``` -------------------------------- ### Fetch Messages with Envelope and Flags - IMAPFlow Client Source: https://imapflow.com/docs/api/imapflow-client Fetches messages from the currently selected mailbox using an async iterator. Avoid running other IMAP commands within the fetch loop to prevent deadlocks. This example retrieves envelope and flags for messages in the range '1:*'. ```javascript for await (let message of client.fetch('1:*', { envelope: true, flags: true })) { console.log(message.uid, message.envelope.subject); } ``` -------------------------------- ### Fetch Unread Messages Source: https://imapflow.com/docs/examples/fetching-messages Fetches all unread messages from the INBOX, marks them as seen, and processes their details. It's crucial to use `fetchAll` when processing multiple messages to avoid fetch loop restrictions. This example requires an active client connection and mailbox lock. ```javascript async function fetchUnread() { await client.connect(); let lock = await client.getMailboxLock('INBOX'); try { // Search for unseen messages let unseenUids = await client.search({ seen: false }, { uid: true }); console.log(`Found ${unseenUids.length} unread messages`); if (unseenUids.length === 0) { return; } // Use fetchAll to get all messages so we can process them after let messages = await client.fetchAll(unseenUids, { envelope: true, source: true }, { uid: true }); for (let message of messages) { console.log(' ---'); console.log('UID:', message.uid); console.log('Subject:', message.envelope.subject); console.log('From:', message.envelope.from[0]?.address); // Now we can safely mark as seen await client.messageFlagsAdd(message.uid, ['\Seen'], { uid: true }); } } finally { lock.release(); } await client.logout(); } fetchUnread().catch(console.error); ``` -------------------------------- ### connect() Source: https://imapflow.com/docs/api/imapflow-client Establishes connection to the IMAP server and authenticates the client. ```APIDOC ## connect() ### Description Establishes connection to the IMAP server and authenticates. ### Returns Promise ### Example ```javascript await client.connect(); console.log('Connected and authenticated'); ``` ``` -------------------------------- ### Constructor Source: https://imapflow.com/docs/api/imapflow-client Creates a new IMAP client instance with configurable options for connection, authentication, and behavior. ```APIDOC ## new ImapFlow(options) ### Description Creates a new IMAP client instance. ### Parameters * `options` (Object) - Configuration options * `host` (String) - IMAP server hostname (required, defaults to `localhost`) * `port` (Number) - Port number (defaults to 993 if `secure: true`, otherwise 110) * `secure` (Boolean) - If `true`, establishes the connection directly over TLS. If `false` (default), uses plain TCP and may upgrade via STARTTLS unless `doSTARTTLS: false` is set. Setting `port: 993` without `secure` implies `secure: true`. * `doSTARTTLS` (Boolean) - Force STARTTLS behavior. `true` requires STARTTLS upgrade (fails if not supported), `false` disables STARTTLS entirely. Cannot be combined with `secure: true`. * `servername` (String) - Servername for SNI (for IP addresses or custom names) * `auth` (Object) - Authentication credentials * `user` (String) - Username * `pass` (String) - Password * `accessToken` (String) - OAuth2 access token (alternative to pass) * `loginMethod` (String) - Optional override: 'LOGIN', 'AUTH=LOGIN', or 'AUTH=PLAIN' * `authzid` (String) - Authorization identity for SASL PLAIN (admin impersonation) * `logger` (Object|Boolean) - Logger instance or false to disable * `tls` (Object) - Additional TLS options * `proxy` (String) - Proxy URL (socks://, socks4://, socks5://, http://) * `clientInfo` (Object) - Client identification for ID extension * `disableAutoIdle` (Boolean) - Disable automatic IDLE mode * `disableCompression` (Boolean) - Disable COMPRESS=DEFLATE * `disableBinary` (Boolean) - Disable BINARY extension * `disableAutoEnable` (Boolean) - Do not auto-enable extensions * `qresync` (Boolean) - Enable QRESYNC support * `maxIdleTime` (Number) - Restart IDLE after this many ms * `missingIdleCommand` (String) - Command if IDLE unsupported: 'NOOP', 'SELECT', or 'STATUS' * `connectionTimeout` (Number) - Connection timeout in ms (default: 90000) * `greetingTimeout` (Number) - Greeting timeout in ms (default: 16000) * `socketTimeout` (Number) - Socket inactivity timeout in ms (default: 300000) * `emitLogs` (Boolean) - Emit log events instead of logging * `logRaw` (Boolean) - Log raw socket data in base64 * `verifyOnly` (Boolean) - Connect and disconnect immediately * `includeMailboxes` (Boolean) - With verifyOnly, also list mailboxes * `expungeHandler` (Function) - Custom EXPUNGE event handler * `id` (String) - Custom instance ID for logs ### Returns ImapFlow instance ### Example ```javascript const client = new ImapFlow({ host: 'imap.example.com', port: 993, secure: true, auth: { user: 'user@example.com', pass: 'password' } }); ``` ``` -------------------------------- ### Get Mailbox Structure as a Tree Source: https://imapflow.com/docs/api/imapflow-client Retrieve mailboxes organized in a hierarchical tree structure. Useful for navigating nested folders. ```javascript let tree = await client.listTree(); function printTree(node, indent = '') { if (node.path) { console.log(indent + node.name); } if (node.folders) { for (let folder of node.folders) { printTree(folder, indent + ' '); } } } printTree(tree); ``` -------------------------------- ### upgradeToSTARTTLS() Source: https://imapflow.com/docs/api/imapflow-client Upgrades the current connection to TLS using STARTTLS. This is typically called automatically when `secure: false` and the server supports STARTTLS. ```APIDOC ## upgradeToSTARTTLS() ### Description Upgrades the current connection to TLS using STARTTLS. This is typically called automatically when `secure: false` and the server supports STARTTLS. ### Returns Promise - Returns `true` if upgrade succeeded, `false` if already using TLS or STARTTLS not supported. ### Example ```javascript // Manual STARTTLS upgrade (usually not needed) const upgraded = await client.upgradeToSTARTTLS(); if (upgraded) { console.log('Connection upgraded to TLS'); } ``` ``` -------------------------------- ### Create ImapFlow Client Instance Source: https://imapflow.com/docs/getting-started/quick-start Import the ImapFlow class and create a new client instance with your server credentials. Disable logging by setting 'logger' to false; omit it to use the default Pino logger. ```javascript const { ImapFlow } = require('imapflow'); const client = new ImapFlow({ host: 'imap.example.com', port: 993, secure: true, auth: { user: 'user@example.com', pass: 'your-password' }, logger: false // Disable logging. Omit to use the default Pino logger. }); ``` -------------------------------- ### Get Connection Statistics Source: https://imapflow.com/docs/api/imapflow-client Retrieves byte counters for sent and received data on the current connection. Optionally reset the counters after reading. ```javascript let { sent, received } = client.stats(); console.log(`Sent ${sent} bytes, received ${received} bytes`); ``` -------------------------------- ### Get Mailbox Tree Structure Source: https://imapflow.com/docs/guides/mailbox-management Fetches mailboxes organized hierarchically as a tree structure. The output is a JSON string representation of the tree. ```javascript let tree = await client.listTree(); console.log(JSON.stringify(tree, null, 2)); ``` -------------------------------- ### Find Large Attachments Source: https://imapflow.com/docs/guides/searching Search for messages that are likely to contain large attachments by using the `larger` criterion. This example finds messages over 500KB. ```javascript // Messages likely to have attachments (> 500KB) let uids = await client.search({ larger: 500 * 1024 }, { uid: true }); ``` -------------------------------- ### Enable TLS for Secure Connection Source: https://imapflow.com/docs/guides/configuration Use TLS for the connection. If true, establishes the connection directly over TLS. If false, a plain connection is used first and upgraded to TLS via STARTTLS if possible. ```javascript { secure: true // Use TLS (recommended) } ``` -------------------------------- ### Connect to IMAP Server Source: https://imapflow.com/docs/getting-started/quick-start Use async/await to connect to the IMAP server and authorize the client. Handles connection errors. ```javascript async function main() { // Wait until client connects and authorizes await client.connect(); console.log('Connected to IMAP server'); } main().catch(err => { console.error('Connection error:', err); }); ``` -------------------------------- ### HTTP CONNECT Proxy Configuration Source: https://imapflow.com/docs/guides/configuration Configure an HTTP CONNECT proxy for the connection. ```javascript { proxy: 'http://proxy.example.com:8080' } ``` -------------------------------- ### Instantiate ImapFlow Client Source: https://imapflow.com/docs/guides/basic-usage Create a new ImapFlow client instance with connection details and authentication credentials. Ensure host, port, and auth are correctly configured. ```javascript const { ImapFlow } = require('imapflow'); const client = new ImapFlow({ host: 'imap.example.com', port: 993, secure: true, auth: { user: 'user@example.com', pass: 'password' } }); ``` -------------------------------- ### Accepting Self-Signed Certificates (Testing Only) Source: https://imapflow.com/docs/guides/configuration Configure to accept self-signed certificates. Warning: Only use this for testing or development environments. ```javascript { tls: { rejectUnauthorized: false } } ``` -------------------------------- ### Upgrade Connection to TLS with STARTTLS Source: https://imapflow.com/docs/api/imapflow-client Manually upgrade an existing connection to TLS using STARTTLS. This is usually handled automatically by the client when `secure: false` and the server supports it. ```javascript const upgraded = await client.upgradeToSTARTTLS(); if (upgraded) { console.log('Connection upgraded to TLS'); } ``` -------------------------------- ### Fetch Message Flags and Flag Color Source: https://imapflow.com/docs/guides/fetching-messages Get message flags like \Seen or \Flagged, and any associated flag color. Helps in understanding message status. ```javascript let message = await client.fetchOne('*', { flags: true }); console.log('Flags:', message.flags); console.log('Is seen?', message.flags.has('\Seen')); console.log('Is flagged?', message.flags.has('\Flagged')); console.log('Flag color:', message.flagColor); // e.g., 'red', 'yellow' ``` -------------------------------- ### Fetch Messages Using Query Macros Source: https://imapflow.com/docs/guides/fetching-messages Utilize predefined macros (FAST, ALL, FULL) for common sets of fetch options. Simplifies common fetch requests. ```javascript // FAST macro: flags, internalDate, size let message = await client.fetchOne('*', { fast: true }); // ALL macro: flags, internalDate, size, envelope let message = await client.fetchOne('*', { all: true }); // FULL macro: flags, internalDate, size, envelope, bodyStructure let message = await client.fetchOne('*', { full: true }); ``` -------------------------------- ### status(path, query) Source: https://imapflow.com/docs/api/imapflow-client Gets mailbox status without selecting it. Allows fetching specific status items like message counts, UID validity, and modseq. ```APIDOC ## status(path, query) ### Description Gets mailbox status without selecting it. ### Parameters #### Path Parameters * `path` (String) - Mailbox path #### Query Parameters * `query` (Object) - Status items to fetch * `messages` (Boolean) - Total message count * `recent` (Boolean) - Recent message count * `uidNext` (Boolean) - Next UID value * `uidValidity` (Boolean) - UIDVALIDITY value * `unseen` (Boolean) - Unseen message count * `highestModseq` (Boolean) - Highest modseq value ### Returns Promise ### Example ```javascript let status = await client.status('INBOX', { messages: true, unseen: true, highestModseq: true }); console.log(`${status.unseen}/${status.messages} unseen`); ``` ``` -------------------------------- ### Verify Credentials Only Source: https://imapflow.com/docs/guides/configuration Configure the client to connect, authenticate, and immediately disconnect. This is useful for testing credentials without performing other operations. ```javascript { verifyOnly: true } ``` -------------------------------- ### Get Mailbox Quota Source: https://imapflow.com/docs/guides/mailbox-management Retrieves the quota information for a mailbox. Returns false if the server does not support the QUOTA extension or the mailbox does not exist. Handles both storage and message quotas. ```javascript let quota = await client.getQuota(); if (!quota) { console.log('Quota not supported'); } else { if (quota.storage) { console.log('Storage:', quota.storage.used, '/', quota.storage.limit); } if (quota.messages) { console.log('Messages:', quota.messages.used, '/', quota.messages.limit); } } ``` -------------------------------- ### Create ImapFlow Client Instance Source: https://imapflow.com/docs/api/imapflow-client Instantiate the ImapFlow client with connection and authentication options. Ensure 'host', 'port', and 'secure' are correctly configured for your IMAP server. Authentication can be done using username/password or an OAuth2 access token. ```javascript const client = new ImapFlow({ host: 'imap.example.com', port: 993, secure: true, auth: { user: 'user@example.com', pass: 'password' } }); ``` -------------------------------- ### SOCKS Proxy with Authentication Source: https://imapflow.com/docs/guides/configuration Configure a SOCKS proxy with authentication credentials. ```javascript { proxy: 'socks://username:password@proxy.example.com:1080' } ``` -------------------------------- ### Basic ImapFlow Client Configuration Source: https://imapflow.com/docs/guides/configuration The minimal configuration requires server details and authentication credentials. ```javascript const client = new ImapFlow({ host: 'imap.example.com', port: 993, secure: true, auth: { user: 'user@example.com', pass: 'password' } }); ``` -------------------------------- ### Get Mailbox Status - IMAPFlow Client Source: https://imapflow.com/docs/api/imapflow-client Retrieves mailbox status information like message counts and highest modseq without selecting the mailbox. Specify the desired status items in the query object. ```javascript let status = await client.status('INBOX', { messages: true, unseen: true, highestModseq: true }); console.log(`${status.unseen}/${status.messages} unseen`); ``` -------------------------------- ### Connect to IMAP Server Source: https://imapflow.com/docs/api/imapflow-client Establishes a connection to the IMAP server and performs authentication. This method should be called before any other operations. ```javascript await client.connect(); console.log('Connected and authenticated'); ``` -------------------------------- ### Basic Username and Password Authentication Source: https://imapflow.com/docs/guides/configuration Configure authentication using username and password. ```javascript { auth: { user: 'user@example.com', pass: 'password' } } ``` -------------------------------- ### Fetch Single Message with Envelope and Source - IMAPFlow Client Source: https://imapflow.com/docs/api/imapflow-client Fetches a single message, identified by its sequence number or UID. The '*' wildcard fetches the latest message. This example retrieves the envelope and source of the latest message. ```javascript let message = await client.fetchOne('*', { envelope: true, source: true }); if (message) { console.log(message.envelope.subject); } ``` -------------------------------- ### Fetch Latest Message with Async/Await Source: https://imapflow.com/docs/guides/basic-usage Demonstrates fetching the latest message using async/await syntax, which is the recommended approach for handling promises. ```javascript async function fetchLatestMessage() { await client.connect(); let lock = await client.getMailboxLock('INBOX'); try { let message = await client.fetchOne('*', { envelope: true }); return message; } finally { lock.release(); } } ``` -------------------------------- ### Download Single Attachment Source: https://imapflow.com/docs/examples/fetching-messages Downloads a single attachment from a specified message UID and part. Uses `client.download` to get a stream of the attachment content and `pipeline` to save it to a file. Ensure `fs`, `path`, and `stream/promises` are imported. ```javascript const fs = require('fs'); const path = require('path'); const { pipeline } = require('stream/promises'); async function downloadAttachment(messageUid, attachmentPart, savePath) { await client.connect(); let lock = await client.getMailboxLock('INBOX'); try { // Download the attachment as stream let { meta, content } = await client.download( messageUid, attachmentPart, { uid: true } ); console.log('Downloading:', meta.filename || 'attachment'); console.log('Content-Type:', meta.contentType); console.log('Expected size:', meta.expectedSize, 'bytes'); // Stream to file await pipeline(content, fs.createWriteStream(savePath)); console.log(`Saved to ${savePath}`); } finally { lock.release(); } await client.logout(); } // Example: Download part '2' of message UID 123 downloadAttachment('123', '2', './attachment.pdf') .catch(console.error); ``` -------------------------------- ### list(options) Source: https://imapflow.com/docs/api/imapflow-client Lists available mailboxes. Supports requesting mailbox status and special-use folder hints. ```APIDOC ## list(options) ### Description Lists available mailboxes. Supports requesting mailbox status and special-use folder hints. ### Parameters #### Query Parameters * `options` (Object) - Optional settings * `statusQuery` (Object) - Request status for each mailbox * `messages` (Boolean) - Include message count * `recent` (Boolean) - Include recent count * `uidNext` (Boolean) - Include next UID * `uidValidity` (Boolean) - Include UIDVALIDITY * `unseen` (Boolean) - Include unseen count * `highestModseq` (Boolean) - Include highest modseq * `specialUseHints` (Object) - Hints for special-use folders * `sent` (String) - Path to Sent folder * `trash` (String) - Path to Trash folder * `junk` (String) - Path to Junk folder * `drafts` (String) - Path to Drafts folder ### Returns Promise> ### Example ```javascript let mailboxes = await client.list(); for (let mailbox of mailboxes) { console.log(mailbox.path, mailbox.specialUse || ''); } // With status query let mailboxes = await client.list({ statusQuery: { messages: true, unseen: true } }); ``` ``` -------------------------------- ### Connect to IMAP Server Source: https://imapflow.com/docs/guides/basic-usage Establish a connection to the IMAP server before performing any operations. Access server capabilities after a successful connection. ```javascript await client.connect(); console.log('Connected successfully'); console.log('Server capabilities:', client.capabilities); ``` -------------------------------- ### fetchAll(range, query, options) Source: https://imapflow.com/docs/api/imapflow-client Fetches all messages within a specified range and returns them as an array. This method is safer for processing but consumes more memory. ```APIDOC ## fetchAll(range, query, options) ### Description Fetches all messages and returns an array. Safer for processing but uses more memory. ### Parameters Same as fetch() ### Returns Promise> ### Example ```javascript let messages = await client.fetchAll('1:100', { envelope: true }); for (let message of messages) { await client.messageFlagsAdd(message.uid, ['\Seen'], { uid: true }); } ``` ``` -------------------------------- ### Fetch Latest Message Source: https://imapflow.com/docs/examples/fetching-messages Connects to an IMAP server and fetches the most recent message from the INBOX. Ensure no other IMAP commands are run within the fetch loop to avoid deadlocks. This example requires initial client connection and mailbox lock. ```javascript const { ImapFlow } = require('imapflow'); const client = new ImapFlow({ host: 'imap.example.com', port: 993, secure: true, auth: { user: 'user@example.com', pass: 'password' } }); async function fetchLatest() { await client.connect(); let lock = await client.getMailboxLock('INBOX'); try { if (client.mailbox.exists === 0) { console.log('No messages in mailbox'); return; } // Fetch the most recent message let message = await client.fetchOne('*', { envelope: true, bodyStructure: true }); console.log('Subject:', message.envelope.subject); console.log('From:', message.envelope.from[0].address); console.log('Date:', message.envelope.date); } finally { lock.release(); } await client.logout(); } fetchLatest().catch(console.error); ``` -------------------------------- ### Set Connection Timeout Source: https://imapflow.com/docs/guides/configuration Configure the maximum time in milliseconds to establish a connection. The default is 90 seconds. ```javascript { connectionTimeout: 90000 } ``` -------------------------------- ### Development Environment Configuration Source: https://imapflow.com/docs/guides/configuration Configuration settings suitable for development environments, including enabling raw log output and disabling TLS certificate verification (use with caution). ```javascript { // Logging uses the built-in Pino instance by default logRaw: true, // Log raw IMAP data (base64 encoded) for debugging tls: { rejectUnauthorized: false // Only for testing! } } ``` -------------------------------- ### Get Mailbox Quota - IMAPFlow Client Source: https://imapflow.com/docs/api/imapflow-client Fetches quota information for a specified mailbox, defaulting to 'INBOX'. Returns false if the server does not support the QUOTA extension or the mailbox does not exist. Check for the existence of 'quota' and 'quota.storage' before accessing storage details. ```javascript let quota = await client.getQuota('INBOX'); if (quota && quota.storage) { console.log(`Used: ${quota.storage.used}/${quota.storage.limit} bytes`); } ``` -------------------------------- ### Manage Gmail labels using flag methods Source: https://imapflow.com/docs/api/imapflow-client Manages Gmail labels by using the standard flag methods with the `useLabels: true` option. Requires `X-GM-EXT-1` extension support. ```javascript // Add a Gmail label await client.messageFlagsAdd('12345', ['MyLabel'], { uid: true, useLabels: true }); // Remove a Gmail label await client.messageFlagsRemove('12345', ['OldLabel'], { uid: true, useLabels: true }); // Replace all labels for a message await client.messageFlagsSet('12345', ['Inbox', 'Important'], { uid: true, useLabels: true }); ``` -------------------------------- ### Property: capabilities Source: https://imapflow.com/docs/api/imapflow-client A map of server capabilities reported by the server. ```APIDOC ## Property: capabilities ### Description Map of server capabilities reported by the server. Keys are capability names, values are typically `true` or, for capabilities like `APPENDLIMIT`, a numeric value. ### Type Map ``` -------------------------------- ### Download Message Body Part as Stream - IMAPFlow Client Source: https://imapflow.com/docs/api/imapflow-client Downloads a specific message body part as a readable stream. The 'part' parameter can be omitted to download the entire message. This example downloads part '2' of a message with UID 12345 and pipes the content to a file. ```javascript let { meta, content } = await client.download(12345, '2', { uid: true }); console.log('Downloading:', meta.filename); const fs = require('fs'); content.pipe(fs.createWriteStream(meta.filename)); ``` -------------------------------- ### Property: usable Source: https://imapflow.com/docs/api/imapflow-client Indicates whether the connection is usable (connected and authenticated). ```APIDOC ## Property: usable ### Description Whether the connection is usable (connected and authenticated). ### Type Boolean ``` -------------------------------- ### Explicitly Control STARTTLS Behavior Source: https://imapflow.com/docs/guides/configuration Controls STARTTLS behavior explicitly. Set to true to require STARTTLS upgrade, or false to never use STARTTLS. ```javascript { secure: false, doSTARTTLS: true // Require STARTTLS upgrade } ``` -------------------------------- ### Set Greeting Timeout Source: https://imapflow.com/docs/guides/configuration Configure the maximum time in milliseconds to wait for the server greeting after a connection is established. The default is 16 seconds. ```javascript { greetingTimeout: 16000 } ``` -------------------------------- ### Custom Logger Configuration Source: https://imapflow.com/docs/guides/configuration Provide a custom logger object, compatible with Pino, to manage logging output. Ensure the logger has trace, debug, info, warn, error, and fatal methods. ```javascript const pino = require('pino'); { logger: pino({ level: 'debug' }) } ``` -------------------------------- ### Configure Outlook/Office 365 Client Source: https://imapflow.com/docs/getting-started/quick-start Use this configuration for connecting to Outlook or Office 365 accounts. OAuth2 is recommended for authentication. ```javascript const client = new ImapFlow({ host: 'outlook.office365.com', port: 993, secure: true, auth: { user: 'your.email@outlook.com', accessToken: 'your-oauth2-token' // OAuth2 recommended } }); ``` -------------------------------- ### Production Environment Configuration Source: https://imapflow.com/docs/guides/configuration Configuration settings optimized for production environments, disabling logging, enforcing strict TLS, and setting appropriate connection timeouts. ```javascript { logger: false, tls: { rejectUnauthorized: true, minVersion: 'TLSv1.2' }, connectionTimeout: 90000, socketTimeout: 300000 } ``` -------------------------------- ### SOCKS Proxy Configuration Source: https://imapflow.com/docs/guides/configuration Configure a SOCKS proxy for the connection. ```javascript { proxy: 'socks://proxy.example.com:1080' } ``` -------------------------------- ### Fetch New Messages as They Arrive Source: https://imapflow.com/docs/examples/fetching-messages Process new messages immediately as they arrive by combining the 'exists' event listener with fetching logic within the same lock context. This ensures you can act on new emails without delay. ```javascript async function watchAndFetch() { await client.connect(); let lock = await client.getMailboxLock('INBOX'); try { let lastCount = client.mailbox.exists; console.log(`Watching INBOX (${lastCount} messages)...`); client.on('exists', async (data) => { // We already hold the lock, so we can fetch directly if (data.count > lastCount) { let newMessages = await client.fetchAll( `${lastCount + 1}:*`, { envelope: true } ); for (let msg of newMessages) { console.log(`New: ${msg.envelope.subject}`); } lastCount = data.count; } }); // Wait until interrupted await new Promise(resolve => process.on('SIGINT', resolve)); } finally { lock.release(); } await client.logout(); } ``` -------------------------------- ### Fetch All Messages with fetchAll() Source: https://imapflow.com/docs/guides/fetching-messages Use `fetchAll()` to retrieve all messages in a mailbox into an array. This is suitable when you need to process messages after fetching and can safely run other commands afterward. Be cautious with large mailboxes as it loads all messages into memory. ```javascript let lock = await client.getMailboxLock('INBOX'); try { // fetchAll returns an array after all messages are fetched let messages = await client.fetchAll('1:100', { envelope: true, flags: true }); // Now you can safely run other commands for (let message of messages) { if (!message.flags.has('\Seen')) { await client.messageFlagsAdd(message.uid, ['\Seen'], { uid: true }); } } } finally { lock.release(); } ``` -------------------------------- ### fetch(range, query, options) Source: https://imapflow.com/docs/api/imapflow-client Fetches messages from the currently selected mailbox and returns an async iterator. Use with caution to avoid deadlocks. ```APIDOC ## fetch(range, query, options) ### Description Fetches messages from the currently selected mailbox. Returns an async iterator. Warning Do not run any other IMAP commands inside the fetch loop. This will cause a deadlock. Use `fetchAll()` if you need to process messages after fetching. ### Parameters #### Path Parameters * `range` (String|Array|SearchObject) - Message range or search query * String: '1:10', '1:_', '_ :-10' * Array: [1, 2, 3, 10] * SearchObject: `{ seen: false }` * `query` (FetchQueryObject) - Fetch query options * `uid` (Boolean) - Include UID * `flags` (Boolean) - Include flags * `envelope` (Boolean) - Include envelope * `bodyStructure` (Boolean) - Include MIME structure * `internalDate` (Boolean) - Include internal date * `size` (Boolean) - Include message size * `source` (Boolean|Object) - Include message source * `headers` (Boolean|Array) - Include headers * `bodyParts` (Array) - Include specific body parts * `threadId` (Boolean) - Include thread ID * `labels` (Boolean) - Include Gmail labels * `fast` (Boolean) - Macro: flags, internalDate, size * `all` (Boolean) - Macro: fast + envelope * `full` (Boolean) - Macro: all + bodyStructure * `options` (Object) - Additional options * `uid` (Boolean) - Range contains UIDs * `changedSince` (BigInt) - Only messages with higher modseq * `binary` (Boolean) - Request binary response ### Returns AsyncGenerator ### Example ```javascript for await (let message of client.fetch('1:*', { envelope: true, flags: true })) { console.log(message.uid, message.envelope.subject); } ``` ```