Search code examples
google-apps-scriptgoogle-drive-apigmail

How do I fix this app script so it doesn't drop files in the wrong place?


I have an app script project I use to pull attachments from emails with a certain tag, and put them in corresponding subfolders on Google Drive based on the file name.

Everything was running seamlessly until recently, when I get occasional files put in the main Google Drive folder by mistake. The script runs every 5 minutes, so those files end up being put in the right place as well.

I'm looking for an easy solution that either stops it from mistakenly adding these attachments to the main Drive folder by tweaking the code, or adding an additional section of code that skims the main drive folder and removes files pdf files that match.

Below is the code I'm using:

function saveAttachments() {
  var searchQuery = 'label:sign-ins is:unread has:attachment newer_than:1h'; // search query for Gmail messages
  var label = GmailApp.getUserLabelByName('sign-ins'); // label for marking processed messages
  var parentFolder = DriveApp.getFoldersByName('** SIGN INS **').next(); // parent folder for saving attachments
  
  var threads = GmailApp.search(searchQuery);
  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    for (var j = 0; j < messages.length; j++) {
      var attachments = messages[j].getAttachments();
      for (var k = 0; k < attachments.length; k++) {
        var attachment = attachments[k];
        var filename = attachment.getName();
        var subject = messages[j].getSubject();
        var folderName = subject.replace(/A filled document|has been submitted to you with pdfFiller LinkToFill./gi, '').trim();
        if (folderName) {
          var folder = getOrCreateSubfolder(parentFolder, folderName);
          var existingFiles = folder.getFilesByName(filename);
          if (!existingFiles.hasNext()) {
            var file = folder.createFile(attachment);
            label.addToThread(threads[i]);
          }
        }
      }
      messages[j].markRead();
    }
  }

  function getOrCreateSubfolder(parentFolder, folderName) {
    var folders = parentFolder.getFoldersByName(folderName);
    if (folders.hasNext()) {
      return folders.next();
    } else {
      return parentFolder.createFolder(folderName);
    }
  }
}

Solution

  • For your variable parentfolder you could try to set the folderID manually in the code rather than using the search for name. If the folder your importing to is a static folder that is.

    var folderId = "R8puyP1llQazAylcFP9PHAc65xOdxYJ"; // Replace with your folder ID
    var parentfolder = DriveApp.getFolderById(folderId);

    You can find your folder id by looking at the drive folders HTML link at the top of the window and you will see your folder id at the end

    https://drive.google.com/drive/u/0/folders/R8puyP1llQazAylcFP9PHAc65xOdxYJ
    

    If this works for you please let me know and or accept my answer! Thank you.