0

我试图弄清楚如何使用 Mailchimp 在交易电子邮件中发送附件。根据文档attachments数组必须包含具有type,namecontent属性的对象。我想不通的是content。令人惊讶的是,我可以找到关于 SO 的相关问题。

文档说它的值必须是:

附件内容为 base64 编码字符串

所以我有这个发送电子邮件的功能,但附件内容已损坏(名称和类型看起来不错):

const sendEmail = emailObj => {
  console.log('sendEmail()');
  const URL = 'https://mandrillapp.com/api/1.0/messages/send';

  const { html, subject, toEmail, attachmentId } = emailObj;

  const file = DriveApp.getFileById(attachmentId);
  const type = file.getMimeType();
  const name = file.getName();
  const content = Utilities.base64Encode(file.getBlob().getDataAsString());

  const options = {
    header: {
      'Content-Type': 'application/json',
    },
    payload: JSON.stringify({
      key: 'key',
      message: {
        from_email: 'email@domain.com',
        subject,
        html,
        to: [
          {
            email: toEmail,
            type: 'to',
          },
        ],
        attachments: [
          {
            type,
            name,
            content,
          },
        ],
      },
    }),
  };


  const response = UrlFetchApp.fetch(URL, options);
  console.log(response.getContentText());
  return emailObj;
};

附件是带有正确名称的损坏的 PDF 文件。

我也尝试将内容设置为:

  • file.getBlob()
  • file.getBlob().getDataAsString()
  • file.getBlob().getBytes()

希望有人以前做过这个:)

4

1 回答 1

1

由于我目前的限制,我无法完全测试 API,我尝试在线转换驱动器中文件的 Base64 并且这种方法有效。

content = Utilities.base64Encode(file.getBlob().getBytes())

base64Encode如文档所示,适用于字节数组。如果它有特殊字符,您可以为其添加特定的字符集(例如Utilities.Charset.UTF_8)。

如果它仍然不起作用,请尝试变体base64EncodeWebSafe。只是总是使用它的字节数组作为它的参数。

测试它的最佳方法是在尝试将其转换为文件时检查作为 base64 获得的那个是否正常工作。您可以尝试将 base64 转换为文件或从中创建驱动器文件并检查它是否是正确的 base64 的在线站点。getDataAsString正如我测试的那样,返回时的 Base64会出错。需要原始字节,所以getBytes我的测试中的技巧也是如此。

于 2021-09-27T15:00:05.917 回答