Remove Gmail Email Attachment Using Google Apps Script

Using Google Apps Script ( http://script.google.com ), I know from Docs how to send, forward, forward error messages, etc., but I didn’t find how to remove the file attachment via email , then there is:

  • save text content (either in HTML format or just in plain text).
  • save original sender, save recipient
  • keep the original date / hour of the message (important!)
  • remove attachment

If this is not possible using the API, is there a way to send a message to myself while keeping 1, 2, and 3?


Note: the class GmailAttachmentlooks interesting and allows you to list recipients:

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

but I can not find how to remove the attachment.

. , ( -, , Thunderbird + Attachment extractor plugin ..), . Google Apps Script.

+6
1

, re-created-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

+5

All Articles