如何使用Nodejs发送包含HTML内容的SENDGRID电子邮件?

3

我从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: ''
    };
}

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

2个回答

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

!note: SendGrid更改了他们的API。因此,V2中的“substitutions”被V3中的“dynamic_template_data”所取代:https://github.com/sendgrid/sendgrid-nodejs/issues/703 要了解如何创建模板,请访问官方文档:https://sendgrid.com/docs/User_Guide/Transactional_Templates/create_and_edit_transactional_templates.html 您模板中的占位符应该被{{ }}包围。例如:{{emailAddress}}

邮件没有被发送出去,而且在Node.js中调试SendGrid的方法也找不到? - kylas
发现错误:“动态模板化不允许使用替换” - kylas
文档中有更新。请尝试使用.dynamic_template_data代替substitutions https://github.com/sendgrid/sendgrid-nodejs/issues/703 - Dat Tran
要通过dynamic_template_data添加HTML内容,您必须在sendgrid模板中包含变量名称作为{{{variable_name}}},而不是{{variable_name}}。请参阅 https://github.com/sendgrid/sendgrid-csharp/issues/738 - shamna

0

你可以使用Notifire来完成它

npm install @notifire/core @notifire/sendgrid

然后只需要

import { Notifire, ChannelTypeEnum } from '@notifire/core';
import { SendgridEmailProvider } from '@notifire/sendgrid';

const notifire = new Notifire();

await notifire.registerProvider(
  new SendgridEmailProvider({
    apiKey: process.env.SENDGRID_API_KEY,
    from: 'sender@mail.com'
  })
);

const passwordResetTemplate = await notifire.registerTemplate({
  id: 'password-reset',
  messages: [
    {
      subject: `You password reset request`,
      // Or for translation or custom logic you can use function syntax
      // subject: (payload: ITriggerPayload) => getTranslation('resetPasswordSubject', payload.language),
      channel: ChannelTypeEnum.EMAIL,
      template: `
          Hi {{firstName}}!
          
          To reset your password click <a href="{{resetLink}}">here.</a>
          
          {{#if organization}}
            <img src="{{organization.logo}}" />
          {{/if}}
      `
    },
  ]
});

await notifire.trigger('<REPLACE_WITH_EVENT_NAME>', {
  $user_id: "<USER IDENTIFIER>",
  $email: "test@email.com",
  firstName: "John",
  lastName: "Doe",
  language: "en",
  organization: {
    logo: 'https://evilcorp.com/logo.png'
  }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接