You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Google Apps Script结合Mailchimp API发送带附件的事务性邮件

解决方案

附件损坏的核心原因是你对二进制文件使用了getDataAsString()方法做转换,该方法会将二进制字节按照默认字符集解码为文本,非文本类附件的字节序列不满足文本编码规则,会出现字节丢失、转义错误,后续再做base64编码得到的就是无效内容。

你只需修改两处代码即可解决问题:

  • 调整content的生成逻辑,直接对文件blob的原始字节数组做base64编码,不需要中转成字符串
  • 修正UrlFetchApp的请求头配置参数名,将单数header改为官方要求的复数headers,避免请求头配置不生效

修改后的完整代码如下:

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().getBytes());

  const options = {
    // 修正参数名为复数headers
    headers: {
      '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;
};

内容的提问来源于stack exchange,提问作者Dmitry Kostyuk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:24:04