简体   繁体   English

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

[英]How to send email with template with sendgrid in node js

send.js send.js

I tested the mail, but its a hard content.I want to attach a dynamic content 我测试了邮件,但是邮件内容很硬。我想附加动态内容

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

Would there be any way to attach html templates please help me 有没有办法附上html模板,请帮帮我

Hi Rajendran , I have tested the below solution and its works fine using createReadStream() the formatString will contain your html. 您好Rajendran,我已经测试了以下解决方案,并且使用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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM