The premium version of Save Gmail addon offers an option to overwrite existing files in Google Drive instead of creating a new file.

For instance, a sales company receives disk backups in zip format every midnight in their Gmail account. They use the addon to automatically download this file attachments to a specific folder in Google Drive. However, instead of creating multiple copies of the backup, they just want the program to overwrite the existing file and not create a new file.

replace-drive-files.png

Go to the add-on menu inside the Google Spreadsheet, choose Save Emails > Create Rule and check the option that says “Overwrite attachments”. Now if you receive another email attachment with the same name as the one that already exists in the current folder, the addon will simply replace the file content without changing the name, location or description of the file. Even the old file links would continue to work.

How to Overwrite Files in Google Drive with Google Apps Script

Internally, the add-on uses the Advanced Drive API service of Google Script to overwrite existing files by replacing the content.

Here’s a sample snippet that downloads a Gmail attachment to Google Drive but creates a new file only if none exist.

function overwriteFilesInGoogleDrive(messageId, folderId) {
  
  // Get the Gmail Message
  var message = GmailApp.getMessageById(messageId);
  
  // Get the parent Google Drive folder
  var folder = DriveApp.getFolderById(folderId);
  
  // Get the first Gmail attachment
  
  var att = message.getAttachments()[0];
  var filename = att.getName();
  
  // Find if files of the same name exist in that folder
  var existing = folder.getFilesByName(filename);
  
  // Does file exist?
  if (existing.hasNext()) {
  
    var file = existing.next();
    
    // Make sure the file name is exactly the same
    if (file.getName() === filename) {
    
      // Updates file metadata and/or content with the Drive API
      Drive.Files.update({
        title: file.getName(), mimeType: file.getMimeType()
      }, file.getId(), att.copyBlob());
    }
    
  }
}

← Save Gmail to Google Drive