发送电子邮件到Node.js中的localhost smtp服务器

时间:2016-10-10 21:14:06

标签: node.js smtp nodemailer

我正在使用nodemailer发送电子邮件:

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();
});

我还有一个使用smtp-server的本地smtp服务器:

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

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

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

当我向localhost smtp服务器发送电子邮件时,我看不到“收到”(请注意:客户端代码中的“me @ localhost”)。

我错过了什么让它起作用?

1 个答案:

答案 0 :(得分:2)

您可能需要在选项

上定义身份验证处理程序
var server = new SMTPServer({
    onAuth: function(auth, session, callback) {
        callback(null, { user : auth });
    },
    onData: function(stream, session, callback) {
        console.log('received');
    },
});

详细了解onAuth params

如果您收到self signed certificate错误,则可能需要在发送电子邮件之前将其包含在内:

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";