【问题标题】:Using nodemailer with handlebars for dynamic emails使用带有把手的 nodemailer 处理动态电子邮件
【发布时间】:2020-09-29 20:59:58
【问题描述】:

我遇到了问题,我似乎无法确定我到底做错了什么。当我运行我的代码时,这是我得到的错误:

[Error: ENOENT: no such file or directory, open 'C:\Users\Alex\Desktop\emailtest\main.handlebars'] { errno: -4058, code: 'ENOENT', syscall: 'open', path: 'C:\\Users\\Alex\\Desktop\\emailtest\\main.handlebars' }

这是我的代码:

const nodemailer = require("nodemailer");
const hbs = require("nodemailer-express-handlebars");
const express = require("express");
const app = express();
const port = 3000;

const transporter = nodemailer.createTransport({
  service: "gmail",
  auth: {
    user: "useremail",
    pass: "userpassword",
  },
  //   tls: {
  //     rejectUnauthorized: false,
  //   },
});

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

const mailOptions = {
  from: "myemailhere",
  to: "receiverpassword",
  subject: "Automated Email",
  template: "index",
};

transporter.sendMail(mailOptions, function (error, info) {
  if (error) {
    console.log(error);
  } else {
    console.log("Email sent: " + info.response);
  }
});

app.listen(port, () => {
  console.log(
    `Listening at http://localhost:${port}`
  );
});

文件夹结构:

server.js
views
    -index.handlebars

不使用 Handlebars,我可以很好地发送电子邮件,但是由于我需要一种动态填写 HTML 的方法,我认为如果我可以让它工作,Handlebars 将是最好的选择。任何见解都会很棒,在此先感谢!

【问题讨论】:

  • 尝试传递完整路径?只是一个想法。
  • @AbrahamLabkovsky 不幸的是,我已经尝试过了,谢谢
  • 另外,viewEngine 不是字符串。它要么是 express-handlebars 的一个实例,要么是一个选项 obj。您也可以在那里定义您的布局目录。不知道究竟是什么导致它使用默认位置,但我会在那里闲逛

标签: javascript node.js express handlebars.js nodemailer


【解决方案1】:
const path = require('path');

const handlebarOptions = {
    viewEngine: {
        extName: ".handlebars",
        partialsDir: path.resolve(__dirname, "views"),
        defaultLayout: false,
    },
    viewPath: path.resolve(__dirname, "views"),
    extName: ".handlebars",
};

trasnporter.use('compile', hbs(handlebarOptions));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-04
    • 2019-05-21
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    相关资源
    最近更新 更多