0

I copied some codes to move Gmail attachments to Google Drive, add a label to the mail, then trash or archive the mail (I have tried both trash and archive but results are the same):

  1. The incoming mails are from the same sender (a machine) with the same subject every time.
  2. The email arrives at random timing, could be several mails in a minute or nothing in few hours.
  3. The filenames has the suffix in yyyy-mm-dd-hh-mm-ss format.

The problem I am facing is when the script processes the new emails in the inbox, it also processes those in the trash. This results duplication of older files. Same problem happens even if I change moveToTrash() to moveToArchive().

How can I prevent my script from duplicating older files (from previously processed emails)?

function GmailToDrive(){
  //build query to search emails
  var query = '';
  //filename:jpg OR filename:tif OR filename:gif OR fileName:png OR filename:bmp OR filename:jpeg'; //'after:'+formattedDate+
  for(var i in fileTypesToExtract){
    query += (query === '' ?('filename:'+fileTypesToExtract[i]) : (' OR filename:'+fileTypesToExtract[i]));
  }
  query = 'in:inbox has:nouserlabels ' + query;
  var threads = GmailApp.search(query);
  var label = getGmailLabel_(labelName);
  var parentFolder;
  if(threads.length > 0){
    parentFolder = getFolder_(folderName);
  }
  var root = DriveApp.getRootFolder();
  for(var i in threads){
    var mesgs = threads[i].getMessages();
    mesgs.reverse();
    for(var j in mesgs){
      //get attachments
      var attachments = mesgs[j].getAttachments();
      for(var k in attachments){
        var attachment = attachments[k];
        var isDefinedType = checkIfDefinedType_(attachment);
        if(!isDefinedType) continue;
        var attachmentBlob = attachment.copyBlob();
        var file = DriveApp.createFile(attachmentBlob);
        parentFolder.addFile(file);
        root.removeFile(file);
      }
    }
    threads[i].addLabel(label);
    threads[i].moveToTrash();
    threads[i].refresh();
  }
}
tehhowch
  • 9,645
  • 4
  • 24
  • 42
  • Make sure you check that the message is not in the trash or archive before you work on its attachments. A label can apply to just one message in a thread (i.e. the newest one) but the whole thread is returned, not just the matched messages. – tehhowch Aug 26 '18 at 20:24
  • Possible duplicate of https://stackoverflow.com/q/51870530/ – tehhowch Aug 26 '18 at 20:35
  • Looks like I'll need to learn more before I can do it the way I want. Thanks anyway. – Hanzwer Aug 28 '18 at 23:49

0 Answers0