【问题标题】:Nodemailer and nodemailer-express-handlebars and/or express-handlebars will not use templateNodemailer 和 nodemailer-express-handlebars 和/或 express-handlebars 不会使用模板
【发布时间】:2021-03-31 21:25:59
【问题描述】:

我想了解如何让 nodemailer 与 nodemailer-express-handlebars 和/或 express-handlebars 一起使用,以便使用 node 发送带有 html 模板的电子邮件。

文件结构:

依赖关系:(我需要 express-handlebars 和 nodemailer-express-handlebars 吗?)

"express-handlebars": "^5.3.0",
"nodemailer": "^6.4.16",
"nodemailer-express-handlebars": "^4.0.0",

服务器.js

import expresshbs from "express-handlebars";

app.set("views", path.join(__dirname, "views"));
app.engine("handlebars", expresshbs({ defaultLayout: false }));
app.set("view engine", "handlebars");

booking.controller.js

import hbs from "nodemailer-express-handlebars";
                
const transporter = nodemailer.createTransport({
    host: "xxx",
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
        user: "xxx",
        pass: process.env.EMAILPASS,
    },
    tls: {
        rejectUnauthorized: false,
       },
 });

transporter.use(
    "compile",
    hbs({
        viewEngine: "nodemailer-express-handlebars",
        viewPath: "emailTemplates/",
    })
);

const mailOptions = {
    from:
        "xxx",
    to: "xxx" // list of receivers
    subject: "subject",
    template: "newbooking",
};

transporter.sendMail(mailOptions, (err, info) => {
    if (err) {
        console.log("Error", err);
    } else {
        console.log("Message sent");
    }
});

在项目的根目录中,我有一个模板 main.handlebars,但是我想删除它并强制例程使用 emailTemplates 中的 newbooking.handlebars 模板。

当前行为:

如果我调用 booking.controller.js,我会收到一封电子邮件,但它使用 main.handlebars 模板。

如果我以任何方式重命名 newbooking.handlebars(例如 newbookingx.handlebars),我会收到错误找不到 newbooking.handlebars。

错误:ENOENT:没有这样的文件或目录,打开 '.../E-Server/emailTemplates/newbooking.handlebars'

所以它显然在寻找 newbooking.handlebars 但没有使用它,而是使用 main.handlebars。

【问题讨论】:

    标签: nodemailer express-handlebars


    【解决方案1】:

    我将开始创建一个名为 emails 的文件夹,例如在这个文件夹中创建一个名为layouts 的子文件夹。 在名为emails 的文件夹中,您放置了所有车把电子邮件。在 layouts 文件夹中,您将电子邮件模板 newbooking.handlebars 放入。

    如果您已经这样做了,请将transporter.use() 更改为以下代码:

        transporter.use(
            "compile",
            hbs({
                  viewEngine: {
              extname: '.handlebars', // handlebars extension
              layoutsDir: 'emails/layouts/', // location of handlebars templates
              defaultLayout: 'newbooking', // name of main template
          },
          viewPath: 'emails',
          extName: '.handlebars',
          };
            })
        );
    

    以下代码定义布局位于emails/layouts/ 文件夹中,默认布局的名称为newbooking。 viewPath 定义电子邮件位于/emails 文件夹中。

    【讨论】:

      猜你喜欢
      • 2022-10-21
      • 2021-04-18
      • 2021-09-11
      • 2023-03-26
      • 2014-10-11
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多