用Google Apps脚本删除Gmail电子邮件的附件



使用Google Apps脚本(http://script.google.com),我从文档中知道,如何发送,向前,转到垃圾消息等。但是我不喜欢t查找如何删除电子邮件的文件附件,即:

  1. 保留文本内容(在html中或只是纯文本可以很好)
  2. 保留原始发件人,请保留收件人
  3. 保持原始消息日期/小时(重要!)
  4. 删除附件

如果无法通过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 Attactment Extractor插件等本地客户端等),但是它们都不是真的很酷。这就是为什么我正在寻找通过Google Apps脚本手动执行的解决方案。

看起来必须重新创建消息:

消息是不变的:只能创建和删除它们。除了应用于给定消息的标签外,无法更改消息属性。

使用Gmail API Insert()使用高级Gmail服务()您可以使用以下方式围绕它进行攻击:Gmail.Users.Messages.insert(resource, userId)

此高级服务必须在使用前启用

示例:[用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&amp; plain -text仅使用电子邮件 - 现在应该在多个边界字符串上使用

最新更新