问题描述
如何使用 Google MailApp api 包含电子邮件标头信息?
我需要提供标头信息,例如 List-Unsubscribe:
或 List-Unsubscribe-Post:
。
以下是 Google Apps 脚本的代码示例。似乎没有包含此类电子邮件标题信息的选项。
sendEmail(recipient,subject,body,options)
// Send an email with two attachments: a file from Google Drive (as a PDF) and an HTML file.
var file = DriveApp.getFileById('1234567890abcdefghijklmnopqrstuvwxyz');
var blob = Utilities.newBlob('Insert any HTML content here','text/html','my_document.html');
MailApp.sendEmail('mike@example.com','Attachment example','Two files are attached.',{
name: 'Automatic Emailer Script',attachments: [file.getAs(MimeType.PDF),blob]
});
解决方法
我相信你的目标如下。
- 您想将
List-Unsubscribe
和List-Unsubscribe-Post
的自定义标头添加到 Gmail 并使用 Google Apps 脚本发送。
在这种情况下,以下流程如何?
- 创建草稿作为临时。
- 在这种情况下,将使用脚本中
MailApp.sendEmail
的参数。
- 在这种情况下,将使用脚本中
- 添加自定义标题。
- 删除草稿。
- 使用 Gmail API 发送草稿。
当此流程反映到您的脚本时,它会变成如下所示。
修改后的脚本:
在使用此脚本之前,please enable Gmail API at Advanced Google services。
var obj = {"List-Unsubscribe": "sample1","List-Unsubscribe-Post": "sample2"}; // Please set the custom headers.
// 1. Create a draft as a temporal.
var file = DriveApp.getFileById('1234567890abcdefghijklmnopqrstuvwxyz');
var blob = Utilities.newBlob('Insert any HTML content here','text/html','my_document.html');
var draft = GmailApp.createDraft('mike@example.com','Attachment example','Two files are attached.',{
name: 'Automatic Emailer Script',attachments: [file.getAs(MimeType.PDF),blob]
});
// 2. Add the custom headers.
var data = Object.entries(obj).map(([k,v]) => `${k}: ${v}`).join("\n") + "\n" + draft.getMessage().getRawContent();
// 3. Delete Draft.
draft.deleteDraft();
// 4. Send the draft using Gmail API.
var res = Gmail.Users.Messages.send({raw: Utilities.base64EncodeWebSafe(data)},"me");
console.log(res)
- 在此示例中,
List-Unsubscribe: sample1
和List-Unsubscribe-Post: sample2
用作示例值。请根据您的实际情况进行修改。