### ListHeader Example Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/types.md An example of the structure for a parsed ListHeader, demonstrating mailing list metadata. ```javascript { post: { mail: 'list@example.com' }, unsubscribe: { url: 'https://example.com/unsubscribe' } } ``` -------------------------------- ### AddressHeader Example Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/types.md An example of the structure for a parsed AddressHeader, including parsed addresses, HTML representation, and plain text. ```javascript { value: [ { name: 'John Doe', address: 'john@example.com' } ], html: 'John Doe <john@example.com>', text: '"John Doe" ' } ``` -------------------------------- ### MailParser Initialization Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/architecture.md Illustrates the initialization phase of the MailParser class, including stream setup and event handler configuration. ```javascript new MailParser(config) ├─ Create ChunkedPassthrough stream ├─ Create Splitter from mailsplit ├─ Initialize state (tree, headers, etc.) ├─ Setup event handlers │ ├─ splitter 'readable' → readData() │ ├─ splitter 'end' → endStream() │ └─ splitter 'error' → emit 'error' └─ Initialize decoders (Iconv or iconv-lite) ``` -------------------------------- ### HeaderValue Example Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/types.md Example of a parsed HeaderValue, showing the main value and any associated parameters. ```javascript // Content-Type: text/html; charset=utf-8; boundary="xyz" { value: 'text/html', params: { charset: 'utf-8', boundary: 'xyz' } } ``` -------------------------------- ### Attachment Example Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/types.md Provides an example of the structure for a parsed email attachment, detailing properties like filename, contentType, and checksum. ```javascript { type: 'attachment', filename: 'document.pdf', contentType: 'application/pdf', contentDisposition: 'attachment', cid: undefined, headers: Map { 'content-type' => {...}, ... }, partId: '2', related: false, checksum: 'a1b2c3d4e5f6...', size: 50000 } ``` -------------------------------- ### HeaderLine Example Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/types.md Example of a raw HeaderLine object, containing the lowercase header key and the full header line value. ```javascript { key: 'subject', line: 'This is the subject line' } ``` -------------------------------- ### Address Header Example Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/types.md Illustrates the structure returned when an address header is parsed, showing the 'value' array containing name and address pairs, along with 'html' and 'text' representations. ```javascript // Address header returns this structure: { value: [ { name: 'John Doe', address: 'john@example.com' }, { name: 'Jane Smith', address: 'jane@example.com' } ], html: '...', text: '"John Doe" , "Jane Smith" ' } ``` -------------------------------- ### Custom Date Formatting Configuration Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/configuration.md Demonstrates how to use simpleParser with a custom date formatting function. The provided example shows how to format the date to RFC822 (UTC string) or ISO format, or a custom string. ```javascript const { simpleParser } = require('mailparser'); const mail = await simpleParser(input, { formatDateString: (date) => { // Return RFC822 formatted date return date.toUTCString(); // Or ISO format // return date.toISOString(); // Or custom format // return date.getFullYear() + '-' + // String(date.getMonth() + 1).padStart(2, '0') + '-' + // String(date.getDate()).padStart(2, '0'); } }); console.log(mail.date); // Uses custom formatter ``` -------------------------------- ### Install mailparser via npm Source: https://github.com/nodemailer/mailparser/blob/master/README.md Use this command in your terminal to add the mailparser package to your project dependencies. ```bash $ npm install mailparser ``` -------------------------------- ### Basic Streaming Usage with MailParser Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/mailparser.md Demonstrates how to use MailParser for basic email streaming. It pipes an input stream to the parser, listens for 'headers', 'data', 'error', and 'end' events, and includes an example of updating image links upon completion. ```javascript const fs = require('fs'); const { MailParser } = require('mailparser'); const parser = new MailParser(); const input = fs.createReadStream('email.eml'); input.pipe(parser); parser.on('headers', (headers) => { console.log('Subject:', headers.get('subject')); console.log('From:', headers.get('from')); }); parser.on('data', (data) => { if (data.type === 'attachment') { // Collect attachment data const chunks = []; data.content.on('data', chunk => chunks.push(chunk)); data.content.on('end', () => { const buffer = Buffer.concat(chunks); console.log(`Saved ${data.filename}: ${buffer.length} bytes`); data.release(); // IMPORTANT: release before next message part }); } else if (data.type === 'text') { console.log('Text:', data.text); console.log('HTML:', data.html); } }); parser.on('error', (err) => { console.error('Parse error:', err); }); parser.on('end', () => { console.log('Parsing complete'); // Update CID image links to data URLs parser.updateImageLinks( (attachment, done) => { const dataUrl = 'data:' + attachment.contentType + ';base64,' + attachment.content.toString('base64'); done(null, dataUrl); }, (err, html) => { if (!err && html) console.log('Updated HTML:', html); } ); }); ``` -------------------------------- ### Process Email from Database Blob Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/QUICK_START.md Parse an email that has been stored as a blob in a database. This example assumes you can retrieve the email content as a buffer. ```javascript const emailBuffer = await db.getEmailBlob(emailId); const mail = await simpleParser(emailBuffer); ``` -------------------------------- ### Internal Usage Pattern of StreamHash Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/streamhash.md Demonstrates the internal mechanism by which MailParser utilizes StreamHash. It shows how to pipe attachment data through the hasher and finalize it to get checksum and size. ```javascript // This is how MailParser uses StreamHash internally const hasher = new StreamHash(attachment, 'md5'); node.decoder.on('readable', () => { let chunk; while ((chunk = node.decoder.read()) !== null) { hasher.write(chunk); } }); node.decoder.once('end', () => { hasher.end(); // Now attachment.checksum and attachment.size are set }); ``` -------------------------------- ### Handle Email with Embedded Images (Data URLs) Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/README.md By default, `simpleParser` converts `cid:` embedded images to data URLs, making them viewable directly in HTML. This example shows how to access the HTML with these converted images. ```javascript const { simpleParser } = require('mailparser'); const mail = await simpleParser(emailStream); // By default, cid: images are converted to data URLs // This allows viewing in browsers without additional requests console.log(mail.html); // ``` -------------------------------- ### Equivalent MailParser and simpleParser Options Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/configuration.md Demonstrates that both MailParser and simpleParser accept the same core configuration options for consistency. ```javascript // These are equivalent const parser = new MailParser({ checksumAlgo: 'sha256', skipTextLinks: true }); const mail = await simpleParser(input, { checksumAlgo: 'sha256', skipTextLinks: true }); ``` -------------------------------- ### Promise-based Parsing with simpleParser Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/simpleparser.md Demonstrates how to use simpleParser with Promises to parse email content from a file stream, Buffer, or string. This is the recommended approach. ```javascript const fs = require('fs'); const { simpleParser } = require('mailparser'); // From file stream const mail = await simpleParser(fs.createReadStream('email.eml')); console.log('Subject:', mail.subject); console.log('From:', mail.from?.text); console.log('Text:', mail.text); // From Buffer const buffer = fs.readFileSync('email.eml'); const mail = await simpleParser(buffer); // From string const emailString = fs.readFileSync('email.eml', 'utf8'); const mail = await simpleParser(emailString); ``` -------------------------------- ### Get and Format Date Header Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/QUICK_START.md Access the 'date' header from parsed email content, which is returned as a JavaScript Date object. Format the date using methods like toISOString() and toUTCString(). ```javascript const mail = await simpleParser(input); console.log(mail.date); // Date object console.log(mail.date.toISOString()); console.log(mail.date.toUTCString()); ``` -------------------------------- ### Parse Email with All Options Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/README.md Demonstrates advanced usage of simpleParser with various options to control content handling, security, performance, and custom formatting. This allows fine-grained control over the parsing process. ```javascript const { simpleParser } = require('mailparser'); const mail = await simpleParser(emailStream, { // Content handling skipHtmlToText: false, skipTextToHtml: false, skipTextLinks: false, skipImageLinks: false, // Security/performance checksumAlgo: 'sha256', maxHtmlLengthToParse: 5 * 1024 * 1024, // Custom formatting formatDateString: (date) => date.toISOString() }); console.log(mail.subject); console.log(mail.from?.text); console.log(mail.text); console.log(mail.html); mail.attachments.forEach(att => { console.log(`${att.filename}: ${att.size} bytes, ${att.checksum}`); }); ``` -------------------------------- ### Accessing and Iterating Headers Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/types.md Demonstrates how to access the headers Map, retrieve specific header values, and iterate over all header entries. ```javascript const headers = parser.headers; // or mail.headers in simpleParser // Get single value const subject = headers.get('subject'); // Get all entries for (const [key, value] of headers) { console.log(key, value); } // Check if key exists if (headers.has('message-id')) { const msgId = headers.get('message-id'); } ``` -------------------------------- ### Parse Email with Configuration Options Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/QUICK_START.md Customize the parsing behavior using configuration options with simpleParser. Options include skipping HTML to text conversion, linkification, and attachment checksum algorithms. ```javascript const mail = await simpleParser(input, { skipHtmlToText: false, // Generate text from HTML if missing skipTextToHtml: false, // Generate HTML from text if missing skipTextLinks: false, // Linkify URLs skipImageLinks: false, // Convert CID images to data URLs checksumAlgo: 'sha256', // Use SHA-256 for attachments maxHtmlLengthToParse: 10*1024*1024 // 10MB HTML limit }); ``` -------------------------------- ### Import MailParser and simpleParser Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/README.md Import the necessary classes and functions from the mailparser library. ```javascript const { MailParser, simpleParser } = require('mailparser'); ``` -------------------------------- ### Handle Image CID Links Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/configuration.md Configure how `cid:` references in HTML are handled, either by converting them to data URLs or keeping them as references. ```javascript // Default behavior (convert CID to data URL) const mail1 = await simpleParser(email); // becomes // // Keep CID references const mail2 = await simpleParser(email, { keepCidLinks: true }); // stays unchanged // Disable CID conversion in MailParser const parser = new MailParser({ skipImageLinks: true }); // CID links remain in HTML, can be custom-processed ``` -------------------------------- ### MailParser Constructor Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/mailparser.md Initializes a new MailParser instance. The constructor accepts an optional configuration object to customize parser behavior, such as character encoding, checksum algorithms, and content processing options. ```APIDOC ## new MailParser(config) ### Description Initializes a new MailParser instance with optional configuration. ### Parameters #### Request Body - **config** (object) - Optional - Configuration object for parser behavior. - **Iconv** (class) - Optional - Custom Iconv module for character encoding. Defaults to `iconv-lite`. - **checksumAlgo** (string) - Optional - Algorithm for calculating attachment checksums. Defaults to 'md5'. - **keepDeliveryStatus** (boolean) - Optional - Whether to keep `message/delivery-status` parts. Defaults to false. - **skipHtmlToText** (boolean) - Optional - Skip HTML-to-text conversion. Defaults to false. - **skipTextToHtml** (boolean) - Optional - Skip text-to-HTML conversion. Defaults to false. - **skipTextLinks** (boolean) - Optional - Do not linkify URLs and email addresses in plaintext. Defaults to false. - **skipImageLinks** (boolean) - Optional - Do not convert `cid:` references to data URLs for embedded images. Defaults to false. - **maxHtmlLengthToParse** (number) - Optional - Maximum HTML size in bytes before skipping conversion. Defaults to Infinity. - **formatDateString** (function) - Optional - Custom date formatter function. ``` -------------------------------- ### MailParser Constructor Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/mailparser.md Instantiate the MailParser class. An optional configuration object can be provided to customize parser behavior. ```javascript new MailParser(config) ``` -------------------------------- ### Minimal Mailparser Configuration Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/configuration.md Uses all default settings for simpleParser. No specific configuration is provided. ```javascript const { simpleParser } = require('mailparser'); // Uses all defaults const mail = await simpleParser(input); ``` -------------------------------- ### Configure Checksum Algorithm Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/configuration.md Set the checksum algorithm for attachments. Defaults to MD5. SHA-256 is recommended for security. ```javascript const parser = new MailParser({ checksumAlgo: 'md5' }); ``` ```javascript const parser = new MailParser({ checksumAlgo: 'sha1' }); ``` ```javascript const parser = new MailParser({ checksumAlgo: 'sha256' }); ``` ```javascript const parser = new MailParser({ checksumAlgo: 'sha512' }); ``` ```javascript const parser = new MailParser({ checksumAlgo: 'blake2b512' }); ``` -------------------------------- ### simpleParser Buffering Memory Management Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/architecture.md Explains the buffering approach of simpleParser, where all attachments are accumulated in memory as Buffers. This results in an O(email_size) memory profile, holding the entire email content. ```text Input Stream │ ├─► MailParser (as above) │ ├─ On 'data' events: │ └─► For attachments: buffer to Buffer │ (accumulated in memory) │ └─► Final: ParsedMail with all attachments as Buffers **Memory Profile:** - O(email_size) - Entire email buffered in memory - All attachments held as Buffers ``` -------------------------------- ### Callback-based Parsing with simpleParser Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/simpleparser.md Shows how to use simpleParser with a callback function to handle email parsing asynchronously. This method returns undefined. ```javascript const fs = require('fs'); const { simpleParser } = require('mailparser'); simpleParser(fs.createReadStream('email.eml'), (err, mail) => { if (err) { console.error('Parse error:', err); return; } console.log('Parsed successfully'); console.log('Subject:', mail.subject); }); ``` -------------------------------- ### Special Behavior Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/simpleparser.md Explains special behaviors of `simpleParser`, including image link conversion (CID to data URLs), automatic HTML to text and text to HTML conversions, and text linkification. ```APIDOC ## Special Behavior ### Image Link Conversion By default, `simpleParser` converts all `cid:` image references in HTML to data URLs: ```javascript // Input HTML: // Output HTML: ``` Set `keepCidLinks: true` to preserve original `cid:` references. ### HTML to Text Conversion When `text` is not present but `html` is, plaintext is automatically generated from HTML unless `skipHtmlToText: true`. ### Text to HTML Conversion When `html` is not present but `text` is, HTML is automatically generated from plaintext unless `skipTextToHtml: true`. ### Text Linkification URLs and email addresses in plaintext are automatically converted to HTML links unless `skipTextLinks: true`. ``` -------------------------------- ### Address Object Structure Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/simpleparser.md Illustrates the structure of address objects returned by simpleParser for email headers. This includes the 'value' array, and 'html' and 'text' representations. ```javascript { value: [ { name?: string, // Display name address: string // Email address } ], html: string, // HTML formatted addresses text: string // Plain text formatted addresses } ``` ```javascript mail.from.value = [ { name: 'John Doe', address: 'john@example.com' } ]; mail.from.text = '"John Doe" '; mail.from.html = 'John Doe <john@example.com>'; ``` -------------------------------- ### Content Size Limits Configuration Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/configuration.md Configures MailParser with a maximum HTML length to parse (10MB) to prevent timeouts on large HTML content. Includes an error handler to log warnings for oversized HTML. ```javascript const { MailParser } = require('mailparser'); const parser = new MailParser({ maxHtmlLengthToParse: 10 * 1024 * 1024 // 10MB - prevent timeout on large HTML }); parser.on('error', (err) => { if (err.message.includes('HTML too long')) { console.warn('HTML content too large, skipping conversion'); } }); ``` -------------------------------- ### Handle Source Stream Errors Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/errors.md Use .catch() on the promise returned by simpleParser to handle errors originating from the input stream, such as file not found or permission issues. ```javascript const { simpleParser } = require('mailparser'); simpleParser(fs.createReadStream('email.eml')) .catch(err => { if (err.code === 'ENOENT') { console.error('File not found'); } else if (err.code === 'EACCES') { console.error('Permission denied'); } else { console.error('Stream error:', err.message); } }); ``` -------------------------------- ### Custom Encoding Configuration with Native Iconv Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/configuration.md Sets up MailParser to use a custom Iconv module instance, specifically the native Iconv, for character encoding beyond what iconv-lite supports. Also configures the checksum algorithm to SHA256. ```javascript const Iconv = require('iconv'); const { MailParser } = require('mailparser'); // Use native Iconv instead of iconv-lite for better compatibility const parser = new MailParser({ Iconv: Iconv, checksumAlgo: 'sha256' }); ``` -------------------------------- ### Optimize for Performance Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/QUICK_START.md Configure mailparser to skip certain processing steps like HTML to text conversion, text to HTML conversion, linkification, and image link conversion to improve performance. Also allows setting a faster checksum algorithm and a maximum HTML parse length. ```javascript const mail = await simpleParser(input, { skipHtmlToText: true, // Don't convert HTML to text skipTextToHtml: true, // Don't convert text to HTML skipTextLinks: true, // Don't linkify skipImageLinks: true, // Don't convert CID checksumAlgo: 'md5', // Faster than SHA maxHtmlLengthToParse: 1024 * 1024 // 1MB limit }); ``` -------------------------------- ### MailParser Configuration for Checksum Algorithm Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/streamhash.md Configures MailParser to use a specific hash algorithm (e.g., 'sha256') for attachments instead of the default 'md5'. The resulting checksum and size are available in the 'data' event for attachments. ```javascript const { MailParser } = require('mailparser'); const parser = new MailParser({ checksumAlgo: 'sha256' // Use SHA-256 instead of MD5 }); parser.on('data', (data) => { if (data.type === 'attachment') { console.log(data.checksum); // hex string of SHA-256 hash console.log(data.size); // total bytes } }); ``` -------------------------------- ### Performance-Optimized Mailparser Configuration Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/configuration.md Optimizes simpleParser for performance by skipping various content conversions like HTML-to-text, text-to-HTML, text linkification, and CID link conversion, while also setting a 1MB HTML parsing limit. ```javascript const { simpleParser } = require('mailparser'); const mail = await simpleParser(input, { skipHtmlToText: true, // Skip HTML-to-text conversion skipTextToHtml: true, // Skip text-to-HTML conversion skipTextLinks: true, // Don't linkify text skipImageLinks: true, // Don't convert CID links maxHtmlLengthToParse: 1024 * 1024 // 1MB limit }); ``` -------------------------------- ### Mailparser Finalization Logic Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/architecture.md Illustrates the steps taken when the input stream ends, including decoder cleanup, text content extraction, and event emission. This is crucial for understanding how the parser finalizes its work. ```javascript endStream() ├─ End current decoder stream └─ If in simpleParser: └─ cleanup() ├─ End all open decoders ├─ getTextContent() │ ├─ Traverse MIME tree │ ├─ Merge text parts │ ├─ htmlToText() if needed │ └─ textToHtml() if needed ├─ Emit final 'text' data event └─ Emit 'end' event In simpleParser: ├─ Collect all data events ├─ updateImageLinks() │ ├─ Find cid: references in HTML │ ├─ Match to attachment objects │ ├─ Call replaceCallback per CID │ └─ Replace references with URLs └─ Resolve promise with ParsedMail ``` -------------------------------- ### Use Secure Hash (SHA-256) Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/QUICK_START.md Specify 'sha256' for attachment checksum calculation instead of the default 'md5'. This is useful for ensuring data integrity with a stronger hashing algorithm. ```javascript const mail = await simpleParser(input, { checksumAlgo: 'sha256' // Instead of default 'md5' }); mail.attachments.forEach(att => { console.log(`${att.filename}: ${att.checksum}`); // SHA-256 hash of attachment }); ``` -------------------------------- ### StreamHash Constructor Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/streamhash.md Instantiates a new StreamHash object. The attachment object will be updated with checksum and size properties upon stream completion. The hash algorithm can be specified, defaulting to 'md5'. ```javascript new StreamHash(attachment, algo) ``` -------------------------------- ### Provide Custom Iconv for Encoding Issues Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/README.md For emails with unusual character encodings that `iconv-lite` might not handle, you can provide a custom `Iconv` implementation to the `MailParser` constructor. ```javascript const Iconv = require('iconv'); const parser = new MailParser({ Iconv }); ``` -------------------------------- ### Header Processing Pipeline Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/architecture.md Visualizes the flow for processing raw email headers, including decoding, type determination, and specialized parsing for different header categories. It highlights the use of addressparser and other utilities. ```text Raw header line │ ▼ decodeHeader() ◄─── Decode RFC 2047 encoded-words │ ▼ Determine header type │ ┌──────┴────────────────────────────────────────────────┐ │ │ ▼ ▼ ▼ ▼ Address Headers Content Headers Date Headers Priority Headers │ │ │ │ ▼ ▼ ▼ ▼ addressparser() parseHeaderValue() new Date() parsePriority() │ │ │ │ decodeAddresses() decodeWords() Validate Map to getAddressesHTML()│ Parsing 'low'/'normal'/'high' getAddressesText()└─► Process params│ │ (charset, etc.) │ Special checks: └─►Date object ├─ Punycode IDN ├─ Encoded-word security └─ Re-parsing rules │ ▼ Headers Map (key → processed value) ``` -------------------------------- ### Address Objects Structure Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/simpleparser.md Describes the structure of address objects returned for email address headers, including `value`, `html`, and `text` properties. ```APIDOC ## Address Objects Address objects returned for address headers have this structure: ```javascript { value: [ { name?: string, // Display name address: string // Email address } ], html: string, // HTML formatted addresses text: string // Plain text formatted addresses } ``` Example: ```javascript mail.from.value = [ { name: 'John Doe', address: 'john@example.com' } ]; mail.from.text = '"John Doe" '; mail.from.html = 'John Doe <john@example.com>'; ``` ``` -------------------------------- ### Use Custom Iconv for Character Encodings Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/configuration.md Integrate the native `iconv` module for parsing emails with uncommon character encodings, offering broader support than `iconv-lite`. ```javascript const Iconv = require('iconv'); const { MailParser } = require('mailparser'); // Use when parsing emails with uncommon charsets // iconv-lite supports ~80 encodings // native Iconv via libiconv supports ~200+ encodings const parser = new MailParser({ Iconv: Iconv, checksumAlgo: 'sha256' }); ``` -------------------------------- ### Mailparser Architecture Diagram Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/architecture.md Visual representation of the mailparser's multi-layered architecture, showing user interaction points, internal components, and external dependencies. ```text ┌─────────────────────────────────────────────────────────────┐ │ User Code │ │ │ │ simpleParser(input, options) │ new MailParser(options) │ └──────────────┬──────────────────────────────┬───────────────┘ │ │ ┌───────┴─────────────────────┬────────┴────────┐ │ │ │ ┌──▼──────────────────────┐ ┌──▼───────────────┐ │ │ simpleParser wrapper │ │ MailParser │ │ │ │ │ (Transform) │ │ │ - Promises/callbacks │ │ - Streaming │ │ │ - Buffer all data │ │ - Emits events │ │ │ - Return ParsedMail │ │ - Low memory │ │ └──┬───────────────────────┘ └──┬───────────────┘ │ │ │ │ └────────────┬───────────────┘ │ │ │ ┌──────────▼──────────────────────────────┐ │ │ Internal: MailParser Instance │ │ │ │ │ │ - ChunkedPassthrough stream │ │ │ - Splitter (from mailsplit) │ │ │ - MIME tree structure │ │ │ - Header processing │ │ │ - Content extraction │ │ └──────────┬──────────────────────────────┘ │ │ │ ┌──────────▼──────────────────────────────┐ │ │ Dependencies │ │ │ │ │ │ - @zone-eu/mailsplit: MIME parsing │ │ │ - libmime: Header parsing │ │ │ - iconv-lite/Iconv: Encoding │ │ │ - html-to-text: HTML conversion │ │ │ - linkify-it: URL detection │ │ │ - nodemailer: Address parsing │ │ │ - encoding-japanese: JP charsets │ │ └──────────────────────────────────────────┘ │ │ └───────────────────────────────────────────────────────┘ ``` -------------------------------- ### Parse Email with Options Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/simpleparser.md Parses an email stream using simpleParser with various options to control HTML/text conversion, link handling, and date formatting. Useful for customizing the parsing process based on specific needs. ```javascript const { simpleParser } = require('mailparser'); const mail = await simpleParser(emailStream, { skipHtmlToText: true, skipTextToHtml: true, skipTextLinks: true, skipImageLinks: true, maxHtmlLengthToParse: 1024 * 1024, // 1MB max formatDateString: (date) => date.toISOString() }); console.log('Text:', mail.text); console.log('HTML:', mail.html); // Process attachments mail.attachments.forEach(attachment => { console.log(`${attachment.filename}: ${attachment.size} bytes`); console.log(`Type: ${attachment.contentType}`); console.log(`Checksum: ${attachment.checksum}`); if (attachment.filename) { fs.writeFileSync(attachment.filename, attachment.content); } }); ``` -------------------------------- ### Simple Parser for In-Memory Email Processing Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/configuration.md Use the simpleParser function for loading an entire email into memory. All attachments will be available as buffers. ```javascript const { simpleParser } = require('mailparser'); const mail = await simpleParser(input); // All attachments are now in memory as buffers ``` -------------------------------- ### textToHtml Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/header-processing.md Converts plain text content into HTML, automatically linkifying URLs and email addresses, and applying paragraph formatting. ```APIDOC ## textToHtml(str) ### Description Converts plain text to HTML, including linkification and paragraph formatting. ### Method `textToHtml(str: string): string` ### Parameters #### Path Parameters - **str** (string) - Required - The plain text content to convert. ### Returns A string containing the HTML-formatted text. ### Processing 1. HTML-encodes special characters. 2. Linkifies URLs and email addresses (unless `skipTextLinks` option is true). 3. Wraps content in `

