Remove an attachment of a Gmail email with Google Apps Script

99封情书 提交于 2019-12-03 14:06:58

Looks like messages will have to be 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.

Using Advanced Gmail Service with the Gmail API insert() you can hack your way around it using: Gmail.Users.Messages.insert(resource, userId)

This advanced service must be enabled before use.

Example: [fill in the EMAIL_ID with an email_id or in whatever way you want to get the email]

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)
}

This will remove the attachments from the email and re-insert it into your mailbox.

edit/update: New RegExp to work with html&plain-text only emails - should now work on multiple boundary strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!