使用Nodemailer与express-handlebars发送模板邮件时出现ENOENT文件不存在错误的求助
Hey there! Let's break down why you're seeing that "ENOENT: no such file or directory" error and get your template emails working smoothly.
First, let's spot the most obvious issue in your code:
1. Typos in Directory Name
Looking at your handlebarOptions, you've written emialTemplate instead of emailTemplate (missing an 'l' in 'email'). That's definitely causing Node to look for a directory that doesn't exist!
Here's the corrected snippet:
const handlebarOptions = { viewEngine: { extName: ".handlebars", // Fixed the typo here partialsDir: path.resolve(__dirname, "emailTemplate"), defaultLayout: false, }, // And fixed it here too viewPath: path.resolve(__dirname, "emailTemplate"), extName: ".handlebars", };
2. Verify Your Directory Structure
Make sure your project folder matches the path you're referencing. Your setup should look exactly like this:
your-project-folder/ ├── index.js └── emailTemplate/ └── comeBack.handlebars // Your template file must exist here
- Double-check that
comeBack.handlebarsis present inside theemailTemplatefolder (the name has to match what you set inmailOptions.template: 'comeBack'exactly). - Confirm
emailTemplatelives in the same folder as yourindex.jsfile —__dirnamepoints directly to the directory whereindex.jsis stored, so the template folder needs to be there.
3. Ensure All Dependencies Are Installed
Double-check you've installed every required package. Run this command in your project folder if you haven't already:
npm install express nodemailer nodemailer-express-handlebars express-handlebars googleapis body-parser
nodemailer-express-handlebars relies on express-handlebars under the hood, so missing that package could also trigger unexpected file lookup errors.
4. Optional: Use path.join for Cross-OS Path Reliability
While path.resolve works fine, path.join automatically handles OS-specific path separators (like / on macOS/Linux vs \ on Windows). You can adjust your paths like this for extra safety:
partialsDir: path.join(__dirname, "emailTemplate"), viewPath: path.join(__dirname, "emailTemplate"),
This isn't strictly necessary, but it's a good habit to avoid path issues across different operating systems.
Final Check
After fixing the typo and verifying your folder structure, restart your server and test the endpoint again. The ENOENT error should disappear once Node can find your template directory and file correctly.
内容的提问来源于stack exchange,提问作者Geetansh Rathore

