======================== CODE SNIPPETS ======================== TITLE: Parse Email Content with Mailparser and imap-simple (JavaScript) DESCRIPTION: Illustrates integrating `imap-simple` with `mailparser` to parse the full content of emails, including headers and body, from an IMAP server. It requires `imap-simple`, `mailparser`, and `lodash`. The example fetches emails and then uses `simpleParser` to extract details like subject and HTML content. SOURCE: https://github.com/n8n-io/imap/blob/master/README.md#_snippet_2 LANGUAGE: javascript CODE: ``` var imaps = require('imap-simple'); const simpleParser = require('mailparser').simpleParser; const _ = require('lodash'); var config = { imap: { user: 'your@email.address', password: 'yourpassword', host: 'imap.gmail.com', port: 993, tls: true, authTimeout: 3000 } }; imaps.connect(config).then(function (connection) { return connection.openBox('INBOX').then(function () { var searchCriteria = ['1:5']; var fetchOptions = { bodies: ['HEADER', 'TEXT', ''], }; return connection.search(searchCriteria, fetchOptions).then(function (messages) { messages.forEach(function (item) { var all = _.find(item.parts, { "which": "" }) var id = item.attributes.uid; var idHeader = "Imap-Id: "+id+"\r\n"; simpleParser(idHeader+all.body, (err, mail) => { // access to the whole mail object console.log(mail.subject) console.log(mail.html) }); }); }); }); }); ``` ---------------------------------------- TITLE: Get Message Parts DESCRIPTION: A utility function to retrieve a flattened array of message parts from the `message.attributes.struct`. This is particularly useful for iterating through the different parts of a message's body, such as identifying and processing attachments. SOURCE: https://github.com/n8n-io/imap/blob/master/README.md#_snippet_8 LANGUAGE: javascript CODE: ``` getParts(struct) - **struct**: The `message.attributes.struct` object, describing the message's body structure. Returns an Array of `parts` objects, representing a flattened view of the message's body structure. ``` ---------------------------------------- TITLE: Connect to IMAP Server DESCRIPTION: The main entry point for establishing a connection to an IMAP server. It accepts connection options and can either use a callback or return a promise. The function handles connection timeouts, rejecting the promise or calling the callback with a `ConnectionTimeoutError` if the connection attempt exceeds the specified timeout. SOURCE: https://github.com/n8n-io/imap/blob/master/README.md#_snippet_7 LANGUAGE: javascript CODE: ``` connect(options, callback) - **options**: An object containing connection configuration. - **imap**: Options passed directly to the node-imap constructor. - **connectTimeout**: (Deprecated) Time in milliseconds to wait before giving up on a connection attempt. Use `options.imap.authTimeout` instead. - **callback**: An optional function with signature `(err, connection)` called upon completion. Returns a Promise that resolves with the `connection` instance (an instance of `ImapSimple`) or rejects with an error. ``` ---------------------------------------- TITLE: Configure IMAP Server Event Listeners DESCRIPTION: Demonstrates how to configure server event listeners (mail, expunge, update) within the connection configuration object for the IMAP client. SOURCE: https://github.com/n8n-io/imap/blob/master/README.md#_snippet_13 LANGUAGE: js CODE: ``` var config = { imap: { ... }, onmail: function (numNewMail) { ... }, onexpunge: function (seqno) { ... }, onupdate: function (seqno, info) { ... } }; ``` ---------------------------------------- TITLE: Retrieve Unread Email Subjects using imap-simple (JavaScript) DESCRIPTION: Demonstrates how to connect to an IMAP server, open the INBOX, search for unseen emails, and extract their subject lines. It uses `imap-simple` for connection and searching, and `node-imap` implicitly. The output is an array of subject strings. SOURCE: https://github.com/n8n-io/imap/blob/master/README.md#_snippet_0 LANGUAGE: javascript CODE: ``` var imaps = require('imap-simple'); var config = { imap: { user: 'your@email.address', password: 'yourpassword', host: 'imap.gmail.com', port: 993, tls: true, authTimeout: 3000 } }; imaps.connect(config).then(function (connection) { return connection.openBox('INBOX').then(function () { var searchCriteria = [ 'UNSEEN' ]; var fetchOptions = { bodies: ['HEADER', 'TEXT'], markSeen: false }; return connection.search(searchCriteria, fetchOptions).then(function (results) { var subjects = results.map(function (res) { return res.parts.filter(function (part) { return part.which === 'HEADER'; })[0].body.subject[0]; }); console.log(subjects); // => // [ 'Hey Chad, long time no see!', // 'Your amazon.com monthly statement', // 'Hacker Newsletter Issue #445' ] }); }); }); ``` ---------------------------------------- TITLE: ImapSimple Constructor DESCRIPTION: The constructor for creating an instance of the `ImapSimple` class. This class is primarily intended for testing purposes, allowing developers to instantiate and interact with IMAP functionalities in a controlled environment. SOURCE: https://github.com/n8n-io/imap/blob/master/README.md#_snippet_10 LANGUAGE: javascript CODE: ``` ImapSimple(imap) - **imap**: An object representing the IMAP client instance, typically from the node-imap library. Creates a new `ImapSimple` instance. ``` ---------------------------------------- TITLE: Retrieve Email Body Content with imap-simple (JavaScript) DESCRIPTION: Shows how to fetch the body content of emails within a specified range (e.g., '1:5') from an IMAP server. It utilizes `imap-simple` for connection and search, and `lodash` for data manipulation to find the 'TEXT' part of the email body. The output logs the ASCII representation of the email body. SOURCE: https://github.com/n8n-io/imap/blob/master/README.md#_snippet_1 LANGUAGE: javascript CODE: ``` var imaps = require('imap-simple'); const _ = require('lodash'); var config = { imap: { user: 'your@email.address', password: 'yourpassword', host: 'imap.gmail.com', port: 993, tls: true, authTimeout: 3000 } }; imaps.connect(config).then(function (connection) { return connection.openBox('INBOX').then(function () { var searchCriteria = ['1:5']; var fetchOptions = { bodies: ['HEADER', 'TEXT'], }; return connection.search(searchCriteria, fetchOptions).then(function (messages) { messages.forEach(function (item) { var all = _.find(item.parts, { "which": "TEXT" }) var html = (Buffer.from(all.body, 'base64').toString('ascii')); console.log(html) }); }); }); }); ``` ---------------------------------------- TITLE: ImapSimple Class API DESCRIPTION: This section details the methods available in the ImapSimple class for interacting with IMAP servers. It covers operations such as managing mailboxes, messages, flags, labels, and retrieving message data. SOURCE: https://github.com/n8n-io/imap/blob/master/README.md#_snippet_11 LANGUAGE: APIDOC CODE: ``` ImapSimple Class Methods: addFlags(uid, flag, [callback]) - Adds the provided flag(s) to the specified message(s). - Parameters: - uid: mixed (The UID of the message or an array of UIDs) - flag: string | string[] (The flag(s) to add) - callback: function (Optional. Called with (err) upon completion) - Returns: Promise (Resolves with err if no callback is provided) addMessageLabel(source, label, [callback]) - Adds the provided label(s) to the specified message(s). - Parameters: - source: mixed (A node-imap MessageSource specifying messages) - label: string | string[] (The label(s) to add) - callback: function (Optional. Called with (err) upon completion) - Returns: Promise (Resolves with err if no callback is provided) removeMessageLabel(source, label, [callback]) - Removes the provided label(s) from the specified message(s). - Parameters: - source: mixed (A node-imap MessageSource specifying messages) - label: string | string[] (The label(s) to remove) - callback: function (Optional. Called with (err) upon completion) - Returns: Promise (Resolves with err if no callback is provided) append(message, [options], [callback]) - Appends the argument message to the currently open mailbox or another mailbox. - Parameters: - message: object (A RFC-822 compatible MIME message) - options: object (Optional. Valid options are mailbox, flags, and date) - callback: function (Optional. Called with (err) upon completion) - Returns: Promise (Resolves with err if no callback is provided) delFlags(uid, flag, [callback]) - Removes the provided flag(s) from the specified message(s). - Parameters: - uid: mixed (The UID of the message or an array of UIDs) - flag: string | string[] (The flag(s) to remove) - callback: function (Optional. Called with (err) upon completion) - Returns: Promise (Resolves with err if no callback is provided) end() - Closes the connection to the IMAP server. - Returns: undefined getBoxes([callback]) - Returns the full list of mailboxes (folders). - Parameters: - callback: function (Optional. Called with (err, boxes) upon success) - Returns: Promise (Resolves with boxes upon success) getPartData(message, part, [callback]) - Downloads part data (message body part or attachment). - Parameters: - message: object (The message object) - part: object (The part object) - callback: function (Optional. Called with (err, data) upon success) - Returns: Promise (Resolves with data upon success. Data is automatically decoded.) deleteMessage(uid, [callback]) - Deletes the specified message(s). - Parameters: - uid: mixed (The UID of the message or an array of UIDs) - callback: function (Optional. Called with (err) upon completion) - Returns: Promise (Resolves with err if no callback is provided) moveMessage(source, boxName, [callback]) - Moves the specified message(s) to another mailbox. - Parameters: - source: mixed (A node-imap MessageSource specifying messages) - boxName: string (The name of the destination mailbox) - callback: function (Optional. Called with (err) upon completion) - Returns: Promise (Resolves with err if no callback is provided) openBox(boxName, [callback]) - Opens a mailbox. - Parameters: - boxName: string (The name of the mailbox to open) - callback: function (Optional. Called with (err, boxName) upon success) - Returns: Promise (Resolves with boxName upon success) closeBox([autoExpunge = true], [callback]) - Closes the currently open mailbox. - Parameters: - autoExpunge: boolean (Optional, defaults to true. If true, messages marked as Deleted are removed.) - callback: function (Optional. Called with (err) upon completion) - Returns: Promise (Resolves with err if no callback is provided) addBox(boxName, [callback]) - Creates a mailbox. - Parameters: - boxName: string (The name of the mailbox to create) - callback: function (Optional. Called with (err, boxName) upon success) - Returns: Promise (Resolves with boxName upon success) delBox(boxName, [callback]) - Deletes a mailbox. - Parameters: - boxName: string (The name of the mailbox to delete) - callback: function (Optional. Called with (err, boxName) upon success) - Returns: Promise (Resolves with boxName upon success) search(searchCriteria, [fetchOptions], [callback]) - Searches for and retrieves mail in the currently open mailbox. - Parameters: - searchCriteria: object (Criteria for searching mail, same format as node-imap) - fetchOptions: object (Optional. Options for fetching results) - callback: function (Optional. Called with results upon completion) - Returns: Promise (Resolves with search results upon success) ``` ---------------------------------------- TITLE: Download Attachments from Unread Emails DESCRIPTION: Fetches all unread emails received since yesterday and downloads any attachments associated with them. It requires the 'imap-simple' library and IMAP server configuration. SOURCE: https://github.com/n8n-io/imap/blob/master/README.md#_snippet_3 LANGUAGE: javascript CODE: ``` var imaps = require('imap-simple'); var config = { imap: { user: 'your@email.address', password: 'yourpassword', host: 'imap.gmail.com', port: 993, tls: true, authTimeout: 3000 } }; imaps.connect(config).then(function (connection) { connection.openBox('INBOX').then(function () { // Fetch emails from the last 24h var delay = 24 * 3600 * 1000; var yesterday = new Date(); yesterday.setTime(Date.now() - delay); yesterday = yesterday.toISOString(); var searchCriteria = ['UNSEEN', ['SINCE', yesterday]]; var fetchOptions = { bodies: ['HEADER.FIELDS (FROM TO SUBJECT DATE)'], struct: true }; // retrieve only the headers of the messages return connection.search(searchCriteria, fetchOptions); }).then(function (messages) { var attachments = []; messages.forEach(function (message) { var parts = imaps.getParts(message.attributes.struct); attachments = attachments.concat(parts.filter(function (part) { return part.disposition && part.disposition.type.toUpperCase() === 'ATTACHMENT'; }).map(function (part) { // retrieve the attachments only of the messages with attachments return connection.getPartData(message, part) .then(function (partData) { return { filename: part.disposition.params.filename, data: partData }; }); })); }); return Promise.all(attachments); }).then(function (attachments) { console.log(attachments); // => // [ { filename: 'cats.jpg', data: Buffer() }, // { filename: 'pay-stub.pdf', data: Buffer() } ] }); }); ``` ---------------------------------------- TITLE: IMAP Fetch Results Structure DESCRIPTION: Details the format of results returned from a successful IMAP search and fetch operation. Each item includes message attributes and its parts. SOURCE: https://github.com/n8n-io/imap/blob/master/README.md#_snippet_12 LANGUAGE: js CODE: ``` // [{ // attributes: object, // parts: [ { which: string, size: number, body: string }, ... ] // }, ...] ``` ---------------------------------------- TITLE: Open, Read, and Mark Messages for Deletion DESCRIPTION: Connects to the IMAP server, opens the INBOX, fetches all messages, reads their content (if plain text and not base64 encoded), and marks each message for deletion. Finally, it closes the mailbox and disconnects. SOURCE: https://github.com/n8n-io/imap/blob/master/README.md#_snippet_5 LANGUAGE: javascript CODE: ``` imaps.connect(config).then(function (connection) { connection.openBox('INBOX').then(function () { var searchCriteria = ['ALL']; var fetchOptions = { bodies: ['TEXT'], struct: true }; return connection.search(searchCriteria, fetchOptions); //Loop over each message }).then(function (messages) { let taskList = messages.map(function (message) { return new Promise((res, rej) => { var parts = imaps.getParts(message.attributes.struct); parts.map(function (part) { return connection.getPartData(message, part) .then(function (partData) { //Display e-mail body if (part.disposition == null && part.encoding != "base64"){ console.log(partData); } //Mark message for deletion connection.addFlags(message.attributes.uid, "\Deleted", (err) => { if (err){ console.log('Problem marking message for deletion'); rej(err); } res(); //Final resolve }) }); }); }); }) return Promise.all(taskList).then(() => { connection.imap.closeBox(true, (err) => { //Pass in false to avoid delete-flagged messages being removed if (err){ console.log(err); } }); connection.end(); }); }); }); ``` ---------------------------------------- TITLE: Append Message to Drafts Folder DESCRIPTION: Appends a new plain text email message to the 'Drafts' folder and marks it with the \Draft flag. Requires IMAP connection configuration. SOURCE: https://github.com/n8n-io/imap/blob/master/README.md#_snippet_4 LANGUAGE: javascript CODE: ``` var imaps = require('imap-simple'); var config = { imap: { user: 'your@email.address', password: 'yourpassword', host: 'imap.gmail.com', port: 993, tls: true, authTimeout: 3000 } }; imaps.connect(config).then(function (connection) { const message = `Content-Type: text/plain To: jhannes@gmail.com Subject: Hello world Hi This is a test message `; connection.append(message.toString(), {mailbox: 'Drafts', flags: '\Draft'}); }); ``` ---------------------------------------- TITLE: Delete Messages by UID DESCRIPTION: Connects to the IMAP server, searches for messages, filters them based on the recipient ('bob@example.com'), extracts their UIDs, and then deletes the selected messages. SOURCE: https://github.com/n8n-io/imap/blob/master/README.md#_snippet_6 LANGUAGE: javascript CODE: ``` imaps.connect(config).then(connection => { return connection.openBox('INBOX') .then(() => connection.search(['ALL'], {bodies: ['HEADER']})) .then( messages => { // select messages from bob const uidsToDelete = messages .filter( message => { return message.parts .filter( part => part.which === 'HEADER')[0].body.to[0] === 'bob@example.com'; }) .map(message => message.attributes.uid); return connection.deleteMessage(uidsToDelete); }); }); ``` ---------------------------------------- TITLE: ConnectionTimeoutError Class DESCRIPTION: An error class specifically designed to indicate that an IMAP connection attempt has timed out. Instances of this error are thrown or passed to callbacks when the connection process exceeds the configured timeout duration. SOURCE: https://github.com/n8n-io/imap/blob/master/README.md#_snippet_9 LANGUAGE: javascript CODE: ``` errors.ConnectionTimeoutError(timeout) - **timeout**: The timeout value in milliseconds that caused the error. This class represents a timeout error during connection attempts. ```