我正在运行节点服务器,并且正在使用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: "[email protected]",
from: "[email protected]",
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: "[email protected]",
from: "[email protected]",
subject: 'Welcome To The App',
text: 'Text is here',
html: content
}
sgMail.send(msg)
}
});