node.js: mailparser not working

Viewed 6903

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

2 Answers

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'))
Related