Backing up Gmail attachments based on the title.

62 views
Skip to first unread message

Johann Jimenez (Kurai Kitsune)

unread,
Oct 4, 2023, 9:41:05 AM10/4/23
to Google Apps Script Community
Hello, I've implemented a script that allows me to save received emails into a Google Drive folder, which is working fine. Now, I want to change my approach. I want to save attachments based on their title into separate folders in my Google Drive.

For example, when I receive an email with an attached photo and the title is 'Image1,' I want to save it in the 'Image1' folder. Similarly, when I receive an email with a photo and the title is 'Image2,' I want to save it in the 'Image2' folder.

I've set up a script that reads unread messages and then compares the email title with the first column of a CSV file I've stored on Google Drive.

Currently, the script successfully reads unread emails and saves the attachments to the corresponding folder. However, the issue is that I can't seem to save the attachment data properly. In my Google Drive folder, the files are unusable. I added a console.log to see what was happening, and the result is: 'Logging output too large. Truncating output.'

I believe that my method for saving the data is incorrect. Here is the script:
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);
  }
}
Thank you in advance, i'm a beginner sorry  also I talk french 

Johann Jimenez (Kurai Kitsune)

unread,
Oct 5, 2023, 5:59:46 AM10/5/23
to Google Apps Script Community
Okay I found it, instread of using a function to copy attachement i made it easier doing it into the  if (correspondingFolder) {  Now I implementend other things in the script to subfolders with date and time x)


    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) {
        // Create a "Backups" folder if it doesn't already exist within the corresponding folder
        var mailFolder = DriveApp.getFolderById(correspondingFolder);
        var backupsFolder;
        var existingFolders = mailFolder.getFoldersByName("Backups");

        if (existingFolders.hasNext()) {
          backupsFolder = existingFolders.next();
        } else {
          backupsFolder = mailFolder.createFolder("Backups");
        }

        // Create a subfolder with the email's received date
        var receivedDate = message.getDate();
        var dateString = Utilities.formatDate(receivedDate, Session.getScriptTimeZone(), 'yyyy-MM-dd HH:mm:ss');
        var subfolder = backupsFolder.createFolder(dateString);

        for (var k = 0; k < attachments.length; k++) {
          var file = attachments[k];
          Logger.log("Name: " + file);
          subfolder.createFile(file);
        }
      }

      // Mark the email as read
      message.markRead();
    }
  }
}

// Move the function definition outside of monitorEmails
function findCorrespondingFolder(csvData, title) {
  for (var i = 0; i < csvData.length; i++) {
    var csvTitle = csvData[i][0];
    var folder = csvData[i][1];
   
    Logger.log("CsvTitle = " + csvTitle);
    Logger.log("Folder = " + folder);
    if (csvTitle.toLowerCase().trim() === title.toLowerCase().trim()) {
      return folder;
    }
  }
  return null; // No corresponding folder found
}
So everything is now fine ^^ 

Bikram Purkait

unread,
Oct 5, 2023, 6:13:37 AM10/5/23
to Google Apps Script Community
Congratulations, you did it 👏.
Reply all
Reply to author
Forward
0 new messages