微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

使用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 Attachment extractor插件等),但它们都不是真的真的很酷.这就是为什么我正在寻找通过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 ServiceGmail 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&纯文本电子邮件 – 现在应该在多个边界字符串上工作

原文地址:https://www.jb51.cc/js/157817.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