如何在 Node 中为电子邮件插入 HTML 文件模板

How to insert a HTML file template in Node for emails

我想插入一个 HTML 文件模板以用于通过节点发送的电子邮件。

当我使用下面的代码时,出现此错误...

(function (exports, require, module, __filename, __dirname) { <!doctype html>

有什么建议吗?

var template = require('../../views/email-template.js');
var htmlAll = _.template(template)(contactinfo[0]);
var data = {
   from: company@example.com,
   to: email,
   subject: 'Your Order Confirmation',
   html: htmlAll

电子邮件-template.js

<!doctype html>
<html>
  <head>
   <meta name="viewport" content="width=device-width">
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <title>Email</title>
   <style media="all" type="text/css">

// . . .

    <table>
     // . . . 

          <td><%= firstName %> <%= lastName %>
           <br><%= company %>
           <br><%= address %>
           <br><%= city %>, <%= state.code %> <%= zip %>
           <br><%= email %>
           <br><%= phone %>
          </td>
       </tr>

     </table>
  // . . . 

您不能通过 nodejs 要求非 javascript 文件 require

使用fs模块

  var fs = require('fs')
  var template = fs.readFileSync('../../views/email-template.js').toString();
  var htmlAll = _.template(template)(contactinfo[0]);

最好缓存 fs.readFileSync 结果以供连续使用