通过node.js + sendgrid使用电子邮件模板

问题描述 投票:0回答:4

我正在使用 node.js 构建一个应用程序,并使用 sendgrid 来处理我的电子邮件。有谁知道我可以定义可在电子邮件正文中使用的电子邮件模板的方法吗?

提前致谢!

node.js email templates sendgrid
4个回答
6
投票

Sendgrid 文档详细介绍了如何创建模板此处,如果您希望通过节点发送模板,则需要 Sendgrid Mail(不要与 Sendgrid 客户端混淆),这里有一个示例说明如何发送您的模板模板这里


6
投票

您可以使用@sendgrid/mail库:

  const sgMail = require("@sendgrid/mail");
  sgMail.setApiKey(process.env.SENDGRID_API_KEY);

  const msg = {
    to: "recipientmail", 
    from: "verifiedsendermail",
    subject: "Email Subject",
    templateId: "your sendgrid email dynamic template id",
    dynamicTemplateData: {
      fullName: "John Doe",
    },
  };

  sgMail
    .send(msg)
    .then((response: any) => {
     
    })
    .catch((error: any) => {
      
    });

在这里,您的模板将如下所示,其中 {{fullName}} 是您的动态变量: enter image description here


1
投票

尝试以下代码:

Mailer.js

const sgMail = require("@sendgrid/mail");
sgMail.setApiKey("YOUR_API_KEY");
templates = {
    password_reset_confirm: "d-a02ad738dfc8404c8da016b46a7548sd",
    password_reset        : "d-e779dcfad71b47e7be8d79bdfe75fb0c",
    confirm_account       : "d-68c570dd12044d894e07566bf951964",
};
function sendEmail(data) {
   const msg = {
      //extract the email details
      to: data.receiver,
      from: data.sender,
      templateId: templates[data.templateName],
      //extract the custom fields 
      dynamic_template_data: {
         name: data.name,
         confirm_account_url:  data.confirm_account__url,
         reset_password_url: data.reset_password_url
      }
    };
    //send the email
    sgMail.send(msg, (error, result) => {
      if (error) {
          console.log(error);
      } else {
          console.log("That's wassup!");
      }
    });
}
exports.sendEmail = sendEmail;

驱动程序.js

//import the mailer.js file we previously created
var sender = require("./mailer.js");
var data = {
   //name of the email template that we will be using
   templateName: "confirm_account",
   //sender's and receiver's email
   sender: "[email protected]",
   receiver: "[email protected]",   
   //name of the user
   name: "Arjun Bastola",
   //unique url for the user to confirm the account
   confirm_account_url: "www.veniqa.com/unique_url"
   
};
//pass the data object to send the email
sender.sendEmail(data);

0
投票

如果您使用的是 sendgrid-nodejs 库,那么您可以在 readme 中找到如何指定模板的示例。您还可以在文档中找到更多高级交易电子邮件模板信息。

© www.soinside.com 2019 - 2024. All rights reserved.