簡體   English   中英

使用Google Apps腳本刪除Gmail電子郵件的附件

[英]Remove an attachment of a Gmail email with Google Apps Script

使用Google Apps腳本( http://script.google.com ),我從文檔中了解如何發送,轉發,轉移到垃圾郵件等,但我找不到如何刪除電子郵件的文件附件 ,即:

  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 + Attachment提取器插件等),但它們都不是真的很酷。 這就是為什么我正在尋找通過Google Apps腳本手動執行此操作的解決方案。

看起來必須重新創建消息 - ish

消息是不可變的:它們只能被創建和刪除。 除了應用於給定消息的標簽之外,不能更改任何消息屬性。

通過Gmail API插入()使用高級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和僅純文本的電子郵件 - 現在應該可以處理多個邊界字符串

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM