我想在本地服务器上发送邮件,但似乎无法使用Nodemailer和NodeJS。
有没有解决方案从本地发送邮件?
var contact = {subject: 'test', message: "test message", email: '[email protected]'};
var to = "[email protected]";
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: '[email protected]',
// 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\'s a 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的传输协议或创建您自己的传输。您尚未在代码中指定此项。
从本地服务器运行不应该是一个问题。
看起来您正在使用直接传输,这在文档中描述为:
...不可靠,因为默认情况下通常会阻止使用的传出端口25。此外,从动态地址发送的邮件通常被标记为垃圾邮件。您应该考虑使用SMTP提供程序。
一种解决方案是定义SMTP传输:
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'password'
}
});
还有其他解决方案here,例如使用Transport Plugin。
无论如何,当您没有向sendMail函数添加回调时,很难诊断您的问题。当您发送邮件时,请执行此操作,然后您可以检查控制台以查看错误可能是什么:
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所说的内容:确保“发件人”电子邮件与运送者对象中的电子邮件是相同的用户电子邮件。并且“to”必须是有效的电子邮件并且存在(检查值是否正确设置(未定义且不为null))。
const transporter = nodemailer.createTransport({
port: 25,
host: 'localhost',
tls: {
rejectUnauthorized: false
},
});
var message = {
from: '[email protected]',
to: '[email protected]',
subject: 'Confirm Email',
text: 'Please confirm your email',
html: '<p>Please confirm your email</p>'
};
transporter.sendMail(message, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
});
我现在通过express.js上的一个宁静的api来触发这个
这应该工作,我用它在digitalocean上设置我的后缀:https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-postfix-as-a-send-only-smtp-server-on-ubuntu-16-04