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):
- The incoming mails are from the same sender (a machine) with the same subject every time.
- The email arrives at random timing, could be several mails in a minute or nothing in few hours.
- 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();
}
}