通过nodemailer向多个收件人发送电子邮件 [英] Sending email to multiple recipients via nodemailer
问题描述
我正在尝试向多个收件人发送电子邮件。为此,我创建了一个收件人数组,但是使用我的代码,我只能将邮件发送到阵列的最后一次电子邮件ID三次。我的代码出了什么问题?
I am trying to send email to multiple recipients. For this I have created an array of recipients, but with my code I am only able to send mail to last email ID of the array three times. What's wrong with my code?
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对象。
foreach在sendMail发送电子邮件之前完成。
Your problem is referencing the same msg object from async code. The foreach completes before the sendMail would send out the emails.
所以msg.to将成为maiilist对象中的最后一项。
So msg.to wil be the last item from the maiilist object.
尝试在maillist foreach中克隆/复制msg,或者只是将msg定义移到那里:
Try to clone/copy msg inside maillist foreach, or just move msg definition to there :
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向多个收件人发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!