【问题标题】:How to send email with template with sendgrid in node js如何在节点 js 中使用带有 sendgrid 的模板发送电子邮件
【发布时间】:2019-06-20 17:47:17
【问题描述】:

发送.js

我测试了邮件,但它是一个硬内容。我想附加一个动态内容

    const msg = {
            to: email,
            from: 'no-reply@mail.com',
            subject: 'subject',
            html: '<strong>and easy to do anywhere, even with Node.js</strong>',
        };
        sgMail
            .send(msg)
            .then(() => {
                console.log('sended');
            })
            .catch(error => {
                console.log('error', error);
            });

模板.js

module.exports = (data)=> {
  return `
    <html>
      <body>
        <div style="text-align: center;">
          <h3>I'd like your input!</h3>
          <p>Please answer the following question:</p>
          <p>${data.body}</p>
        </div>
      </body>
    </html>
  `;
}; 

有没有办法附加html模板 请帮帮我

【问题讨论】:

    标签: javascript node.js email sendgrid


    【解决方案1】:

    嗨,拉金德兰, 我已经使用 createReadStream() 测试了以下解决方案,它的工作正常,formatString 将包含您的 html。

    const sendEmail = (body) => {
    let formatString;
    fs.open('template.html', 'r', (err, fd) => {
      if (err) {
        console.log(err);
        if (err.code === 'ENOENT') {
          console.error('myfile does not exist');
          return;
        }
        throw err;
      }
    
      const rr = fs.createReadStream('template.html');
      rr.on('readable', () => {
        const result = `${rr.read()}`;
        formatString = result.replace('####', body);
        console.log(formatString);
      });
      rr.on('end', () => {
        console.log('end');
      });
    });
    return formatString;
    

    };

    <html>
    <body>
      <div style="text-align: center;">
        <h3>I'd like your input!</h3>
        <p>Please answer the following question:</p>
        <p>####</p>
      </div>
    </body>
    

    【讨论】:

    • 但是我想发送带有动态内容的模板,所以我需要将内容从 send.js 传递给 template.js
    • 是的,你可以使用 sendEmail 功能,我也附上了 html
    • const msg = { to: email, from: 'no-reply@mail.com', subject: 'subject', html: sendEmail, }; 这是正确的,但我收到了来自 sendgrid 回调的错误消息
    • 尝试这样 const msg = { to: email, from: 'no-reply@mail.com', subject: 'subject', html: sendEmail (data.body)};
    猜你喜欢
    • 2015-05-15
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多