【问题标题】:Sendgrid API: How to send bulk emails with individual template data?Sendgrid API:如何发送带有单个模板数据的批量电子邮件?
【发布时间】:2020-08-17 16:25:04
【问题描述】:

请求的行为:

我想同时使用 Sendgrid 和 Firestore Cloud 功能发送批量电子邮件。电子邮件应根据收件人显示一些个人用户数据(例如用户 ID 和用户名)。

当前状态

我创建了一个有效的云功能。它从 firestore 获取用户数据并使用 sendgrid API 向给定的电子邮件地址发送电子邮件。

问题

但是,它将所有用户的 id 发送到每个电子邮件地址,而不是仅发送属于某个订阅者的 id。示例:

我的 Firestore 集合中有 3 个具有 3 个 id 的订阅者: “abc”、“pqr”、“xyz”

该函数应该发送三封电子邮件,包括属于电子邮件地址的 id。相反,该函数现在将“abcpqrxyz”发送到每个地址。​​

我的云功能:

export const sendAllEmails = functions.https.onCall(async (event) => {

  const subscriberSnapshots = await admin.firestore().collection('subscribers').get();

  const emails = subscriberSnapshots.docs.map(snap => snap.data().email);
  const ids = subscriberSnapshots.docs.map(snap => snap.id);

  const individualMail = {
    to: emails,
    from: senderEmail,
    templateId: TEMPLATE_ID,
    dynamic_template_data: {
        subject: event.subject,
        text: event.text,
        id: ids // sends all ids to everyone instead of a single id in every mail
  }

  await sendGridMail.send(individualMail);
  return {success: true};
});

我需要遍历电子邮件和 ID,还是 SendGrid API 对此行为有更智能的实现?

【问题讨论】:

    标签: javascript typescript google-cloud-firestore sendgrid sendgrid-api-v3


    【解决方案1】:

    您必须仔细阅读这些元素中的每一个才能获取值并构造对象。

    可能参数未正确包含在请求正文中。请注意,个性化对象包含为每封邮件提供的数据。

    https://sendgrid.com/docs/ui/sending-email/how-to-send-an-email-with-dynamic-transactional-templates/#send-a-transactional-email

    var data = JSON.stringify({
      "personalizations": [
        {
          "to": [
            {
              "email": "john.doe@example.com",
              "name": "John Doe"
            }
          ],
          "dynamic_template_data": {
            "verb": "",
            "adjective": "",
            "noun": "",
            "currentDayofWeek": ""
          },
          "subject": "Hello, World!"
        }
      ],
      "from": {
        "email": "noreply@johndoe.com",
        "name": "John Doe"
      },
      "reply_to": {
        "email": "noreply@johndoe.com",
        "name": "John Doe"
      },
      "template_id": "<<YOUR_TEMPLATE_ID>>"
    });
    
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === this.DONE) {
        console.log(this.responseText);
      }
    });
    
    xhr.open("POST", "https://api.sendgrid.com/v3/mail/send");
    xhr.setRequestHeader("authorization", "Bearer <<YOUR_API_KEY_HERE>>");
    xhr.setRequestHeader("content-type", "application/json");
    
    xhr.send(data);
    

    【讨论】:

    • 我不完全明白。你能提供一个代码示例吗?
    猜你喜欢
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 2021-03-22
    • 2023-03-15
    • 2016-11-30
    • 1970-01-01
    • 2019-06-20
    • 2015-11-11
    相关资源
    最近更新 更多