4

I want to parse an email and found mailparser package. (installed it using "npm install mailparser"). i'm using windows 7. i'm trying to run the simple example but the "end" event is not called and i don't see any logs. this is what i run:

const MailParser = require("mailparser").MailParser;
const mailparser = new MailParser({debug: true});

let email = "From: 'Sender Name' <sender@example.com>\r\n"+
    "To: 'Receiver Name' <receiver@example.com>\r\n"+
    "Subject: Hello world!\r\n"+
    "\r\n"+
    "How are you today?";

// setup an event listener when the parsing finishes
mailparser.on("end", function(mail_object){
    console.log("From:", mail_object.from); //[{address:'sender@example.com',name:'Sender Name'}]
    console.log("Subject:", mail_object.subject); // Hello world!
    console.log("Text body:", mail_object.text); // How are you today?
});

// send the email source to the parser
mailparser.write(email);
mailparser.end();

What am i doing wrong? Thx

Yoni Mayer
  • 1,212
  • 1
  • 14
  • 27
  • I had the same initial problem. You installed the wrong mailparser library. You need to install mailparser-mit for this to work. – Charles Saag May 28 '18 at 15:15

2 Answers2

5

According to the fine manual, there's only two events: headers and data.

Perhaps it's easiest to use the simpleParser instead of the lower-level (event-driven) MailParser:

const simpleParser = require('mailparser').simpleParser;
...
simpleParser(email).then(function(mail_object) {
  console.log("From:", mail_object.from.value);
  console.log("Subject:", mail_object.subject);
  console.log("Text body:", mail_object.text);
}).catch(function(err) {
  console.log('An error occurred:', err.message);
});
robertklep
  • 198,204
  • 35
  • 394
  • 381
0

It looks like the OP was asking about mazira/mailparser-mit, which is a fork of the more popular nodemailer/mailparser.

The mainline mailparser has since switched back to the MIT license, and the mailparser-mit fork has not been updated in two years as of this writing.

Here's an example to get started with the lower-level MailParser class from the mailparser package:

const {MailParser} = require('mailparser') // v3.0.1
const {createReadStream} = require('fs')

const parseEmail = async (readableStream) =>
  new Promise((resolve, reject) =>
    readableStream
      .pipe(new MailParser())
      .on('headers', (headers) => console.log('headers', headers))
      .on('data', (data) => console.log('data', data))
      .on('error', reject)
      .on('end', resolve),
  )

parseEmail(createReadStream('emails/test1.eml'))
Mike Fogel
  • 3,127
  • 28
  • 22