在 Nodemailer 中使用 Jade 邮件模板

Using Jade mail template in Nodemailer

我有一个用 Nodemailer 创建的联系表。现在我想要在客户提交联系表时发送一封 Jade 模板邮件。

我已经让它工作了,邮件模板已经被发送了,但是 Jade 文件的内容以某种方式显示在邮件的 'subject' header 中。一切都带有所有 HTML 标签。所以,某处出错了。

这是我的 Nodemailer 代码:

router.post('/contact/send', function(req, res) {

  var transporter = nodeMailer.createTransport({

  service : 'Gmail',
  auth : {
    user: process.env.GMAIL_USER,
    pass: process.env.GMAIL_PASS
  }

  });

  var mailOptions = {
    from: req.body.name + ' <' + req.body.email + '>',
    to: 'xxxxx@gmail.com',
    subject:'Website verzoek',
    text:'Er is een website verzoek binnengekomen van '+ req.body.name+' Email: '+req.body.email+'Soort website: '+req.body.website+'Message: '+req.body.message,
    html:'<p>Websiteverzoek van: </p><ul><li>Naam: '+req.body.name+' </li><li>Email: '+req.body.email+' </li><li>Soort website: '+req.body.website+' </li><li>Message: '+req.body.message+' </li></ul>'
  };

  transporter.sendMail(mailOptions, function (err, info) {
    if(err) {
      console.log(err);
      res.redirect('/#contact');
    } else {
      console.log('Message send');
      res.redirect('/#contact');
    }
  });

  var toAddress = req.body.email;

  var sendMail = function(toAddress, subject, content, next) {
    var mailTemplate = {
      from: 'xxxxxx@gmail.com',
      to: toAddress,
      subject: subject,
      html: content
    };
    transporter.sendMail(mailTemplate, next);
  };

  var template = process.cwd() + '/views/mails/mail.jade';

  fs.readFile(template, 'utf8', function(err, file) {
    if (err) {
      console.log('Error');
    } else {
      var compiledTmpl = jade.compile(file, {filename: template});
      var context = {title: 'Express'};
      var html = compiledTmpl(context);

      sendMail(toAddress, html, function(err, response) {
        if(err) {
          console.log('ERROR!');
        } else {
          console.log('Template send');
        }
      });
    }
  });

});

问题是打字错误。您的 sendMail 函数将主题作为第二个参数。

var sendMail = function(toAddress, subject, content, next) {
var mailTemplate = {
  from: 'xxxxxx@gmail.com',
  to: toAddress,
  subject: subject,
  html: content
   };
   transporter.sendMail(mailTemplate, next);
};

您正在 将已编译的 html 作为第二个参数 传递给函数。所以它将 html 作为 header.

sendMail(toAddress, html, function(err, response) {
    if(err) {
      console.log('ERROR!');
    } else {
      console.log('Template send');
    }
  });

干杯。