Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send email to localhost smtp server in Node.js

I'm using nodemailer to sends emails:

var nodemailer = require('nodemailer'),
config = require('./mailer.conf');

var smtpTransport;

console.log('Creating Transport');

//smtp transport configuration
var smtpTransport = nodemailer.createTransport({
    host: config.host,
    port: config.port,
    auth: {
        user: config.email,
        pass: config.password
    }
});

//Message
var message = {
    from: "[email protected]",
    replyTo: "[email protected]",
    to: "me@localhost",
    subject: "hello"
};

console.log('Sending Mail');
// Send mail
smtpTransport.sendMail(message, function(error, info) {
    if (error) {
        console.log(error);
    } else {
        console.log('Message sent successfully!');
        console.log('Server responded with "%s"', info.response);
    }
    console.log('Closing Transport');
    smtpTransport.close();
});

I have also a local smtp server using smtp-server:

var SMTPServer = require('smtp-server').SMTPServer;

var server = new SMTPServer({
    onData: function(stream, session, callback) {
        console.log('received');
    }
});

server.listen(465);
console.log('listening');

I don't see "received" when I send emails to my localhost smtp server (note to: "me@localhost" in the client code).

What am I missing to make it work?

like image 295
Rafael Angarita Avatar asked Oct 30 '22 18:10

Rafael Angarita


1 Answers

You may need to define the authentication handler on your options

var server = new SMTPServer({
    onAuth: function(auth, session, callback) {
        callback(null, { user : auth });
    },
    onData: function(stream, session, callback) {
        console.log('received');
    },
});

Learn more about onAuth params

If you get a the self signed certificateerror, you may need to include this before sending your email:

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
like image 98
Khalid Avatar answered Nov 11 '22 06:11

Khalid