'Running a for loop for queried messages gives an error message
I am trying to write a simple script that is giving me some issues. The objective of the script is to upload the PDF attachments of any messages within a certain label onto a Google Drive folder. The script should work as follows:
- Incoming emails will be added to the "To-Upload Scan2GoogleDrive" label. This will be achieved with a Gmail filter.
- The script will query messages using the variable querythreads. Basically emails with PDF attachments and in the "To-Upload Scan2GoogleDrive" label
- For each message in the query check if it has an attachment that ends with .pdf. get the file name and upload it to a Google Drive Folder.
- Once completed, remove the "To-Upload Scan2GoogleDrive" label and add the "Upload Complete Scan2GoogleDrive" label for each message.
Unfortunately, the script gives an error message(shown below). It seems that the code runs once and then stops midway. Checking the emails in the label it also appears that only one email was uploaded and moved to the completed label. I am not sure why the var=attachments line works the first time but when it loops back it fails.
TypeError: Cannot read property 'getAttachments' of undefined uploadGmailToDrive @ Code.gs:28
Any help would be appreciated on this problem. Thanks in advance.
var teamDriveFolderID = DriveApp.getFolderById("Replace with a folder ID")
var queryThreads = GmailApp.search("label:To-Upload Scan2GoogleDrive filename:pdf")
var label = GmailApp.getUserLabelByName("To-Upload Scan2GoogleDrive")
var labelDone = GmailApp.getUserLabelByName("Upload Complete Scan2GoogleDrive")
//check if the appropriate labels are in the users inbox. If not, create them.
function checkLabels() {
if (!label) {
labelTest = GmailApp.createLabel("To-Upload Scan2GoogleDrive");
Logger.log("Label To-Upload Scan2GoogleDrive was created");
}
if (!labelDone) {
labelTestDone = GmailApp.createLabel("Upload Complete Scan2GoogleDrive");
Logger.log("Label Upload Complete Scan2GoogleDrive was created");
}
};
//run the checklabel function shown above. Then query the messages based on the queryThreads variable. For each message, check
function uploadGmailToDrive() {
checkLabels()
var msgs = GmailApp.getMessagesForThreads(queryThreads);
for (var i = 0; i < msgs.length; i++) {
var msg = msgs[i];
var attachments = msg[i].getAttachments();
for (var j = 0; j < attachments.length; j++) {
var attachment = attachments[j];
if (attachment.getName().endsWith(".pdf")) {
var file = attachment.getAs("application/pdf");
var fileName = file.getName();
var fileId = teamDriveFolderID.createFile(fileName, file);
Logger.log("File uploaded to team drive: " + fileId);
}
}
}
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
