如何在Node JS中使用sendgrid发送带有模板的电子邮件

时间:2019-01-27 15:43:12

标签: javascript node.js email sendgrid

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

Template.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模板 请帮助我

1 个答案:

答案 0 :(得分:0)

嗨Rajendran,               我已经测试了以下解决方案,并且使用createReadStream()可以正常工作,formatString将包含您的html。

  <label>Role</label>

  <div  *ngFor="let control of role.controls; let i = index;">
    <input  type="checkbox"  
    [formControl] = "control">
    <label>{{roles[i]}}</label>

};

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;