我想使用 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/