javascript - 试图在我的节点服务器上分离我的 SendGrid html 电子邮件模板
问题描述
我正在运行节点服务器,并且正在使用 SendGrid 发送电子邮件。我需要将我的电子邮件 HTML 与我的 js 文件分开,这样我就可以从一个单一的基础上修改它们。我现在拥有的是这样的:
const express = require('express')
const config = require('config')
const sgMail = require('@sendgrid/mail')
const sendKey = config.get('SENDGRID_API_KEY')
sgMail.setApiKey(sendKey)
const msg = {
to: "test@test.com",
from: "test@test.com",
subject: 'Welcome To The App',
text: 'Text is here',
html: <strong>HTML HERE</strong>
}
sgMail.send(msg)
我想在我当前的 js 文件之外调用我的 HTML 属性,而不是在我的 msg 对象中编写 HTML。
如何拥有一个单独的welcomeEmail.html 文件并将其添加到我的js 文件中的msg 对象中?
我已经尝试过 fs 模块,但我所拥有的只是
Error: ENOENT: no such file or directory, open './welcomeEmail.html'
无论如何,我无法读取我的 HTML 文件。
知道我缺少什么吗?
解决方案
您可以使用fs
,您可能从错误的路径中读取。
用这个:
fs.readFile('./welcomeEmail.html', 'utf8', (err, content)=>{//do Something});
确保welcomeEmail.html
在项目中的正确位置。
请记住readFile
,async
您应该在回调中执行其余代码,因此您的代码应该是这样的(取决于用例是什么):
const express = require('express')
const config = require('config')
const sgMail = require('@sendgrid/mail')
const sendKey = config.get('SENDGRID_API_KEY')
const fs = require('fs')
sgMail.setApiKey(sendKey)
fs.readFile('./welcomeEmail.html', 'utf8', (err, content)=>{
if(err){
console.log(err);
}
else{
let msg = {
to: "test@test.com",
from: "test@test.com",
subject: 'Welcome To The App',
text: 'Text is here',
html: content
}
sgMail.send(msg)
}
});
推荐阅读
- javascript - 我应该把异步和等待放在哪里?
- python - 如何在我的所有 HTML 模板中引用静态变量?
- python - Kali linux 和使用脚本打开 sh 文件
- c++ - C++ 引用和退出范围
- java - 如何将 JHawk(插件)安装到 Eclipse 中
- excel - 当日期在excel中的另一个单元格上更新时,我想增加一个单元格上的数字
- javascript - 没有 parseInt,Vue 的共享状态怎么不会更新?
- c++ - 为什么在通过引用返回运算符赋值时取消引用“this”指针?
- java - 为什么 LinkedHashSet 不支持基于索引的操作,因为它维护其元素的顺序
- javascript - 使用带有粘性导航栏的标签会将我带到错误的地方