如何从 Nodejs 发送包含 html 内容的 SENDGRID 电子邮件?

kyl*_*las 3 node.js sendgrid

我从 Sendgrid 网站设计了一个模板。我们就这样称呼它吧sendgrid.html

Nodejs我正在尝试发送带有设计的电子邮件sendgrid.html。下面是我的 Nodejs 代码:

function sendVoucherCodeEmail (emailAddress, voucherCode){
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);
    const msg = {
        to: emailAddress,
        from: 'example@example.com',
        subject: 'YourCode',
        text: ''
    };
}
Run Code Online (Sandbox Code Playgroud)

我想传递emailAddressvoucherCode到 html 内容并将其作为电子邮件发送给用户。我该怎么做 ?先感谢您。

Dat*_*ran 6

最好在sendgrid上创建一个模板,并在使用sendgrid API发送时只输入模板的ID。通过这样做,您可以轻松更改内容,而无需部署新的应用程序。您仍然可以将所需的数据注入到模板中。

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
sgMail.setSubstitutionWrappers('{{', '}}');
const msg = {
  to: emailAddress,
  from: 'example@example.com',
  templateId: templateId,
  dynamic_template_data: {emailAddress, voucherCode},
};
Run Code Online (Sandbox Code Playgroud)

!注意:sendgrid 改变了他们的 API。所以在V2中被V3中substitutions替换: https ://github.com/sendgrid/sendgrid-nodejs/issues/703dynamic_template_data

要了解如何创建模板,您可以访问这里的官方文档:https://sendgrid.com/docs/User_Guide/Transactional_Templates/create_and_edit_transactional_templates.html

模板中的占位符应被 包围{{ }}。例如: {{emailAddress}}