### Install IMAP Client from Git Source: https://github.com/n8n-io/imap/blob/master/_autodocs/README.md Use this command to install the IMAP client directly from its Git repository. This is useful for development or when needing the latest unreleased version. ```bash npm install chadxz/imap-simple ``` -------------------------------- ### connect() Source: https://github.com/n8n-io/imap/blob/master/_autodocs/SUMMARY.md Main entry point function for establishing an IMAP connection. Includes configuration and connection examples. ```APIDOC ## connect() ### Description Establishes an IMAP connection using the provided configuration. ### Method function ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config** (object) - Required - IMAP connection settings, event handlers, and search/fetch options. ### Request Example ```javascript // Example usage not provided in source ``` ### Response #### Success Response - **ImapSimple instance** - An instance of the ImapSimple class upon successful connection. #### Response Example ```json // Example response not provided in source ``` ``` -------------------------------- ### Example Scenario: Server Not Responding Source: https://github.com/n8n-io/imap/blob/master/_autodocs/errors.md Illustrates a scenario where the IMAP server is not responding, leading to a ConnectionTimeoutError. This example configures a short authentication timeout to trigger the error quickly. ```javascript // Scenario 1: Server not responding const slowConfig = { imap: { user: 'test@example.com', password: 'password', host: 'slow-server.example.com', port: 993, tls: true, authTimeout: 1000 // Only wait 1 second } }; imaps.connect(slowConfig) .catch(err => { // Error: ConnectionTimeoutError: connection timed out. timeout = 1000 ms console.error(err.name, ':', err.message); }); // Scenario 2: Network latency const highLatencyConfig = { imap: { user: 'test@example.com', password: 'password', host: '203.0.113.0', // Fictional address with high latency port: 993, authTimeout: 5000 // Allow 5 seconds } }; ``` -------------------------------- ### Usage Examples for PartStruct Source: https://github.com/n8n-io/imap/blob/master/_autodocs/types.md Demonstrates how to use PartStruct objects to find attachments, filter by MIME type, and access part metadata like type, subtype, size, encoding, and parameters. ```javascript const parts = imaps.getParts(message.attributes.struct); // Find all attachments const attachments = parts.filter(p => p.disposition && p.disposition.type.toUpperCase() === 'ATTACHMENT' ); // Find specific MIME type const pdfParts = parts.filter(p => p.type === 'application' && p.subtype === 'pdf' ); // Get part metadata const part = parts[0]; console.log(`${part.type}/${part.subtype} (${part.size} bytes)`); console.log('Encoding:', part.encoding); if (part.params) { console.log('Charset:', part.params.charset); } ``` -------------------------------- ### Outlook/Microsoft 365 Configuration Source: https://github.com/n8n-io/imap/blob/master/_autodocs/configuration.md Example configuration for connecting to Outlook or Microsoft 365 IMAP servers. Uses standard port 993 with TLS. ```javascript const config = { imap: { user: 'yourname@outlook.com', password: 'your-password', host: 'outlook.office365.com', port: 993, tls: true, authTimeout: 5000 } }; imaps.connect(config).then(connection => { console.log('Connected to Outlook'); }); ``` -------------------------------- ### Handle 'Connection ended unexpectedly' Error Source: https://github.com/n8n-io/imap/blob/master/_autodocs/errors.md Catch and log specific errors when the IMAP connection ends during setup before the 'ready' state. ```javascript imaps.connect(config) .catch(err => { if (err.message === 'Connection ended unexpectedly') { console.error('Server closed connection during handshake'); } }); ``` -------------------------------- ### Usage Example: Accessing Envelope Data Source: https://github.com/n8n-io/imap/blob/master/_autodocs/types.md Demonstrates how to access and log various fields from the message envelope object, including the sender's address. ```javascript const envelope = message.attributes.envelope; if (envelope) { console.log('Date:', envelope.date); console.log('Subject:', envelope.subject); if (envelope.from && envelope.from[0]) { const from = envelope.from[0]; console.log('From:', `${from.name} <${from.mailbox}@${from.host}>`); } } ``` -------------------------------- ### Handle 'Connection closed unexpectedly' Error Source: https://github.com/n8n-io/imap/blob/master/_autodocs/errors.md Catch and log specific errors when the IMAP connection emits a 'close' event during setup before the 'ready' state. ```javascript imaps.connect(config) .catch(err => { if (err.message === 'Connection closed unexpectedly') { console.error('Server closed connection unexpectedly'); } }); ``` -------------------------------- ### Accessing Parsed Headers Source: https://github.com/n8n-io/imap/blob/master/_autodocs/types.md Example of how to access and log individual header fields from a ParsedHeader object. Remember that all header values are arrays. ```javascript const header = message.parts.find(p => p.which === 'HEADER').body; // Access headers (remember: all are arrays) console.log(header.subject[0]); // 'Meeting reminder' console.log(header.from[0]); // 'John Doe ' console.log(header.to.join(', ')); // 'jane@example.com, bob@example.com' // Custom headers if (header['x-custom-header']) { console.log(header['x-custom-header'][0]); } ``` -------------------------------- ### Listen for New Mail with JavaScript Source: https://github.com/n8n-io/imap/blob/master/_autodocs/README.md Use this pattern to set up a listener for incoming emails. The connection remains open to receive real-time notifications. ```javascript imaps.connect(config).then(connection => { connection.on('mail', (numNewMail) => { console.log('New mail arrived:', numNewMail); }); // Keep connection open process.on('SIGINT', () => { connection.end(); }); }); ``` -------------------------------- ### Get All Mailboxes Source: https://github.com/n8n-io/imap/blob/master/_autodocs/api-reference/ImapSimple.md Retrieves a nested object representing all available mailboxes. Use this to list folders and their hierarchy. ```javascript connection.getBoxes() .then(boxes => { console.log('Available mailboxes:'); for (const [name, box] of Object.entries(boxes)) { console.log(` ${name} (${box.attribs.join(', ')})`); } }) .catch(err => console.error('Failed:', err)); ``` ```javascript function listBoxes(boxes, indent = '') { for (const [name, box] of Object.entries(boxes)) { console.log(indent + name); if (box.children) { listBoxes(box.children, indent + ' '); } } } connection.getBoxes() .then(boxes => listBoxes(boxes)); ``` -------------------------------- ### connect() Source: https://github.com/n8n-io/imap/blob/master/_autodocs/api-reference/connect.md Establishes a connection to an IMAP server and returns an ImapSimple instance. This function can be used with Promises or callbacks. ```APIDOC ## connect(options, [callback]) ### Description Main entry point for establishing a connection to an IMAP server. Returns an `ImapSimple` instance which provides a simplified API wrapper around node-imap. ### Method `connect` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **options** (object) - Required - Configuration object containing IMAP connection settings. * **options.imap** (object) - Required - Options passed directly to node-imap constructor. Accepts all node-imap connection options including `user`, `password`, `host`, `port`, `tls`, `authTimeout`. * **options.imap.user** (string) - Required - IMAP server username/email address. * **options.imap.password** (string) - Required - IMAP server password. * **options.imap.host** (string) - Required - IMAP server hostname (e.g., `imap.gmail.com`). * **options.imap.port** (number) - Required - IMAP server port (typically 993 for TLS, 143 for plain). * **options.imap.tls** (boolean) - Optional - Enable TLS encryption. Defaults to `true`. * **options.imap.authTimeout** (number) - Optional - Authentication timeout in milliseconds. Defaults to `2000`. * **options.onmail** (function) - Optional - Callback function invoked when new mail arrives. Receives signature `(numNewMail)`. * **options.onexpunge** (function) - Optional - Callback function invoked when messages are expunged. Receives signature `(seqno)`. * **options.onupdate** (function) - Optional - Callback function invoked when mailbox state updates. Receives signature `(seqno, info)`. * **callback** (function) - Optional - Optional callback with signature `(err, connection)`. If provided, returns undefined; otherwise returns Promise. ### Request Example #### Promise-based connection ```javascript const imaps = require('imap-simple'); const config = { imap: { user: 'your@email.address', password: 'yourpassword', host: 'imap.gmail.com', port: 993, tls: true, authTimeout: 3000 } }; imaps.connect(config) .then(function (connection) { console.log('Connected to IMAP server'); return connection.openBox('INBOX'); }) .catch(function (err) { console.error('Connection failed:', err.message); }); ``` #### Callback-based connection ```javascript imaps.connect(config, function (err, connection) { if (err) { console.error('Connection failed:', err); return; } console.log('Connected'); }); ``` #### Connection with event handlers ```javascript const config = { imap: { user: 'your@email.address', password: 'yourpassword', host: 'imap.gmail.com', port: 993, tls: true, authTimeout: 5000 }, onmail: function (numNewMail) { console.log('New mail arrived:', numNewMail); }, onexpunge: function (seqno) { console.log('Message expunged at sequence number:', seqno); }, onupdate: function (seqno, info) { console.log('Mailbox update:', seqno, info); } }; imaps.connect(config) .then(connection => { // Connection is ready with event handlers registered }); ``` ### Response #### Success Response **Promise** — Resolves with an `ImapSimple` instance that can be used to perform IMAP operations. The connection is ready to use immediately upon resolution. #### Response Example (See Request Example for Promise-based connection) ### Throws/Rejects * **ConnectionTimeoutError** - Condition: Authentication timeout occurs (connection idle beyond `authTimeout`). Source: `lib/errors.js`. * **Error** - Condition: Connection closed unexpectedly. Source: `lib/imapSimple.js` line 661. * **Error** - Condition: Connection ended unexpectedly. Source: `lib/imapSimple.js` line 654. * **Any node-imap error** - Condition: IMAP protocol errors, authentication failures, network issues. Source: Propagated from node-imap. ``` -------------------------------- ### Establish Basic IMAP Connection Source: https://github.com/n8n-io/imap/blob/master/_autodocs/README.md Connect to an IMAP server using provided configuration. Ensure your IMAP server details are correct. ```javascript const imaps = require('imap-simple'); const config = { imap: { user: 'your@email.address', password: 'yourpassword', host: 'imap.gmail.com', port: 993, tls: true, authTimeout: 3000 } }; imaps.connect(config).then(connection => { console.log('Connected!'); connection.end(); }); ``` -------------------------------- ### Open Mailbox with Callback Source: https://github.com/n8n-io/imap/blob/master/_autodocs/README.md Shows how to open a mailbox using the alternative Callback pattern. This pattern is useful for older Node.js versions or specific asynchronous control flows. ```javascript // Callback pattern (alternative) connection.openBox('INBOX', (err, result) => { if (err) { } else { } }); ``` -------------------------------- ### Run IMAP Client Tests Source: https://github.com/n8n-io/imap/blob/master/_autodocs/README.md Execute the test suite for the IMAP client using this npm command. Ensure all tests pass to verify the client's functionality. ```bash npm test ``` -------------------------------- ### Get All MIME Parts Structure Source: https://github.com/n8n-io/imap/blob/master/_autodocs/types.md Retrieve the structure of all MIME parts within a message using the imaps library. This function returns a PartStruct array. ```javascript // Get all MIME parts const mimePartsStruct = message.attributes.struct; const parts = imaps.getParts(mimePartsStruct); // Returns PartStruct array ``` -------------------------------- ### Open Mailbox with Promise Source: https://github.com/n8n-io/imap/blob/master/_autodocs/README.md Demonstrates opening a mailbox using the preferred Promise-based pattern. Handles successful opening and errors asynchronously. ```javascript // Promise pattern (preferred) connection.openBox('INBOX') .then(result => { }) .catch(err => { }); ``` -------------------------------- ### Listening to ImapSimple Events Source: https://github.com/n8n-io/imap/blob/master/_autodocs/api-reference/ImapSimple.md Connect to an IMAP server and set up listeners for 'mail', 'error', and 'close' events. This is useful for real-time monitoring of mail arrival and connection status. ```javascript const connection = await imaps.connect(config); connection.on('mail', (numNewMail) => { console.log('New mail arrived:', numNewMail); }); connection.on('error', (err) => { console.error('Connection error:', err); }); connection.on('close', () => { console.log('Connection closed'); }); ``` -------------------------------- ### Configure Server Event Listeners Source: https://github.com/n8n-io/imap/blob/master/README.md Add event listener functions like 'onmail', 'onexpunge', and 'onupdate' to the configuration object passed to the 'connect' function. These functions are called when specific server events occur. ```javascript var config = { imap: { ... }, onmail: function (numNewMail) { ... }, onexpunge: function (seqno) { ... }, onupdate: function (seqno, info) { ... } }; ``` -------------------------------- ### Backup Emails to EML Files with JavaScript Source: https://github.com/n8n-io/imap/blob/master/_autodocs/README.md This snippet demonstrates how to connect to an IMAP server, search for all emails, and save the full content of each email to a separate .eml file. ```javascript const fs = require('fs'); const imaps = require('imap-simple'); imaps.connect(config) .then(conn => { return conn.openBox('INBOX') .then(() => conn.search(['ALL'], {bodies: ''})) .then(messages => { return Promise.all( messages.map((msg, idx) => { const fullPart = msg.parts.find(p => p.which === ''); return conn.getPartData(msg, fullPart) .then(data => { fs.writeFileSync(`email-${idx}.eml`, data); }); }) ); }); }); ``` -------------------------------- ### Accessing Mailboxes with getBoxes() Source: https://github.com/n8n-io/imap/blob/master/_autodocs/types.md Fetches all mailboxes and demonstrates accessing top-level mailboxes by name, including those with special characters. ```javascript const boxes = await connection.getBoxes(); // Access top-level mailboxes console.log(boxes.INBOX); console.log(boxes['[Gmail]/Sent Mail']); ``` -------------------------------- ### Import IMAP Simple Module Source: https://github.com/n8n-io/imap/blob/master/_autodocs/README.md Import the main 'imap-simple' module. This is the primary way to access the library's functionalities. ```javascript const imaps = require('imap-simple'); ``` -------------------------------- ### Usage Pattern Source: https://github.com/n8n-io/imap/blob/master/_autodocs/README.md imap-simple supports a Promise/Callback hybrid pattern for all its methods. The Promise pattern is preferred. ```APIDOC ## Usage Pattern All methods support both Promise and Callback patterns. If a callback is provided, it's invoked; otherwise, a Promise is returned. ### Promise Pattern (Preferred) ```javascript connection.openBox('INBOX') .then(result => { /* handle success */ }) .catch(err => { /* handle error */ }); ``` ### Callback Pattern (Alternative) ```javascript connection.openBox('INBOX', (err, result) => { if (err) { // handle error } else { // handle success } }); ``` ``` -------------------------------- ### Connect Options Object Structure Source: https://github.com/n8n-io/imap/blob/master/_autodocs/configuration.md This object defines the structure for connecting to an IMAP server using imap-simple. It includes both node-imap connection settings and imap-simple specific handlers. ```javascript { imap: { // node-imap connection settings user: 'email@example.com', password: 'password', host: 'imap.gmail.com', port: 993, tls: true, authTimeout: 3000, // ... all other node-imap options }, // imap-simple specific handlers onmail: function (numNewMail) { }, onexpunge: function (seqNo) { }, onupdate: function (seqNo, info) { }, // deprecated connectTimeout: 3000 // Use options.imap.authTimeout instead } ``` -------------------------------- ### Multiple Account Configuration Source: https://github.com/n8n-io/imap/blob/master/_autodocs/configuration.md Defines configurations for multiple IMAP accounts (Gmail, Outlook, custom) and provides an async function to connect to all of them, logging success or failure for each. ```javascript const accounts = { gmail: { imap: { user: 'name@gmail.com', password: 'app-password', host: 'imap.gmail.com', port: 993, tls: true, authTimeout: 5000 } }, outlook: { imap: { user: 'name@outlook.com', password: 'password', host: 'outlook.office365.com', port: 993, tls: true, authTimeout: 5000 } }, custom: { imap: { user: 'user@example.com', password: 'password', host: 'mail.example.com', port: 993, tls: true, authTimeout: 5000 } } }; async function connectAllAccounts() { const connections = {}; for (const [name, config] of Object.entries(accounts)) { try { connections[name] = await imaps.connect(config); console.log(`Connected to ${name}`); } catch (err) { console.error(`Failed to connect to ${name}:`, err.message); } } return connections; } ``` -------------------------------- ### Manage IMAP Connection Source: https://github.com/n8n-io/imap/blob/master/_autodocs/INDEX.md Establish and close IMAP connections, and listen for connection events. ```javascript imaps.connect(config) // Establish connection connection.end() // Close connection connection.on(event, callback) // Listen for events ``` -------------------------------- ### Find Text and HTML Parts Source: https://github.com/n8n-io/imap/blob/master/_autodocs/api-reference/getParts.md Connects to an IMAP server, opens the INBOX, searches for all messages, and identifies the 'text/plain' and 'text/html' parts within the first message's MIME structure. It also logs the size of each part. ```javascript const imaps = require('imap-simple'); imaps.connect(config) .then(connection => connection.openBox('INBOX')) .then(connection => { return connection.search(['ALL'], {struct: true}); }) .then(messages => { const message = messages[0]; const parts = imaps.getParts(message.attributes.struct); // Find text/plain part const textPart = parts.find(p => p.type === 'text' && p.subtype === 'plain' ); // Find text/html part const htmlPart = parts.find(p => p.type === 'text' && p.subtype === 'html' ); console.log('Text part:', textPart ? textPart.partID : 'not found'); console.log('HTML part:', htmlPart ? htmlPart.partID : 'not found'); // Get part sizes parts.forEach(part => { const mimeType = `${part.type}/${part.subtype}`; console.log(`${mimeType}: ${part.size} bytes`); }); }); ``` -------------------------------- ### Open Mailbox and Log Info Source: https://github.com/n8n-io/imap/blob/master/_autodocs/types.md Open a specified mailbox and log its total messages, new messages, and read-only status. This requires an active 'connection' object. ```javascript const boxInfo = await connection.openBox('INBOX'); console.log('Total messages:', boxInfo.messages); console.log('New messages:', boxInfo.newMessages); console.log('Read-only:', boxInfo.readOnly); ``` -------------------------------- ### Main Exports Source: https://github.com/n8n-io/imap/blob/master/_autodocs/README.md The main export of the imap-simple library provides several functions and a class for interacting with IMAP servers. ```APIDOC ## Main Export ```javascript const imaps = require('imap-simple'); ``` ### Exports: - **connect**: function - Establishes connection to IMAP server. - **ImapSimple**: class - Constructor for creating instances (rarely used directly). - **getParts**: function - Flattens MIME structure arrays. - **parseHeader**: function - Re-exported from node-imap for header parsing. - **errors**: object - Contains error classes like ConnectionTimeoutError. ``` -------------------------------- ### Callback-based IMAP Connection Source: https://github.com/n8n-io/imap/blob/master/_autodocs/api-reference/connect.md Use this snippet for a callback-based connection. It establishes a connection and logs success or error messages. ```javascript imaps.connect(config, function (err, connection) { if (err) { console.error('Connection failed:', err); return; } console.log('Connected'); }); ``` -------------------------------- ### Promise-based IMAP Connection Source: https://github.com/n8n-io/imap/blob/master/_autodocs/api-reference/connect.md Use this snippet for a Promise-based connection. It establishes a connection and opens the 'INBOX' mailbox. Handles connection errors gracefully. ```javascript const imaps = require('imap-simple'); const config = { imap: { user: 'your@email.address', password: 'yourpassword', host: 'imap.gmail.com', port: 993, tls: true, authTimeout: 3000 } }; imaps.connect(config) .then(function (connection) { console.log('Connected to IMAP server'); return connection.openBox('INBOX'); }) .catch(function (err) { console.error('Connection failed:', err.message); }); ``` -------------------------------- ### Download All Attachments Source: https://github.com/n8n-io/imap/blob/master/_autodocs/api-reference/getParts.md Connects to an IMAP server, opens the INBOX, searches for unseen messages, and downloads all attachments from these messages. It logs the filenames and sizes of the downloaded attachments. ```javascript imaps.connect(config) .then(connection => connection.openBox('INBOX')) .then(connection => { return connection.search(['UNSEEN'], {bodies: '', struct: true}) .then(messages => ({connection, messages})); }) .then(({connection, messages}) => { const attachmentPromises = []; messages.forEach(message => { const parts = imaps.getParts(message.attributes.struct); parts.filter(part => { return part.disposition && part.disposition.type.toUpperCase() === 'ATTACHMENT'; }).forEach(part => { attachmentPromises.push( connection.getPartData(message, part) .then(data => ({ filename: part.disposition.params.filename, data: data })) ); }); }); return Promise.all(attachmentPromises); }) .then(attachments => { console.log('Downloaded attachments:', attachments); attachments.forEach(att => { console.log(` - ${att.filename} (${att.data.length} bytes)`); }); }); ``` -------------------------------- ### getParts() Signature Source: https://github.com/n8n-io/imap/blob/master/_autodocs/api-reference/getParts.md The signature for the getParts() utility function, indicating its parameters and return type. ```javascript getParts(struct, [parts]) -> Array ``` -------------------------------- ### addBox(boxName) Source: https://github.com/n8n-io/imap/blob/master/_autodocs/api-reference/ImapSimple.md Creates a new mailbox (folder) on the IMAP server. It returns a Promise that resolves with the name of the created mailbox. ```APIDOC ## addBox(boxName, [callback]) ### Description Creates a new mailbox (folder). ### Method `ImapSimple.prototype.addBox` ### Parameters #### Path Parameters - **boxName** (string) - Required - Name of the new mailbox to create #### Callback - **callback** (function) - Optional - Callback with signature `(err, boxName)` ### Returns `Promise` — Resolves with the created mailbox name. ### Request Example ```javascript connection.addBox('MyArchive') .then(boxName => console.log('Created mailbox:', boxName)) .catch(err => console.error('Failed:', err)); connection.addBox('Work/Projects') .then(boxName => console.log('Created:', boxName)); ``` ``` -------------------------------- ### Utility Functions Source: https://github.com/n8n-io/imap/blob/master/_autodocs/INDEX.md Helper functions for parsing MIME structures and email headers. ```APIDOC ## imaps.getParts(struct) ### Description Flattens a MIME structure into a more accessible array of parts. ### Method imaps.getParts ### Parameters - **struct**: (Object) - The MIME structure object, typically from a message's body structure. ``` ```APIDOC ## imaps.parseHeader(headerText) ### Description Parses a raw email header string into a structured object. ### Method imaps.parseHeader ### Parameters - **headerText**: (String) - The raw header text of an email. ``` -------------------------------- ### Implement Connection Retry Logic with JavaScript Source: https://github.com/n8n-io/imap/blob/master/_autodocs/README.md This function attempts to connect to the IMAP server multiple times with a delay between retries. It throws an error if all attempts fail. ```javascript async function connectWithRetry(config, maxAttempts = 3) { for (let i = 0; i < maxAttempts; i++) { try { return await imaps.connect(config); } catch (err) { if (i < maxAttempts - 1) { console.log(`Attempt ${i + 1} failed, retrying...`); await new Promise(r => setTimeout(r, 1000 * (i + 1))); } else { throw err; } } } } ``` -------------------------------- ### Connection Management Source: https://github.com/n8n-io/imap/blob/master/_autodocs/INDEX.md Methods for establishing, maintaining, and closing IMAP connections. ```APIDOC ## imaps.connect(config) ### Description Establishes a connection to an IMAP server using the provided configuration. ### Method imaps.connect ### Parameters - **config**: (Object) - Configuration object containing connection details (e.g., { host: '...', port: 993, secure: true, user: '...', password: '...' }). ### Response Returns a Promise that resolves with a connection object. ``` ```APIDOC ## connection.end() ### Description Closes the active IMAP connection gracefully. ### Method connection.end. ``` ```APIDOC ## connection.on(event, callback) ### Description Listens for specific events emitted by the connection. ### Method connection.on ### Parameters - **event**: (String) - The name of the event to listen for (e.g., 'mail', 'error'). - **callback**: (Function) - The function to execute when the event is triggered. ``` -------------------------------- ### Catch ConnectionTimeoutError Source: https://github.com/n8n-io/imap/blob/master/_autodocs/errors.md Demonstrates how to catch a ConnectionTimeoutError specifically when connecting to an IMAP server. This is useful for handling cases where authentication takes too long. ```javascript const imaps = require('imap-simple'); imaps.connect(config) .catch(err => { if (err instanceof imaps.errors.ConnectionTimeoutError) { console.error('Connection timed out after', err.timeout, 'ms'); } else { console.error('Connection failed:', err.message); } }); ``` -------------------------------- ### Events Source: https://github.com/n8n-io/imap/blob/master/_autodocs/README.md The connection object emits various events to notify about server activities. ```APIDOC ## Events The connection emits events from the underlying IMAP server: - `mail(numNewMail)`: Emitted when new mail arrives. - `expunge(seqNo)`: Emitted when a message is deleted. - `update(seqNo, info)`: Emitted when a message's state changes. - `alert(msg)`: Emitted when the server sends an alert. - `error(err)`: Emitted when an error occurs. - `close()`: Emitted when the connection is closed. - `end()`: Emitted when the connection ends. ``` -------------------------------- ### IMAP with Event Handlers and Debugging Source: https://github.com/n8n-io/imap/blob/master/_autodocs/configuration.md Connect to an IMAP server with custom event handlers for new mail, expunges, and updates. Enables debug logging using `console.log`. ```javascript const config = { imap: { user: 'user@example.com', password: 'password', host: 'imap.gmail.com', port: 993, tls: true, authTimeout: 5000, debug: console.log // Enable debug logging }, onmail: function (numNewMail) { console.log(`${numNewMail} new message(s) arrived`); // Refresh inbox connection.openBox('INBOX') .then(() => connection.search(['UNSEEN'])) .then(messages => { console.log('Unread:', messages.length); }); }, onexpunge: function (seqNo) { console.log(`Message at sequence ${seqNo} was removed`); }, onupdate: function (seqNo, info) { console.log(`Message ${seqNo} updated:`, info); } }; imaps.connect(config).then(connection => { console.log('Connected with event handlers'); // Keep connection alive and listening for events process.on('SIGINT', () => { connection.end(); process.exit(0); }); }); ``` -------------------------------- ### Lint IMAP Client Code Source: https://github.com/n8n-io/imap/blob/master/_autodocs/README.md Run the linter to check for code style consistency and potential errors. This command helps maintain code quality. ```bash npm run lint ``` -------------------------------- ### Manual Header Parsing Source: https://github.com/n8n-io/imap/blob/master/_autodocs/api-reference/parseHeader.md Demonstrates how to manually parse a raw email header string using the `parseHeader` function. This is useful when you have a raw header string and need to extract its components. ```javascript const imaps = require('imap-simple'); // If you need to manually parse raw headers const rawHeader = `From: sender@example.com To: recipient@example.com Subject: Test Email Date: Mon, 24 Jun 2024 10:30:00 +0000 Message-ID: `; const parsed = imaps.parseHeader(rawHeader); console.log('Subject:', parsed.subject[0]); // 'Test Email' console.log('From:', parsed.from[0]); // 'sender@example.com' console.log('To:', parsed.to[0]); // 'recipient@example.com' ``` -------------------------------- ### ImapSimple Source: https://github.com/n8n-io/imap/blob/master/README.md Constructor for creating an instance of ImapSimple, primarily used for testing purposes. ```APIDOC ## ImapSimple ### Description Constructor for creating an instance of the `ImapSimple` class. This is typically used internally or for testing purposes to simulate an IMAP connection. ### Method ImapSimple(imap) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **imap** (object) - Required - An object representing the underlying node-imap connection. ### Request Example ```javascript // This is typically used internally or for testing. // const mockImap = require('imap-mock'); // const imapInstance = new ImapSimple(mockImap); ``` ### Response #### Success Response - **ImapSimple** - A new instance of the ImapSimple class. #### Response Example ```json // Returns an instance of ImapSimple { "_imap": { /* provided imap object */ }, "_box": null } ``` ``` -------------------------------- ### Building Recipient Lists from Headers Source: https://github.com/n8n-io/imap/blob/master/_autodocs/api-reference/parseHeader.md Connects to an IMAP server, fetches all messages with headers, and iterates through them to build a unique list of all recipients found in the 'From', 'To', 'Cc', and 'Bcc' fields. ```javascript const imaps = require('imap-simple'); imaps.connect(config) .then(connection => connection.openBox('INBOX')) .then(connection => { return connection.search(['ALL'], {bodies: ['HEADER']}); }) .then(messages => { const recipients = new Set(); messages.forEach(message => { const header = message.parts.find(p => p.which === 'HEADER').body; // Collect from all address fields [header.from, header.to, header.cc, header.bcc].forEach(field => { if (field && Array.isArray(field)) { field.forEach(addr => { // Extract just the email address const match = addr.match(/["\w.-]+@["\w.-]+\\.\w+/); if (match) recipients.add(match[0]); }); } }); }); console.log('All recipients:', Array.from(recipients)); }); ``` -------------------------------- ### ImapSimple.addMessageLabel Source: https://github.com/n8n-io/imap/blob/master/README.md Adds one or more labels (folders) to specified messages. ```APIDOC ## ImapSimple.addMessageLabel ### Description Adds the provided label(s) to the specified message(s). Labels are often represented as folders in IMAP. ### Method addMessageLabel(source, label, callback) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **source** (mixed) - Required - A `MessageSource` object specifying the messages to which labels should be added. - **label** (string | Array) - Required - The label or array of labels (folder names) to add. - **callback** (function) - Optional - Callback function with signature `(err)`. ### Request Example ```javascript // Add 'Archive' label to messages identified by source imap.addMessageLabel(messageSource, 'Archive') .then(() => console.log('Label added successfully')) .catch(err => console.error('Error adding label:', err)); // Add multiple labels to messages imap.addMessageLabel(messageSource, ['Important', 'Urgent']) .then(() => console.log('Labels added successfully')) .catch(err => console.error('Error adding labels:', err)); ``` ### Response #### Success Response (200) - None explicitly documented, operation is confirmed by promise resolution or lack of error in callback. #### Error Response - **Error** - If the operation fails. ``` -------------------------------- ### Async/Await Error Handling Source: https://github.com/n8n-io/imap/blob/master/_autodocs/errors.md Utilize async/await with try-catch blocks for cleaner error handling in sequential IMAP operations. Includes specific handling for ConnectionTimeoutError. ```javascript async function fetchUnreadEmails() { try { const connection = await imaps.connect(config); await connection.openBox('INBOX'); const messages = await connection.search(['UNSEEN']); connection.end(); return messages; } catch (err) { if (err instanceof imaps.errors.ConnectionTimeoutError) { console.error('Connection timeout'); } else { console.error('Error:', err.message); } throw err; } } fetchUnreadEmails().catch(console.error); ``` -------------------------------- ### IMAP Connection with Event Handlers Source: https://github.com/n8n-io/imap/blob/master/_autodocs/api-reference/connect.md Establishes an IMAP connection with custom event handlers for new mail, expunged messages, and mailbox updates. The connection is ready to use upon resolution of the returned Promise. ```javascript const config = { imap: { user: 'your@email.address', password: 'yourpassword', host: 'imap.gmail.com', port: 993, tls: true, authTimeout: 5000 }, onmail: function (numNewMail) { console.log('New mail arrived:', numNewMail); }, onexpunge: function (seqno) { console.log('Message expunged at sequence number:', seqno); }, onupdate: function (seqno, info) { console.log('Mailbox update:', seqno, info); } }; imaps.connect(config) .then(connection => { // Connection is ready with event handlers registered }); ``` -------------------------------- ### Search Unread Emails and Fetch Headers Source: https://github.com/n8n-io/imap/blob/master/_autodocs/README.md Connect to IMAP, open the INBOX, search for unseen messages, and log their sender and subject. Requires an active connection and an open INBOX. ```javascript imaps.connect(config) .then(connection => { return connection.openBox('INBOX') .then(() => { return connection.search(['UNSEEN'], { bodies: ['HEADER', 'TEXT'] }); }) .then(messages => { console.log('Found', messages.length, 'unread messages'); messages.forEach(msg => { const header = msg.parts.find(p => p.which === 'HEADER'); console.log('From:', header.body.from[0]); console.log('Subject:', header.body.subject[0]); }); connection.end(); }); }) .catch(err => console.error('Error:', err.message)); ``` -------------------------------- ### Retry Logic with Exponential Backoff Source: https://github.com/n8n-io/imap/blob/master/_autodocs/errors.md Implements a connection function that retries establishing a connection with exponential backoff, limiting the number of attempts. Useful for transient network issues. ```javascript async function connectWithRetry(config, maxAttempts = 3) { let lastError; for (let attempt = 1; attempt <= maxAttempts; attempt++) { try { return await imaps.connect(config); } catch (err) { lastError = err; if (attempt < maxAttempts) { const delay = Math.pow(2, attempt - 1) * 1000; // 1s, 2s, 4s console.log(`Attempt ${attempt} failed, retrying in ${delay}ms`); await new Promise(r => setTimeout(r, delay)); } } } throw lastError; } connectWithRetry(config) .then(connection => { console.log('Connected after retries'); }) .catch(err => { console.error('Failed to connect after all attempts:', err.message); }); ``` -------------------------------- ### Handle Email Attachments Source: https://github.com/n8n-io/imap/blob/master/_autodocs/README.md Searches for all messages, identifies attachment parts within each message, and prepares to download them. This snippet focuses on identifying attachments. ```javascript imaps.connect(config) .then(connection => { return connection.openBox('INBOX') .then(() => connection.search(['ALL'], {struct: true})) .then(messages => { const attachmentParts = []; messages.forEach(message => { const parts = imaps.getParts(message.attributes.struct); parts.filter(part => { return part.disposition && part.disposition.type.toUpperCase() === 'ATTACHMENT'; }).forEach(part => { attachmentParts.push({message, part}); }); }); // Download all attachments return Promise.all( attachmentParts.map(ap => connection.getPartData(ap.message, ap.part) ) ); }); }); ``` -------------------------------- ### Navigating Nested Mailboxes Source: https://github.com/n8n-io/imap/blob/master/_autodocs/types.md Shows how to check for and iterate through the children of a specific mailbox if it exists and contains nested mailboxes. ```javascript // Navigate nested structure if (boxes.Work && boxes.Work.children) { for (const [name, box] of Object.entries(boxes.Work.children)) { console.log(' -', name); } } ``` -------------------------------- ### Self-Hosted Server with Self-Signed Certificate Source: https://github.com/n8n-io/imap/blob/master/_autodocs/configuration.md Connect to a self-hosted IMAP server that uses a self-signed certificate. Set `rejectUnauthorized` to `false` in `tlsOptions` to allow the connection. ```javascript const config = { imap: { user: 'user@example.com', password: 'password', host: 'mail.example.com', port: 993, tls: true, tlsOptions: { rejectUnauthorized: false // Allow self-signed certificates }, authTimeout: 3000 } }; imaps.connect(config).then(connection => { console.log('Connected with self-signed certificate'); }); ``` -------------------------------- ### ImapSimple.getBoxes Source: https://github.com/n8n-io/imap/blob/master/README.md Retrieves the full list of mailboxes (folders) available on the IMAP server. ```APIDOC ## ImapSimple.getBoxes ### Description Fetches and returns a list of all available mailboxes (folders) on the IMAP server. The structure of the returned object is identical to the one provided by the node-imap library's `getBoxes()` method. ### Method getBoxes(callback) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **callback** (function) - Optional - Callback function with signature `(err, boxes)`. ### Request Example ```javascript // Using Promise imap.getBoxes() .then(boxes => { console.log('Mailboxes:', boxes); }) .catch(err => { console.error('Error fetching mailboxes:', err); }); // Using Callback imap.getBoxes((err, boxes) => { if (err) { console.error('Error fetching mailboxes:', err); } else { console.log('Mailboxes:', boxes); } }); ``` ### Response #### Success Response - **boxes** (object) - An object containing the list of mailboxes, mirroring the node-imap structure. #### Response Example ```json { "INBOX": { "messages": 100, "recent": 5, "unseen": 10, "flags": ["\Answered", "\Flagged", ...], "delimiter": "/", "மையான": { "messages": 50, "recent": 0, "unseen": 0, "flags": [], "delimiter": "/" } }, "Sent": { ... }, "Drafts": { ... } } ``` #### Error Response - **Error** - If the operation fails. ``` -------------------------------- ### Specific Error Handling per Operation Source: https://github.com/n8n-io/imap/blob/master/_autodocs/errors.md Demonstrates how to implement fine-grained error handling for individual IMAP operations like deleting or moving messages, checking for specific error messages. ```javascript const imaps = require('imap-simple'); async function safeDeleteMessage(connection, uid) { try { await connection.deleteMessage(uid); console.log('Message deleted:', uid); } catch (err) { if (err.message.includes('read-only')) { console.error('Mailbox is read-only, cannot delete'); } else { console.error('Failed to delete message:', err.message); } } } async function safeMove(connection, source, boxName) { try { await connection.moveMessage(source, boxName); } catch (err) { if (err.message.includes('doesn\'t exist')) { console.error('Destination mailbox does not exist:', boxName); } else { console.error('Failed to move message:', err.message); } } } ``` -------------------------------- ### ImapSimple Class Methods Source: https://github.com/n8n-io/imap/blob/master/_autodocs/SUMMARY.md Core class with a complete reference to its public methods for managing IMAP operations. ```APIDOC ## ImapSimple Methods ### Description Provides methods for interacting with an IMAP server after a connection is established. ### Methods - **openBox(boxName)**: Opens a specified mailbox. - **closeBox()**: Closes the currently open mailbox. - **search(criteria, options)**: Searches for messages within the current mailbox based on specified criteria. - **getPartData(messageId, partIndex)**: Retrieves the data for a specific part of a message. - **addFlags(messageIds, flags)**: Adds flags to specified messages. - **delFlags(messageIds, flags)**: Deletes flags from specified messages. - **deleteMessage(messageId)**: Deletes a specific message. - **moveMessage(messageId, targetBox)**: Moves a message to a different mailbox. - **addMessageLabel(messageId, label)**: Adds a label to a message (Gmail specific). - **removeMessageLabel(messageId, label)**: Removes a label from a message (Gmail specific). - **append(message, boxName)**: Appends a new message to a specified mailbox. - **getBoxes()**: Retrieves a list of all mailboxes. - **addBox(boxName)**: Creates a new mailbox. - **delBox(boxName)**: Deletes an existing mailbox. - **end()**: Closes the IMAP connection. ### Parameters Parameters vary per method. Refer to the full API reference for details on each method's parameters, including types, requirements, and descriptions. ### Response Responses vary per method. Refer to the full API reference for details on each method's return values and potential errors. ``` -------------------------------- ### Gmail Configuration with 2FA Source: https://github.com/n8n-io/imap/blob/master/_autodocs/configuration.md Configure IMAP connection to Gmail using an app password for 2-factor authentication. Ensure you generate a 16-character app password from your Google account settings. ```javascript const config = { imap: { user: 'yourname@gmail.com', password: 'your-16-char-app-password', // Generate at https://myaccount.google.com/apppasswords host: 'imap.gmail.com', port: 993, tls: true, authTimeout: 5000 } }; imaps.connect(config).then(connection => { console.log('Connected to Gmail'); }); ``` -------------------------------- ### Part Object Schema Source: https://github.com/n8n-io/imap/blob/master/_autodocs/api-reference/getParts.md Defines the structure of objects returned by getParts(), representing individual MIME parts. ```javascript { partID: string, type: string, subtype: string, params: object, encoding: string, size: number, md5: string, disposition: object|null, language: Array|null, location: string|null, } ``` -------------------------------- ### Handle IMAP Authentication Errors Source: https://github.com/n8n-io/imap/blob/master/_autodocs/errors.md Catch and handle authentication failures, such as invalid credentials, by checking the error message for specific indicators like 'LOGIN failed'. ```javascript imaps.connect({ imap: { user: 'invalid@example.com', password: 'wrongpassword', host: 'imap.gmail.com', port: 993, tls: true, authTimeout: 3000 } }) .catch(err => { if (err.message.includes('LOGIN failed')) { console.error('Authentication failed. Check username/password.'); } else { console.error('Connection error:', err.message); } }); ``` -------------------------------- ### Open Mailbox with ImapSimple Source: https://github.com/n8n-io/imap/blob/master/_autodocs/api-reference/ImapSimple.md Opens a specified mailbox for reading and message operations. Supports Promise and callback patterns. Use when you need to access messages or perform operations within a specific folder. ```javascript connection.openBox('INBOX') .then(boxInfo => { console.log('Opened mailbox with', boxInfo.messages, 'messages'); }) .catch(err => console.error('Failed to open mailbox:', err)); ``` ```javascript connection.openBox('INBOX', (err, boxInfo) => { if (err) console.error(err); else console.log('Mailbox opened'); }); ``` -------------------------------- ### addBox Source: https://github.com/n8n-io/imap/blob/master/README.md Creates a new mailbox. This operation can be handled via a callback or a promise. ```APIDOC ## addBox ### Description Creates a new mailbox. The provided callback is invoked with `(err, boxName)`, or the returned promise resolves with `boxName`. ### Method Promise ### Parameters - **boxName** (*string*) - Required - The name of the mailbox to create. - **callback** (*function*) - Optional - A callback function with signature `(err, boxName)`. ### Response - **Promise** - Resolves with the `boxName` of the created mailbox. - **callback** - Called with `(err, boxName)` upon completion. ``` -------------------------------- ### IMAP Utility Functions Source: https://github.com/n8n-io/imap/blob/master/_autodocs/INDEX.md Helper functions for parsing MIME structures and email headers. ```javascript imaps.getParts(struct) // Flatten MIME structure imaps.parseHeader(headerText) // Parse email headers ```