0
votes

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.

enter image description here

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?

1

1 Answers

0
votes

Well turns out, saving a file to the root, then copying it to another directory and then delete the original file takes longer than just put it in the correct directory to begin with.

I changed this:

               var file = DriveApp.createFile(attachmentBlob);
            if (parentFolder.addFile(file)) {
                root.removeFile(file);

            }

to this:

var file = parentFolder.createFile(attachmentBlob);

Although I'm pretty sure this method wasn't always possible. Maybe I'm mistaken.