如何在 sendgrid 中发送带有 .xlsx 附件的电子邮件?

how to send email with .xlsx attachment in sendgrid?

下面是用来发送邮件的消息对象。

 message = {
        to: toEmail,
        from: emailInfo.emailFromAddress,
        subject: emailInfo.emailSubjectTemplate,
        attachments: [
          {
            filename: fileName,
            content: base64str,
            contentId: fileName,
            disposition: "attachment"
          }
        ],
        html: emailMessageBodyTemplate
      };

内容通过以下代码编码成base64字符串。

const base64_encode = file => {
  var bitmap = fs.readFileSync(file);
  return new Buffer(bitmap).toString("base64");
};

我不知道我哪里出错了,但我收到如下错误。

留言:"The content value must be a string at least one character in length."

但是调试的时候内容不为空是base64字符串

请帮忙。

在这个 page 上它准确地描述了你的错误。

我认为此错误内容是指您的消息或错误描述的文本

You may not send an email with no content.

并且根据 API 文档,您缺少必需的参数内容。

message = {
            to: toEmail,
            from: emailInfo.emailFromAddress,
            subject: emailInfo.emailSubjectTemplate,
            content:[
              {
                 type : 'string',
                 value : 'message'
              }
            ],
            attachments: [
              {
                filename: fileName,
                content: base64str,
                contentId: fileName,
                disposition: "attachment"
              }
            ],
            html: emailMessageBodyTemplate
          };

希望对您有所帮助。

我遇到了同样的问题,在我的例子中,我使用 'xlsx' npm lib 来实现解决方案如下:

const workbook = XLSX.utils.book_new();
const ws = XLSX.utils.aoa_to_sheet(data);
XLSX.utils.book_append_sheet(workbook, ws, 'Accounts');

// write the file in base64 format
const report = XLSX.write(workbook, { type: 'base64', compression: true });

const attachment = {
    content: report,
    filename: `MyReport.xlsx`,
    type: 'text/html',
    disposition: 'attachment'
};