I have a homemade script for saving attachments to Drive from Gmail. I'm looping through the attachments and Logging the time when each attachment is saved. I've noticed some weird discrepancies between some saves. As the following image shows. Sometimes there is a minute and a half between loops. Each file is a pdf and they are all roughly the same size, e.g. 100 kb. each. It's not unusual that this script processes 50 attachments from a single email.
My for loop is as follows:
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);
if (parentFolder.addFile(file)) {
root.removeFile(file);
writeToSheet(file, message, msgId, k, totalattachments)
}
}
Below are the relevant functions.
function checkIfDefinedType_(attachment) {
var fileName = attachment.getName();
var temp = fileName.split('.');
var fileExtension = temp[temp.length - 1].toLowerCase();
if (fileTypesToExtract.indexOf(fileExtension) !== -1) return true;
else return false;}
function writeToSheet(file, message, msgId, k, totalattachments) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var fileId = file.getId();
var fileUrl = file.getUrl();
var formattedDate = Utilities.formatDate(new Date(), "GMT", "dd-MM-yyyy HH:mm:ss");
var emailSubject = message.getSubject();
var emailFrom = message.getFrom();
var sheet = ss.getSheetByName('Log');
sheet.appendRow([msgId, formattedDate, emailFrom, emailSubject, k, totalattachments, file, fileId, fileUrl]);}
Is there something wrong with my code?
