javascript – 通过nodemailer向多个收件人发送电子邮件
作者:互联网
我正在尝试向多个收件人发送电子邮件.为此,我创建了一个收件人数组,但是使用我的代码,我只能将邮件发送到阵列的最后一次电子邮件ID三次.我的代码出了什么问题?
var nodemailer = require("nodemailer");
var smtpTransport = nodemailer.createTransport(
"SMTP",{
host: '',
// secureConnection: true, // use SSL
port: 25
});
var maillist = [
'****.sharma3@****.com',
'****.bussa@****.com',
'****.gawri@****.com',
];
var msg = {
from: "******", // sender address
subject: "Hello ✔", // Subject line
text: "Hello This is an auto generated Email for testing from node please ignore it ✔", // plaintext body
cc: "*******"
// html: "<b>Hello world ✔</b>" // html body
}
maillist.forEach(function (to, i , array) {
msg.to = to;
smtpTransport.sendMail(msg, function (err) {
if (err) {
console.log('Sending to ' + to + ' failed: ' + err);
return;
} else {
console.log('Sent to ' + to);
}
if (i === maillist.length - 1) { msg.transport.close(); }
});
});
解决方法:
您的问题是从异步代码引用相同的msg对象.
forema在sendMail发送电子邮件之前完成.
所以msg.to将成为maiilist对象的最后一项.
尝试在maillist foreach中克隆/复制msg,或者只是将msg定义移动到那里:
maillist.forEach(function (to, i , array) {
var msg = {
from: "******", // sender address
subject: "Hello ✔", // Subject line
text: "Hello This is an auto generated Email for testing from node please ignore it ✔", // plaintext body
cc: "*******"
// html: "<b>Hello world ✔</b>" // html body
}
msg.to = to;
smtpTransport.sendMail(msg, function (err) {
标签:nodemailer,javascript,node-js 来源: https://codeday.me/bug/20191004/1853619.html