` tags. 4. Converts multiple newlines to `

` breaks. 5. Converts single newlines to `
` tags. ### Linkification Uses the `linkify-it` library with support for full TLD lists, Twitter mentions, fuzzy detection, and Git protocols. ### Security - URL quotes are escaped in `href` attributes. - Email addresses are HTML-encoded. - Content is properly escaped for HTML. ### Example ```javascript const text = 'Check out https://example.com\n\nThis is a new paragraph'; parser.textToHtml(text); //

Check out https://example.com

This is a new paragraph

``` ``` -------------------------------- ### Configure Mailparser for High Volume Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/configuration.md Reuse parser configuration for high-volume processing by setting specific options like checksum algorithm and skipping certain content types. ```javascript const { MailParser } = require('mailparser'); // Reuse parser configuration const options = { checksumAlgo: 'md5', // Faster than SHA skipTextLinks: true, skipImageLinks: true, skipTextToHtml: true }; // For each email const parser = new MailParser(options); // ... process ``` -------------------------------- ### Promise-Based Error Handling with try-catch Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/errors.md Use a try-catch block when using `simpleParser` to handle potential errors during parsing. Differentiate between common error types like TypeError for invalid input or 'ENOENT' for file not found. ```javascript const { simpleParser } = require('mailparser'); try { const mail = await simpleParser(input, options); console.log('Parsed:', mail.subject); } catch (err) { if (err instanceof TypeError) { console.error('Invalid input:', err.message); } else if (err.code === 'ENOENT') { console.error('File not found'); } else { console.error('Parse error:', err.message); } } ``` -------------------------------- ### getAddressesText Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/header-processing.md Formats an array of address objects into a plain text string. ```APIDOC ## getAddressesText(value) ### Description Formats an array of address objects into a plain text string. ### Method `getAddressesText(value: array): string` ### Parameters #### Path Parameters - **value** (array) - Required - Array of address objects, where each object can have `name` and `address` properties. ### Returns A string containing plain text formatted addresses. ### Format - With name: `"John Doe" ` - Without name: `john@example.com` - Groups: `"Group Name": member1, member2;` ### Example ```javascript const addresses = [ { name: 'John Doe', address: 'john@example.com' } ]; const text = parser.getAddressesText(addresses); // "John Doe" ``` ``` -------------------------------- ### Import mailparser in Node.js Source: https://github.com/nodemailer/mailparser/blob/master/README.md Require the mailparser module to begin using its parsing functionality in your script. ```javascript const mailparser = require('mailparser'); ``` -------------------------------- ### MailParser Methods Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/mailparser.md Provides methods for writing data chunks to the parser and signaling completion. ```APIDOC ## write(chunk, encoding, callback) ### Description Writes a data chunk to the parser. This method is part of the Transform stream interface. ### Method write ### Parameters #### Request Body - **chunk** (Buffer/string) - Required - Email data chunk. - **encoding** (string) - Optional - Encoding of chunk if string. Defaults to 'utf8'. - **callback** (function) - Optional - Called when chunk is processed. ### Returns boolean indicating if backpressure was applied. ``` ```APIDOC ## end(chunk, encoding, callback) ### Description Finishes writing data to the parser and signals completion of the stream. ### Method end ### Parameters #### Request Body - **chunk** (Buffer/string) - Optional - Final data chunk. - **encoding** (string) - Optional - Encoding if chunk is string. - **callback** (function) - Optional - Called when stream ends. ### Returns void ``` -------------------------------- ### pipe(destination, options) Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/mailparser.md Pipes the parser output to another stream. This is useful for processing parsed email content in chunks or sending it to another destination. ```APIDOC ## pipe(destination, options) ### Description Pipes the parser output to another stream. This is useful for processing parsed email content in chunks or sending it to another destination. ### Parameters #### Path Parameters - **destination** (Stream) - Required - Target stream for parsed data. - **options** (object) - Optional - Stream options like `{ end: true }`. ### Returns destination stream for chaining ``` -------------------------------- ### Handling Raw Header Lines Event Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/mailparser.md Listen for the 'headerLines' event to access the raw header lines of the email. This event emits an array of objects, each containing a 'key' and the 'line' itself. ```javascript parser.on('headerLines', (lines) => { // lines is an array of raw header line objects }); ``` -------------------------------- ### Format Addresses as HTML Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/header-processing.md Formats an array of address objects into an HTML string with mailto links. Ensures proper escaping for security and applies specific CSS classes for styling. ```javascript getAddressesHTML(value) ``` ```javascript const addresses = [ { name: 'John Doe', address: 'john@example.com' } ]; const html = parser.getAddressesHTML(addresses); // John Doe <john@example.com> ``` -------------------------------- ### processHeaders(lines) Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/header-processing.md Parses raw header lines into a Map with decoded values. It handles special processing for content, address, priority, message identity, date, and list headers. ```APIDOC ## processHeaders(lines) ### Description Parse raw header lines into a Map with decoded values. Handles special processing based on header name for content, address, priority, message identity, date, and list headers. ### Method ```javascript processHeaders(lines) ``` ### Parameters #### Path Parameters - **lines** (array) - Required - Array of header line objects from mailsplit ### Response Map with lowercase header names as keys ### Request Example ```javascript const lines = [ { key: 'from', line: 'John Doe ' }, { key: 'subject', line: 'Test Subject' }, { key: 'date', line: 'Wed, 3 Jun 2020 22:50:46 GMT' } ]; const headers = parser.processHeaders(lines); console.log(headers.get('from')); // { value: [...], html: '...', text: '...' } console.log(headers.get('subject')); // 'Test Subject' console.log(headers.get('date')); // Date object ``` ``` -------------------------------- ### Handle HTML Too Long Error Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/errors.md Configure maxHtmlLengthToParse and listen for 'error' events to manage cases where HTML content exceeds the defined size limit. ```javascript const { MailParser } = require('mailparser'); const parser = new MailParser({ maxHtmlLengthToParse: 100 * 1024 // 100KB limit }); parser.on('error', (err) => { if (err.message.includes('HTML too long')) { console.warn('Skipping HTML parsing, too large'); } }); ``` -------------------------------- ### getAddressesHTML Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/header-processing.md Formats an array of address objects into an HTML string, including mailto links and appropriate CSS classes for styling. ```APIDOC ## getAddressesHTML(value) ### Description Formats an array of address objects into an HTML string with mailto links. ### Method `getAddressesHTML(value: array): string` ### Parameters #### Path Parameters - **value** (array) - Required - Array of address objects, where each object can have `name` and `address` properties. ### Returns A string containing HTML-formatted addresses with CSS classes (`.mp_address_group`, `.mp_address_name`, `.mp_address_email`). ### Security - HTML-encodes email addresses. - Properly escapes `href` attributes. - Handles address groups recursively. ### Example ```javascript const addresses = [ { name: 'John Doe', address: 'john@example.com' } ]; const html = parser.getAddressesHTML(addresses); // John Doe <john@example.com> ``` ``` -------------------------------- ### MIME Part Tree Structure Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/architecture.md Illustrates the internal tree representation of a parsed MIME message. It shows how nested parts, headers, text content, and attachments are organized, including details for attachment streams and release functions. ```text Root Node (RFC 5322 message) ├─ headers: [From, Subject, Date, ...] ├─ children[0]: multipart/alternative │ ├─ headers: [Content-Type, ...] │ └─ children[0]: text/plain │ │ ├─ headers: [Content-Type: text/plain; charset=utf-8, ...] │ │ ├─ textContent: "Hello world" │ │ └─ isAttachment: false │ │ │ └─ children[1]: text/html │ ├─ headers: [Content-Type: text/html; charset=utf-8, ...] │ ├─ textContent: "..." │ └─ isAttachment: false │ └─ children[1]: application/pdf ├─ headers: [Content-Type, Content-Disposition: attachment, ...] ├─ filename: "document.pdf" ├─ isAttachment: true ├─ decoder: Transform stream (base64 → binary) └─ release: function (must call after processing) ``` -------------------------------- ### Custom Error Handling for Parsing Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/QUICK_START.md Implement custom error handling for email parsing using try-catch blocks. Differentiate between input errors, file system errors, and general parsing errors. ```javascript try { const mail = await simpleParser(input, { maxHtmlLengthToParse: 100 * 1024 // 100KB limit }); console.log(mail.subject); } catch (err) { if (err instanceof TypeError) { console.error('Invalid input:', err.message); } else if (err.code === 'ENOENT') { console.error('File not found'); } else { console.error('Parse error:', err.message); } } ``` -------------------------------- ### Custom Date Formatting Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/QUICK_START.md Provide a custom function to format date strings found in email metadata. This allows for consistent date representation across different email clients. ```javascript const mail = await simpleParser(input, { formatDateString: (date) => { // Custom formatting in HTML metadata return date.toISOString(); } }); ``` -------------------------------- ### updateImageLinks Source: https://github.com/nodemailer/mailparser/blob/master/_autodocs/api-reference/header-processing.md Replaces `cid:` image references within HTML content with custom URLs provided by a callback function. ```APIDOC ## updateImageLinks(replaceCallback, done) ### Description Replaces `cid:` image references in HTML with custom URLs generated by a callback. ### Method `updateImageLinks(replaceCallback: function, done: function): void` ### Parameters #### Path Parameters - **replaceCallback** (function) - Required - A callback function that is called for each `cid:` image found. It receives the `attachment` object and a callback `(err, url) => {}`. The `url` returned will replace the `cid:` reference. - **done** (function) - Required - The final callback function `(err, html) => {}` that is called once all replacements are complete, receiving any errors and the updated HTML string. ### Processing 1. Scans the HTML for `cid:` references. 2. Finds matching attachments based on their Content-ID. 3. Invokes `replaceCallback` for each image to get a replacement URL. 4. Updates the HTML with the returned URLs. 5. Only processes images found within `multipart/related` sections. ### Example ```javascript parser.updateImageLinks( (attachment, done) => { // Convert to data URL const dataUrl = 'data:' + attachment.contentType + ';base64,' + attachment.content.toString('base64'); done(null, dataUrl); }, (err, html) => { if (!err) { console.log('Updated HTML:', html); } } ); ``` ```