Sendgrid - 通过动态模板添加电子邮件附件

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

我在 Node.js 和 Express 环境中使用 Sendgrid API v3。

我正在使用电子邮件动态模板,我可以轻松地将自定义文本发送到电子邮件模板。

但我还需要添加附件,但我找不到相关文档。我需要以两种不同的方式添加附件:

  1. 有些电子邮件需要始终具有相同的附件,无论发送到 sendgrid 的服务器数据是什么,电子邮件模板最好有自己的附件发送到客户收件箱。
  2. 如果客户端购买电子书,该文件应由服务器与其余的 {{{data}}} 一起发送到 Sendgrid,并且该特定文件应作为附件传递给客户端。

谁能告诉我如何添加附件吗?

谢谢

sendgrid email-attachments sendgrid-templates
2个回答
2
投票

使用动态模板和附件发送电子邮件。参考他们的 API 文档

Sendgrid 电子邮件 API 带附件:


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

const fs = require("fs");

pathToAttachment = `${__dirname}/attachment.pdf`;
attachment = fs.readFileSync(pathToAttachment).toString("base64");

const msg = {
  to: '[email protected]',
  from: '[email protected]',
  subject: 'Sending with SendGrid is Fun',
  templateId: "d-11111111111111111111111111",
  attachments: [
    {
      content: attachment,
      filename: "attachment.pdf",
      type: "application/pdf",
      disposition: "attachment"
    }
  ]
};

sgMail.send(msg).catch(err => {
  console.log(err);
});

对于您的两种情况,为什么不构建一个功能来发送带有动态模板ID和附件参数的电子邮件?

sendEmail(
  templateId: string, 
  attachments: Attachment
)

Sendgrid 电子邮件 API,带内嵌图像:

如果您需要将该图像包含在动态模板的 html 中,请添加

attachments.content_id
(也在文档中)。

来自文档:

内容 ID...当处置设置为“内联”时使用

例如,您的代码可能包含以下代码片段:

  attachments: [
    {
      content: attachment,
      filename: "my_cool_image.png",
      type: "application/pdf",
      disposition: "inline",
      content_id: "my_cool_image"
    }
  ]

在您的动态模板中:

   <img src="cid:my_cool_image" alt="cool" title="cool"/>

-1
投票

Sendgrid 附件的大小限制为 30mb,这对于您想要执行的操作来说可能太小了。 Sendgrid 让您可以使用 digioh api 发送最大 2GB 的文件。 https://digioh.com/sendgrid

另一种解决方案是在电子邮件中以文本形式发送回调 URL,该 URL 链接到 Express 服务器上的端点,让用户下载数据。在这种情况下,您需要一些额外的设置以确保只有购买了该项目的用户才能下载它们。

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