【发布时间】: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