使用node.js和sendgrid发送电子邮件模板

8
我正在使用node.js构建一个应用程序,并使用sendgrid处理我的电子邮件。有没有人知道我如何定义一个可以在电子邮件正文中使用的电子邮件模板?
提前感谢!
4个回答

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

5
你可以使用 @sendgrid/mail 库:
  const sgMail = require("@sendgrid/mail");
  sgMail.setApiKey(process.env.SENDGRID_API_KEY);

  const msg = {
    to: "recipientmail", 
    from: "verifiedsendermail",
    subject: "Email Subject",
    template_id: "your sendgrid email dynamic template id",
    personalizations: [
      {
        dynamic_template_data: {
          fullName: "John Doe",
        },
      },
    ],
  };

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

在这里,你的模板看起来应该像下面这样,其中{{fullName}}是你的动态变量: 输入图像描述


1
你可以使用 - https://docs.sendgrid.com/for-developers/sending-email/using-handlebars#handlebarjs-reference - Nicolae Maties

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;

Driver.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: "abc@xyz.com",
   receiver: "xyz@abc.com",   
   //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

1
你能发布一个使用它的例子吗? - Apoorv
信息在此处:https://github.com/sendgrid/sendgrid-nodejs/blob/78dae9ed05cc54bd50b4c0354a5e15855d83db60/docs/use-cases/transactional-templates.md - Stephane

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