Sendgrid:从 URL (JS) 附加 PDF

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

在我的 next.js 项目中,我使用 Sendgrid 发送电子邮件。

现在,我想附加一个来自 URL 的动态 PDF。我遵循了文档,我的代码如下所示:

const sgMail = require("@sendgrid/mail");
const { data } = await axios.get(url);
const textBuffered = Buffer.from(data);

sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
      to: "[email protected]",
      from: "[email protected]",
      attachments: [
        {
          content: textBuffered.toString("base64"),
          filename: file,
          type: "application/pdf",
          disposition: "attachment",
          content_id: "mytext",
        },
      ],
    };
    sgMail.send(msg).then(() => {
      console.log("Email sent");
      res.status(200).json({ message: "Mail sent!" });
    }).catch((error) => {
        console.log(error)
        return res.status(400).json({
          message: "There was a problem.",
        });
      });

我也尝试过这个解决方案,但它也没有用:

const https = require("https");
const fs = require("fs");

const fileTest = fs.createWriteStream("test.pdf");
const newPdf = https.get(
  url,
  function (response) {
    response.pipe(fileTest);
  }
);

sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
      to: "[email protected]",
      from: "[email protected]",
      attachments: [
        {
          content: fileTest.toString("base64"),
          filename: file,
          type: "application/pdf",
          disposition: "attachment",
          content_id: "mytext",
        },
      ],
    };
    sgMail.send(msg).then(() => {
      console.log("Email sent");
      res.status(200).json({ message: "Mail sent!" });
    }).catch((error) => {
        console.log(error)
        return res.status(400).json({
          message: "There was a problem.",
        });
      });

在这两种情况下,我都得到错误:

“unhandledRejection: ResponseError: Bad Request: code: 400,
回复: { 标题:{ 服务器:'nginx', 日期:'2023 年 2 月 25 日星期六 21:12:43 GMT', '内容类型':'应用程序/ json', '内容长度':'209', 连接:'关闭', 'access-control-allow-origin': 'https://sendgrid.api-docs.io', '访问控制允许方法':'POST', 'access-control-allow-headers': '授权,内容类型,代表,x-sg-elas-acl', '访问控制最大年龄':'600', 'x-no-cors-reason':'https://sendgrid.com/docs/Classroom/Basics/API/cors.html', 'strict-transport-security': 'max-age=600;包括子域' }, 正文:{错误:[数组]}}“

关于如何解决这个问题的任何想法?谢谢!!!

javascript axios pdf-generation sendgrid
© www.soinside.com 2019 - 2024. All rights reserved.