使用 Google Apps 脚本 ( http://script.google.com ),我从 the docs 知道、如何发送、转发、移至垃圾邮件等,但我没有找到如何删除电子邮件的文件附件,即:
- 保留文本内容(HTML 或纯文本都可以)
- 保留原始发件人,保留收件人
- 保留原始消息的日期/时间(重要!)
- 删除附件
如果无法通过 API,是否可以在保留 1、2 和 3 的同时将消息重新发送给我自己?
注:GmailAttachment
类看起来很有趣并允许列出收件人:
var threads = GmailApp.getInboxThreads(0, 10);
var msgs = GmailApp.getMessagesForThreads(threads);
for (var i = 0 ; i < msgs.length; i++) {
for (var j = 0; j < msgs[i].length; j++) {
var attachments = msgs[i][j].getAttachments();
for (var k = 0; k < attachments.length; k++) {
Logger.log('Message "%s" contains the attachment "%s" (%s bytes)',
msgs[i][j].getSubject(), attachments[k].getName(), attachments[k].getSize());
}
}
}
但我找不到如何删除附件。
注意:我已经研究了许多其他解决方案,我已经阅读了几乎所有关于此的文章(具有专用 Web 服务的解决方案,以及 Thunderbird 等本地客户端 + 附件提取器插件等) ,但他们都不是真的很酷。这就是为什么我一直在寻找通过 Google Apps 脚本手动执行此操作的解决方案。
最佳答案
看起来消息必须是 re-created-ish :
Messages are immutable: they can only be created and deleted. No message properties can be changed other than the labels applied to a given message.
使用 Advanced Gmail Service与 Gmail API insert()您可以使用以下方法绕过它:Gmail.Users.Messages.insert(resource, userId)
此高级服务 must be enabled使用前。
示例:[在 EMAIL_ID
中填写 email_id
或以任何您希望获取电子邮件的方式]
function removeAttachments () {
// Get the `raw` email
var email = GmailApp.getMessageById("EMAIL_ID").getRawContent();
// Find the end boundary of html or plain-text email
var re_html = /(-*\w*)(\r)*(\n)*(?=Content-Type: text\/html;)/.exec(email);
var re = re_html || /(-*\w*)(\r)*(\n)*(?=Content-Type: text\/plain;)/.exec(email);
// Find the index of the end of message boundary
var start = re[1].length + re.index;
var boundary = email.indexOf(re[1], start);
// Remove the attachments & Encode the attachment-free RFC 2822 formatted email string
var base64_encoded_email = Utilities.base64EncodeWebSafe(email.substr(0, boundary));
// Set the base64Encoded string to the `raw` required property
var resource = {'raw': base64_encoded_email}
// Re-insert the email into the user gmail account with the insert time
/* var response = Gmail.Users.Messages.insert(resource, 'me'); */
// Re-insert the email with the original date/time
var response = Gmail.Users.Messages.insert(resource, 'me',
null, {'internalDateSource': 'dateHeader'});
Logger.log("The inserted email id is: %s",response.id)
}
这将从电子邮件中删除附件并将其重新插入您的邮箱。
编辑/更新:新的 RegExp 仅适用于 html 和纯文本电子邮件 - 现在应该适用于多个边界字符串
关于javascript - 使用 Google Apps 脚本删除 Gmail 电子邮件的附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46434390/