【问题标题】:How to send a transactional email with attachment with Google Apps Script and Mailchimp API如何使用 Google Apps Script 和 Mailchimp API 发送带有附件的交易电子邮件
【发布时间】:2021-11-17 19:08:25
【问题描述】:

我正在尝试弄清楚如何使用 Mailchimp 在交易电子邮件中发送附件。根据documentationattachments 数组必须包含具有typenamecontent 属性的对象。我想不通的是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()

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

【问题讨论】:

  • 我尝试在线转换我在驱动器中的文件的 Base64 并且这种方法有效。 content = Utilities.base64Encode(file.getBlob().getBytes())base64Encode 适用于字节数组。如果它有特殊字符,您可以向它添加特定的字符集(例如 Utilities.Charset.UTF_8)。如果它仍然不起作用,请尝试变体base64EncodeWebSafe。只是总是尝试将字节数组作为其参数。
  • 最好的测试方法是在尝试将其转换为文件时检查作为 base64 获得的那个是否正常工作。您可以尝试将 base64 转换为文件或从中创建驱动器文件并检查它是否是正确的 base64 的在线站点。正如我测试过的,getDataAsString 返回的 Base64 会出错。需要原始字节,所以 getBytes 在我的测试中成功了。
  • @NaziA 谢谢,这有效!如果您写出答案,我将非常乐意接受。
  • 我很高兴它成功了@DmitryKostyuk,我已经根据我的 cmets 创建了一个答案。

标签: google-apps-script mailchimp mailchimp-api-v3.0 mailchimp-api-v3


【解决方案1】:

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

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

base64Encode 按照documentation 的建议在字节数组上工作。如果它有特殊字符,你可以添加特定的字符集(例如Utilities.Charset.UTF_8)。

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

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

【讨论】:

  • Utilities.base64Encode(file.getBlob().getBytes()) 完美地完成了这项工作,谢谢!
猜你喜欢
  • 2014-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 2012-08-13
  • 2011-05-18
  • 1970-01-01
  • 2021-11-21
相关资源
最近更新 更多