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.
mailparser is an asynchronous and non-blocking parser for node.js to parse mime encoded e-mail messages. Handles even large attachments with ease - attachments are parsed in chunks that can be saved into disk or sent to database while parsing (tested with 16MB attachments).
mailparser parses raw source of e-mail messages to convert mime-stream into a structured object.
No need to worry about charsets or decoding quoted-printable or base64 data, mailparser (with the help of node-iconv) does all of it for you. All the textual output from mailparser (subject line, addressee names, message body) is always UTF-8.
You need to have node-iconv installed!
npm install mailparser
Create a new mailparser object
var MailParser = require("mailparser").MailParser,
mp = new MailParser();
Set up listener for different events
Get mail headers as a structured object
mp.on("header", function(headers){
console.log(headers);
});
Get mail body as a structured object
mp.on("body", function(body){
console.log(body);
});
Get info about binary attachment that is about to start streaming
mp.on("astart", function(id, headers){
console.log("attachment id" + id +" started);
console.log(headers);
});
Get part of a binary attachment in the form of a Buffer
mp.on("astream", function(id, buffer){
console.log("attachment id" + id);
console.log(buffer);
});
Attachment parsing completed
mp.on("aend", function(id){
console.log("attachment " + id + " finished");
});
Feed the parser with data
mp.feed(part1_of_the_message);
mp.feed(part2_of_the_message);
mp.feed(part3_of_the_message);
...
mp.feed(partN_of_the_message);
Finish the feeding
mp.end();
Parser returns the headers object with "header" event and it's structured like this
{ useMime: true
, contentType: 'multipart/alternative'
, charset: 'us-ascii'
, format: 'fixed'
, multipart: true
, mimeBoundary: 'Apple-Mail-2-1061547935'
, messageId: 'BAFE6D0E-AE53-4698-9072-AD1C9BF966AB@gmail.com'
, messageDate: 1286458909000
, receivedDate: 1286743827944
, contentTransferEncoding: '7bit'
, addressesFrom:
[ { address: 'andris.reinman@gmail.com'
, name: 'Andris Reinman'
}
]
, addressesReplyTo: []
, addressesTo: [ { address: 'andris@kreata.ee', name: false } ]
, addressesCc: []
, subject: 'Simple test message with special characters like \u0161 and \u00f5'
, priority: 3
}
Message body is returned with the "body" event and is structured like this
{ bodyText: 'Mail message as plain text',
, bodyHTML: 'Mail message as HTML',
, bodyAlternate: ["list of additional text/* and multipart/* parts of the message"],
, attachments: ["list of attachments"]
}
Attachments are included full size in the body object if the attachments are textual. Binary attachments are sent to the client as a stream that can be saved into disk if needed (events "astream" and "aend"), only the attachment meta-data is included in the body object this way.
See test.js for an actual usage example (parses the source from mail.txt and outputs to console)
node test.js
You need to install node-iconv before running the test!
Messages with attachments are typically formatted as nested multipart messages. This means that the bodyText and bodyHTML fields might be left blank. Search for an alternate with content-type multipart from the bodyAlternate array and use the bodyText and bodyHTML defined there instead.
BSD
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.