【问题标题】:Sendgrid multiple attachments using URLSendgrid 使用 URL 的多个附件
【发布时间】:2022-02-11 07:19:23
【问题描述】:

我在为 sendgrid 实现多个附件时遇到了困难。我面临的问题是fetchAttach 函数请求在创建sendEmail 对象之前没有返回textBuffered,即使它是async/await 函数。下面是我的代码以便更好地理解以及日志的结果

let fileNames = [
  "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
  "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
];
let attachments = [];

async function fetchAttach(file) {
  let textBuffered;
  request(file, { encoding: null }, (err, res, body) => {
    if (err) {
      console.log("Error-->", err);
    }
    if (res) {
      console.log(res.statusCode);
    }
    if (body) {
      textBuffered = Buffer.from(body);
      console.log("textBuffered");
    }
  });
  return textBuffered;
}

app.post("/api/custom-email", async (req, res) => {
  const {
    firstName,
    lastName,
    email,
    message
  } = req.body;
   
  for (let file of fileNames) {
    await fetchAttach(file)
      .then((res) => {
        console.log("1st. then");
        const attachObj = {
          content: res.toString("base64"),
          filename: `${firstName}${lastName}.pdf`,
          type: "application/pdf",
          disposition: "attachment",
          content_id: "mytext",
        };
        attachments.push(attachObj);
      })

      .then(() => {
        console.log("attachments-->", attachments);
        console.log("2nd .then triggered");
        const sendEmail = {
          method: "POST",
          url: "https://api.sendgrid.com/v3/mail/send",
          headers: {
            "content-type": "application/json",
            Authorization: `Bearer SG.xxxxxxxxxxxxxxxxxxxxxxxxxxx`,
          },
          body: {
            personalizations: [
              {
                to: [
                  {
                    email,
                    name: `${firstName} ${lastName}`,
                  },
                ],
                dynamic_template_data: {
                   message,

                },
              },
            ],
            from: {
              email: "info@xxxxx.com",
              name: `(Do not reply) - ${businessName}`,
            },
            reply_to: {
              email: "info@xxxxx.com",
              name: "xxxxxxx",
            },
            template_id: "d-xxxxxxxxxxxxxxxxxx",
            attachments: attachments,
          },
          json: true,
        };

        console.log("sendEmail triggered");
      });
  }
 
  return res.send("OK");
});

以下是控制台中的日志:

1st. then
attachments--> [
  {
    content: undefined,
    filename: 'testEmaila.pdf',
    type: 'application/pdf',
    disposition: 'attachment',
    content_id: 'mytext'
  }
]
2nd .then triggered
sendEmail triggered
1st. then
attachments--> [
  {
    content: undefined,
    filename: 'testEmaila.pdf',
    type: 'application/pdf',
    disposition: 'attachment',
    content_id: 'mytext'
  },
  {
    content: undefined,
    filename: 'testEmaila.pdf',
    type: 'application/pdf',
    disposition: 'attachment',
    content_id: 'mytext'
  }
]
2nd .then triggered
sendEmail triggered
200
textBuffered
200
textBuffered

【问题讨论】:

    标签: javascript promise request base64 sendgrid


    【解决方案1】:

    我使用this post 找到了上述问题的解决方案。

    request npm 包不支持 async/await 而我最终使用了request-promise 包,现在我的fetchAttach 函数如下所示

    async function fetchAttach(file) {
      let textBuffered;
      await request(file, { encoding: null }, (err, res, body) => {
        if (err) {
          console.log("Error-->", err);
        }
        if (res) {
          console.log(res.statusCode);
        }
        if (body) {
          textBuffered = Buffer.from(body);
          console.log("textBuffered");
        }
      });
      return textBuffered;
    }
    

    request(file, ...) 之前添加了awaitrequest-promise 包支持。

    【讨论】:

    • Twilio SendGrid 开发人员传道者在这里。我很高兴你找到了这个解决方案,我只是想指出 request 和 request-promise 都已被弃用。我建议您使用不同的 HTTP 库,例如 node-fetchgot(它们都支持承诺)来提出您的请求。
    猜你喜欢
    • 1970-01-01
    • 2022-08-16
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-30
    • 1970-01-01
    • 2021-10-24
    相关资源
    最近更新 更多