Search code examples
google-apps-scriptgoogle-drive-apigmailgoogle-drive-shared-drive

Apps Script - Search Gmail label for all attachments and overwrite files to google drive folder


Using prior articles and questions found within stack overflow I was able to find a snippet of App Script that searches Gmail labels for attachments and moves them to a specific folder in Google Drive.

function saveAttachmentInFolder(){
  var folder = DriveApp.getFolderById('xxosi2');
  var userId = "[email protected]";
  var query = "label:thankyoucards-reports";
  var res = Gmail.Users.Messages.list(userId, {q: query});//I assumed that this works
  res.messages.forEach(function(m){
    var attA=GmailApp.getMessageById(m.id).getAttachments();
    attA.forEach(function(a){
      
      folder.createFile(a.copyBlob()).setName(a.getName());
    });
  });
}

I need to modify this code to perform the following additional functions:

  1. If file exists, overwrite and retain version history

I have also played around with the answer found in the following thread to no avail as I believe this is hard coded in some way and too specific to the one file type (xlsx) Copying attachments from Gmail to Google Drive folder and overwriting old files with Apps Script.


Solution

  • I believe your goal is as follows.

    • You want to check this using the filename between the existing file in the folder and the attachment file.
    • You want to overwrite the existing file with the attachment file.

    In this case, how about the following modification? In this case, Drive API is used. So, please enable Drive API at Advanced Google services.

    From:

    folder.createFile(a.copyBlob()).setName(a.getName());
    

    To:

    var filename = a.getName();
    var files = folder.getFilesByName(filename);
    if (files.hasNext()) {
      Drive.Files.update({}, files.next().getId(), a.copyBlob(), {supportsAllDrives: true});
    } else {
      folder.createFile(a.copyBlob()).setName(filename);
    }
    
    • When this modified script is run, the existing file is searched from the folder using the filename of the attachment file. When the file is found, the file is overwritten by the attachment file. When the file is not found, the file is created as a new file.

    Note:

    • In this modified script, the existing file is overwritten. So, please be careful about this. I would like to recommend using a sample file for testing the script.

    Reference: