';
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);
}
}
);
```
```