Search code examples
node.jsemailbulknodemailer

Send raw email file with nodeJs


I tried to send some email contained in a file with nodemailer for nodejs, to do that i first parsed the file with mailparser and then send the object returned with node mailer, the problem is that it seems that it doubles the headers, creating two from:, two to: etc... I'm wondering if there is another way to make nodemailer read files from a directory and send them, or if you know some other way i could do that.

I have some files that gets accumulated in a directory and each day at 8am, they are all sent to a server. The time can change but thats not relevent i guess :). thanks for any help or tips you guys can give and the others for reading :P.

Here is the exemple of code i'm using as asked

var fs = require('fs');
var MailParser = require("mailparser").MailParser;
var file = './113B797D-69F0-4127-A4CE-27923E7006CF.3.1';
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
 port: 2529,
 host: '127.0.0.1'
});
var mailparser = new MailParser();
mailparser.on("error", function(err) {
   console.log('[Error] mailparser: '+err);
});

mailparser.on("end", function(mail_object) { 
  console.log(mail_object);
  transporter.sendMail(mail_object);
});
fs.createReadStream(file).pipe(mailparser);

Solution

  • var nodemailer = require('nodemailer');
    
    // create reusable transporter object using the default SMTP transport 
    var smtpConfig = {
        host: 'smtp.email.com',
        port: 465,
        secure: true, // use SSL
        auth: {
            user: 'test@email.com',
            pass: 'passHere'
        }
    };
    
    var transporter = nodemailer.createTransport(smtpConfig);
    
    // setup e-mail data with unicode symbols
    var mailOptions = {
        envelope: {
            from: 'test@email.com', // sender address
            to: 'email@test.com'    // list of receivers
        },
        raw: {
            path: '/path/to/file.eml'
        }
    };
    
    // send mail with defined transport object
    transporter.sendMail(mailOptions, function(error, info){
        if(error){
            return console.log(error);
        }
        console.log('Message sent: ' + info.response);
    });