handlebars.js - 使用 Nodemailer 和 Handlebars 发送电子邮件

标签 handlebars.js nodemailer express-handlebars

我想使用 Nodemailer 和 Handlebars 发送电子邮件,但无法使用动态模板。

这是我的设置。 template 是模板名称,它看起来像 sign-up-mail-template 现在,当我发送此电子邮件时,我将收到 Error: ENOENT: no such file 或目录,打开 '/home/ubuntu/backend/src/templates/sign-up-email-template.handlebars'

如果我将 defaultLayout 更改为 sign-up-email-template.hbs 将毫无问题地发送电子邮件,但即使我请求发送不同的电子邮件模板假设将在 mailOptions 中调用 password-reset-template ,它将发送 defaultLayout

有人可以向我解释一下我在这里做错了什么吗?

此外,如果 const template = "password-reset-template.hbs" 它将收到 Error: ENOENT: no such file or directory, open '/home/ubuntu/backend/src/templates/password-reset-template.hbs.handlebars'

 const transporter = nodemailer.createTransport(
    smtpTransport({
      host: constants.EMAIL_HOST,
      port: constants.SMTP_PORT,
      secure: false,
      requireTLS: true,
      auth: {
        user: constants.EMAIL_USER,
        pass: constants.EMAIL_PASSWORD
      }
    })
  );

  const handlebarsOptions = {
    viewEngine: {
      extName: ".hbs",
      partialsDir: "./src/templates/",
      layoutsDir: "./src/templates/",
      defaultLayout: template
    },
    viewPath: path.resolve("./src/templates/"),
    extName: ".html"
  };

  transporter.use("compile", hbs(handlebarsOptions));

  const mailOptions = {
    to: email,
    from: '"Welcome" <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bed0d193ccdbced2c7fed3dfd7d290ddd1d3" rel="noreferrer noopener nofollow">[email protected]</a>',
    template,
    subject,
    context: {
      code: promoCode
    }
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      throw new Error(error.message);
    }
    console.log("Message sent: %s", info.message);
  });

最佳答案

您需要创建一个 main.handlebars 文件,如下所示。

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<body>

    {{{body}}}

</body>
</html>

{{body}} 是放置 sign-up-email-template.handlebars 的位置。

希望对你有帮助!

关于handlebars.js - 使用 Nodemailer 和 Handlebars 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56225938/

相关文章:

html - 传递给 Handlebars 模板的数据未显示在客户端

javascript - 在 Handlebars 中,如何转义字段名称中的特殊字符?

firebase - 如何将 nodemailer 与 Cloud Functions for Firebase 结合使用?

javascript - NodeMailer 服务器上没有任何响应

javascript - 每个循环内的 Handlebars i18n 助手

javascript - 如何将函数传递给 nodejs-express 中的 express-handlebars?

handlebars.js - 如何从 Liquid 模板 (Jekyll) 呈现 Handlebars 标记

javascript - Firefox 中的 Handlebars XML 解析错误

javascript - 带有 "a"标签的 Ember View 助手的意外行为

node.js - Express 后端在从 Angular 5 应用程序传递数据时丢弃数据