简体   繁体   中英

Express handlebar error : Error: ENOENT: no such file or directory,

I am trying to send styled email with sendgrid, nodemailer@6.7.7, nodemailer-handlebars1 and expess-handlerbar@6

the folder structure involving sendemail

在此处输入图像描述

The send email function

const nodemailer = require("nodemailer");
const logger = require("./logger");
const handlebars = require("nodemailer-handlebars");
const path = require("path");

const viewpath = path.join(__dirname, "../views");

const sendEmail = (options) => {

// the transporter that will send the mail
const transporter = nodemailer.createTransport({
    service : process.env.EMAIL_SERVICE,
    auth: {
        user: process.env.EMAIL_USERNAME,
        pass: process.env.EMAIL_PASSWORD
    }
})

// for using express handlebars
transporter.use("compile", handlebars({
    viewEngine: "express-handlebars",
    viewPath: `${viewpath}`
}))

console.log(viewpath)

// mail options
const mailOptions = {
    from: process.env.EMAIL_FROM,
    to: options.to,
    subject: options.subject,
    // html: options.html,
    text: options.text,
    template: "index"
}

transporter.sendMail(mailOptions, (error, info) => {
    if(error){
        logger.error(`Send Mail Error : ${error}`)
    } else {
        logger.info(`Email sent successfully`)
    }
})
}

module.exports = sendEmail

When email is sent i get this error

在此处输入图像描述

When i change the view path variable to

const viewpath = path.join(__dirname, "../views/index.handlebars");

i get

在此处输入图像描述

If i uncomment the html inside the mailoptions and comment text and readjust the arguement{html} everywhere sendEmail() is invoked email is sent successfully. What could be the problem? And also what is the best practise?

The issue is that for the viewEngine setting you should pass through options that will go to the rendering engine, not just the name of it. Currently, the rendering engine is looking for a layout for your email, but it doesn't look like you are using a layout, so try:

const viewpath = path.join(__dirname, "../views");

  transporter.use(
    "compile",
    handlebars({
      viewEngine: {
        defaultLayout: false,
      },
      viewPath: viewpath,
    })
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM