如何发送 html 具有动态值的电子邮件?

how to Send html email with dynamic value?

const doc = [{id: 2, title: 'hello word', email: 'test@email.com'},{id: 3, title: 'post data'}, email: 'test@email.com'}]

 {
                    doc.map(data => {
                        var readHTMLFile = function (path, callback) {
                            fs.readFile(path, { encoding: 'utf-8' }, function (err, html) {
                                if (err) {
                                    throw err;
                                    callback(err);
                                }
                                else {
                                    callback(null, html);
                                }
                            });
                        };

                        readHTMLFile(__dirname + '/../emailTemplates/newsletter.html', function (err, html) {
                            var template = handlebars.compile(html);
                            var replacements = {
                                name: data.name
                            };
                            var htmlToSend = template(replacements);
                            var mailOptions = {
                                from: 'info@fnmotivation.com',
                                to: data.email,
                                subject: 'Check out story posts in your communities',
                                html: htmlToSend
                            };
                            transporter.sendMail(mailOptions, function (err, info) {
                                if (err) {
                                    console.log(err);
                                    callback(err);
                                }
                            });
                        });
                    })
                }

我只想发送一次存储在 doc 变量中的数据,但邮件发送了两次可能是因为我使用了映射 doc 变量。知道如何发送一封邮件吗?

删除 doc.map 方法并从文档列表中获取 toEmailAddresses 作为逗号分隔的字符串。

const doc = [{ id: 2, title: 'hello word', email: 'test@email.com' }, { id: 3, title: 'post data', email: 'test@email.com' }]

const readHTMLFile = function (path, callback) {
  fs.readFile(path, { encoding: 'utf-8' }, function (err, html) {
    if (err) {
      throw err;
      callback(err);
    }
    else {
      callback(null, html);
    }
  });
};

readHTMLFile(__dirname + '/../emailTemplates/newsletter.html', function (err, html) {
  const template = handlebars.compile(html);
  const toEmailAddresses = doc.map(data => data.email).join(); // to get email addresses.

  const mailOptions = {
    from: 'info@fnmotivation.com',
    to: toEmailAddresses,
    subject: 'Check out story posts in your communities',
    html: template
  };
  transporter.sendMail(mailOptions, function (err, info) {
    if (err) {
      console.log(err);
      callback(err);
    }
  });
});