Skip to main content

MailParser

Streaming e‑mail parser for Node.js that can handle very large messages with minimal memory overhead.

MailParser offers two ways to consume a message:

  • simpleParser – convenience helper that buffers the whole message (including attachments) in memory and returns a single mail object. Great for simple use‑cases and tests.
  • MailParser class – a lower‑level Transform stream that emits message parts and attachment streams as they become available, letting you process huge messages without blowing up memory.

Installation

npm install mailparser

simpleParser()

const { simpleParser } = require("mailparser");

// Callback style
simpleParser(source, options, (err, mail) => {
if (err) throw err;
console.log(mail.subject);
});

// Promise style
simpleParser(source, options)
.then((mail) => console.log(mail.subject))
.catch(console.error);

// async/await
const mail = await simpleParser(source, options);

Parameters

  • source – a Buffer, String, or readable stream containing the RFC 822 message.
  • options – optional configuration (see Options).

Returned mail object

The resolved mail object aggregates every piece of the message:

PropertyType/Notes
headersMap of lowercase header keys → parsed values
subjectString – shorthand for headers.get('subject')
from, to, cc, bcc, reply-toAddress object (see below)
dateDate object
messageIdString
inReplyToString
referencesString[] | String
htmlHTML body with cid: images inlined as data URIs
textPlain‑text body
textAsHtmltext rendered as basic HTML
attachmentsAttachment[] (buffered in memory)
Security note

No sanitisation is performed. If you display html, make sure to run it through a trusted HTML‑sanitiser first.

Address object

{
"value": [
{
"name": "Jane Doe",
"address": "jane@example.com"
}
],
"html": "<span class=\"mp_address_name\">Jane Doe</span> &lt;<a href=\"mailto:jane@example.com\" class=\"mp_address_email\">jane@example.com</a>&gt;",
"text": "Jane Doe <jane@example.com>"
}
  • value – array of individual addresses (or groups)
  • text – formatted for plaintext context
  • html – formatted for HTML context

For a deep‑dive into address objects see the Message → Addresses section.

headers Map quirks

Most headers resolve to strings (single header) or string[] (multiple occurrences). The following are parsed into richer structures for convenience:

  • Address headers → address objects (from, to, cc, bcc, sender, reply-to, delivered-to, return-path).
  • Priority headers (x-priority, importance, …) are normalised to a single priority key with values "high" | "normal" | "low".
  • referencesString | String[].
  • dateDate.
  • Structured headers (content-type, content-disposition, dkim-signature) → { value: String, params: Object }.

Attachment object (simpleParser)

PropertyNotes
filenameFile name (may be undefined)
contentTypeMIME type
contentDispositionUsually "attachment"
checksumMD5 hash of content
sizeBytes
headersMap of MIME headers for this node
contentBuffer with the entire attachment
contentId / cidContent‑ID (without angle brackets)
relatedtrue if the part is inline (eg. embedded image)

MailParser (stream API)

const { MailParser } = require("mailparser");

const parser = new MailParser(options);
sourceStream.pipe(parser);

MailParser is a Transform stream in object mode that emits two kinds of objects via the 'data' event:

  1. { type: 'headers', headers: Map } – once, after the headers are parsed.
  2. { type: 'attachment', ... } – for every attachment (see below). The content property is a Readable stream.
  3. { type: 'text', html, text, textAsHtml } – once, containing the message bodies.

Stream options

OptionDefaultDescription
skipHtmlToTextfalseDo not generate text from HTML
maxHtmlLengthToParseInfinityLimit HTML size in bytes
formatDateStringundefinedCustom date → string formatter
skipImageLinksfalseLeave cid: links untouched
skipTextToHtmlfalseDo not generate textAsHtml
skipTextLinksfalseSkip link‑autodetection in text
keepDeliveryStatusfalseTreat message/delivery-status parts as attachments
Iconviconv-liteAlternative iconv implementation
keepCidLinksfalsesimpleParser‑only – synonym for skipImageLinks: true

Attachment stream object (type === 'attachment')

Identical shape to the buffered object shown earlier, except:

  • content is a Readable stream.
  • You must call attachment.release() when you are done. Parsing pauses until every attachment is released.
  • related is only available after parsing ends.
parser.on("data", (part) => {
if (part.type === "attachment") {
console.log("Attachment:", part.filename);
part.content.pipe(fs.createWriteStream(part.filename)).on("finish", part.release);
}
});

Character set decoding

MailParser relies on iconv‑lite for charset conversion, except for ISO‑2022‑JP and EUC‑JP which are handled by encoding‑japanese.

If you prefer node-iconv, inject it:

const { Iconv } = require('iconv');
const { simpleParser } = require('mailparser');

simpleParser(rfc822Message, { Iconv })
.then(mail => /* … */);

License

Dual‑licensed under the MIT License or EUPL v1.1 +.