首页 > 解决方案 > 试图在我的节点服务器上分离我的 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 文件。

知道我缺少什么吗?

标签: javascriptnode.jssendgrid

解决方案


可以使用fs,您可能从错误的路径中读取。

用这个:

fs.readFile('./welcomeEmail.html', 'utf8', (err, content)=>{//do Something});

确保welcomeEmail.html在项目中的正确位置。

请记住readFileasync您应该在回调中执行其余代码,因此您的代码应该是这样的(取决于用例是什么):

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)
  }
});

推荐阅读