Send an email to localhost smtp server in Node.js

I use nodemailer to send 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: "me@localhost.com",
    replyTo: "me@localhost.com",
    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 also have 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 do not see “received” messages when sending emails to my localhost smtp server (note the “me @localhost” in the client code).

What am I missing to make it work?

+4
source share
1 answer

You may need to define an authentication handler in your settings

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 an error self signed certificate, you may need to enable this before sending the email:

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
+2
source

Source: https://habr.com/ru/post/1657326/


All Articles