【发布时间】:2021-11-17 19:08:25
【问题描述】:
我正在尝试弄清楚如何使用 Mailchimp 在交易电子邮件中发送附件。根据documentation,attachments 数组必须包含具有type、name 和content 属性的对象。我想不通的是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