Product
Socket Now Supports uv.lock Files
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
mailparser
Advanced tools
The mailparser npm package is a powerful tool for parsing email messages. It can handle various email formats and extract useful information such as headers, attachments, and the email body. This package is particularly useful for applications that need to process and analyze email content programmatically.
Parsing Email from a String
This feature allows you to parse an email from a raw string. The `simpleParser` function takes the raw email string and a callback function, and it returns a parsed email object containing various parts of the email such as headers, text, and attachments.
const { simpleParser } = require('mailparser');
const email = `From: sender@example.com
To: receiver@example.com
Subject: Test email
This is a test email.`;
simpleParser(email, (err, parsed) => {
if (err) {
console.error(err);
} else {
console.log(parsed);
}
});
Parsing Email from a Stream
This feature allows you to parse an email from a stream, such as a file stream. The `simpleParser` function can take a stream as input and parse the email content, making it useful for processing large email files.
const { simpleParser } = require('mailparser');
const fs = require('fs');
const emailStream = fs.createReadStream('path/to/email.eml');
simpleParser(emailStream, (err, parsed) => {
if (err) {
console.error(err);
} else {
console.log(parsed);
}
});
Extracting Attachments
This feature allows you to extract attachments from an email. The parsed email object contains an `attachments` array, where each attachment object includes properties like `filename` and `content`.
const { simpleParser } = require('mailparser');
const email = `From: sender@example.com
To: receiver@example.com
Subject: Test email
This is a test email with an attachment.`;
simpleParser(email, (err, parsed) => {
if (err) {
console.error(err);
} else {
parsed.attachments.forEach(attachment => {
console.log(attachment.filename);
console.log(attachment.content);
});
}
});
Nodemailer is a module for Node.js applications to allow easy email sending. While it focuses on sending emails rather than parsing them, it can be used in conjunction with mailparser for a complete email handling solution.
The imap package is used to connect to and interact with IMAP email servers. It allows you to fetch emails from an IMAP server, which can then be parsed using mailparser. It is more focused on email retrieval rather than parsing.
Mail-listener2 is a library for listening to incoming emails using IMAP. It can be used to monitor an email account and retrieve new emails, which can then be parsed using mailparser. It is useful for real-time email processing.
Advanced email parser for Node.js. Everything is handled as a stream which should make it able to parse even very large messages (100MB+) with relatively low overhead.
The module exposes two separate modes, a lower level MailParser
class and simpleParser
function. The latter is simpler to use (hence the name) but is less resource efficient as it buffers attachment contents in memory.
For older version of MailParser see the docs here
Starting from v2.0.0 MailParser is licensed under the European Union Public License 1.1. In general, EUPLv1.1 is a copyleft license compatible with GPLv2, so if you're OK using GPL then you should be OK using MailParser. Previous versions of MailParser are licensed under the MIT license.
npm install mailparser
simpleParser
is the easiest way to parse emails. You only need to provide a message source to get a parsed email structure in return. As an additional bonus all embedded images in HTML (eg. the images that point to attachments using cid: URIs) are replaced with base64 encoded data URIs, so the message can be displayed without any additional processing. Be aware though that this module does not do any security cleansing (eg. removing javascript and so on), this is left to your own application.
const simpleParser = require('mailparser').simpleParser;
simpleParser(source, (err, mail)=>{})
or as a Promise:
simpleParser(source).then(mail=>{}).catch(err=>{})
Where
Parsed mail
object has the following properties
mail.headers.get('subject')
)Address objects have the following structure:
value an array with address details
text is a formatted address string for plaintext context
html is a formatted address string for HTML context
Example
{
value: [
{
address: 'andris+123@kreata.ee',
name: 'Andris Reinman'
},
{
address: 'andris.reinman@gmail.com',
name: ''
}
],
html: '<span class="mp_address_name">Andris Reinman</span> <<a href="mailto:andris+123@kreata.ee" class="mp_address_email">andris+123@kreata.ee</a>>, <a href="mailto:andris.reinman@gmail.com" class="mp_address_email">andris.reinman@gmail.com</a>',
text: 'Andris Reinman <andris+123@kreata.ee>, andris.reinman@gmail.com'
}
headers
is a Map with lowercase header keys. So if you want to check for the Subject: header then you can do it like this:
if (mail.headers.has('subject')) {
console.log(mail.headers.get('subject'));
}
The format of a header depends on the specific key. For most header keys the value is either a string (a single header) or an array of strings (multiple headers with the same key were found).
Special header keys are the following:
references is a string if only a single reference-id exists or an array if multiple ids exist
date value is a Date object
The following headers are parsed into structured objects, where value
property includes the main value as string and params
property holds an object of additional arguments as key-value pairs
Some headers are also automaticaly mime-word decoded
Attachment objects have the following structure:
MailParser
is a lower-level email parsing class. It is a transform stream that takes email source as bytestream for the input and emits data objects for attachments and text contents.
const MailParser = require('mailparser').MailParser;
let parser = new MailParser()
The parser emits 'headers' once message headers have been processed. The headers object is a Map. Different header keys have different kind of values, for example address headers have the address object/array as the value while subject value is string.
Header keys in the Map are lowercase.
parser.on('headers', headers = {
console.log(headers.get('subject'));
});
Event 'data' or 'readable' emits message content objects. The type of the object can be determine by the type
property. Currently there are two kind of data objects
Attachment object is the same as in simpleParser
except that content
is not a buffer but a stream. Additionally there's a method release()
that must be called once you have processed the attachment. The property related
is set after message processing is ended, so at the data
event this value is not yet available.
parser.on('data', data => {
if(data.type === 'attachment'){
console.log(data.filename);
data.content.pipe(process.stdout);
data.on('end', ()=>data.release());
}
});
If you do not call release()
then the message processing is paused.
Text object has the following keys:
parser.on('data', data => {
if(data.type === 'text'){
console.log(data.html);
}
});
Charset decoding is handled using iconv-lite that is missing some charsets, especially some Japanese ones. If required then it would be possible to switch to native iconv bindings with node-iconv to handle these missing charsets but for now this option is not used for easier packaging.
European Union Public License 1.1. Commercial licenses available upon request. Contact sales@nodemailer.com for details.
© 2017 Kreata OÜ
FAQs
Parse e-mails
The npm package mailparser receives a total of 575,465 weekly downloads. As such, mailparser popularity was classified as popular.
We found that mailparser demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.
Security News
PEP 770 proposes adding SBOM support to Python packages to improve transparency and catch hidden non-Python dependencies that security tools often miss.