使用Nodemailer从本地主机发送电子邮件

我想在本地服务器上发送邮件,但似乎不能与Nodemailer和NodeJS一起工作。

有没有解决办法从本地发送邮件?

var contact = {subject: 'test', message: "test message", email: 'visitor@gmail.com'}; var to = "myemail@gmail.com"; var transporter = nodemailer.createTransport(); transporter.sendMail({ from: contact.email, to: to, subject: contact.subject, text: contact.message }); 

 var nodemailer = require('nodemailer'); // Create a SMTP transport object var transport = nodemailer.createTransport("SMTP", { service: 'Hotmail', auth: { user: "username", pass: "password" } }); // Message object var message = { // sender info from: 'name@hotmail.com', // Comma separated list of recipients to: req.query.to , // Subject of the message subject:req.query.subject //'Nodemailer is unicode friendly ✔', // plaintext body text: req.query.text //'Hello to myself!', // HTML body /* html:'<p><b>Hello</b> to myself <img src="cid:note@node"/></p>'+ '<p>Here\'sa nyan cat for you as an embedded attachment:<br/></p>'*/ }; console.log('Sending Mail'); transport.sendMail(message, function(error){ if(error){ console.log('Error occured'); console.log(error.message); return; } console.log('Message sent successfully!'); // if you don't want to use this transport object anymore, uncomment //transport.close(); // close the connection pool }); 

您必须指定像SMTP那样的传输协议或创build自己的传输。您没有在代码中指定此传输协议。

不应该是从本地服务器运行的问题。

看起来您正在使用直接传输,这在文档中描述为:

…不可靠,因为使用的输出端口25通常被默认阻塞。 另外,从dynamic地址发送的邮件通常被标记为垃圾邮件。 你应该考虑使用SMTP提供者。

一个解决scheme是定义一个SMTP传输:

 var transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'sender@gmail.com', pass: 'password' } }); 

这里还有其他的解决scheme,比如使用Transport Plugin。

无论如何,当你不向sendMail函数添加callback函数时,诊断你的问题是很困难的。 当你发送邮件,这样做,然后你可以检查控制台,看看有什么错误可能是:

 transporter.sendMail({ from: contact.email, to: to, subject: contact.subject, text: contact.message }, function(error, info){ if(error){ console.log(error); }else{ console.log('Message sent: ' + info.response); } }); 

另外@cheniel说:确保“发件人”电子邮件与传输器对象中的电子邮件是同一个用户电子邮件。 和“到”必须是一个有效的电子邮件和存在(检查值是否正确设置(不是未定义,而不是空))。