function monitorEmails() {
var threads = GmailApp.search('is:unread');
var csvFileId = 'LinkToCSVFile'; // Replace with the ID of the CSV file in Google Drive
var csvFile = DriveApp.getFileById(csvFileId);
var csvContent = csvFile.getBlob().getDataAsString();
var csvData = Utilities.parseCsv(csvContent, ';'); // Specify the semicolon as the delimiter
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
//Logger.log("FOR loop execution");
for (var j = 0; j < messages.length; j++) {
var message = messages[j];
var subject = message.getSubject();
var attachments = message.getAttachments();
// Search for the corresponding folder in the CSV file
var correspondingFolder = findCorrespondingFolder(csvData, subject);
//Logger.log("Destination folder found: " + correspondingFolder);
if (correspondingFolder) {
copyAttachments(attachments, correspondingFolder);
}
// Mark the email as read
message.markRead();
}
}
}
// Move the function definition outside of monitorEmails
function findCorrespondingFolder(csvData, title, folder) {
for (var i = 0; i < csvData.length; i++) {
var csvTitle = csvData[i][0];
var folder = csvData[i][1];
if (csvTitle.toLowerCase().trim() === title.toLowerCase().trim()) {
return folder;
}
}
return null; // No corresponding folder found
}
function copyAttachments(attachments, destinationFolderId) {
var destinationFolder = DriveApp.getFolderById(destinationFolderId);
for (var i = 0; i < attachments.length; i++) {
var attachment = attachments[i];
var attachmentName = attachment.getName();
Logger.log(attachmentName);
// Get the content of the attachment
var attachmentContent = attachment.getBytes();
Logger.log(attachmentContent);
// Create a file in the destination folder with the content of the attachment
destinationFolder.createFile(attachmentName, attachmentContent);
}
}