Automatically Save Email Attachments to Google Drive

Email communication remains a crucial aspect of work and collaboration. Google Workspace, formerly known as G Suite, offers a suite of tools that streamline productivity, and in this post, we’ll explore how to automate the process of saving email attachments from a Google Group, or any other Inbox, to a specific folder in Google Drive.

Cover

Problem

Imagine you’re managing a Google Group, where important attachments are regularly sent. Manually saving these attachments to your Google Drive can be time-consuming and prone to errors. Is there a way to automate this process and ensure that you don’t miss any crucial documents?

Solution

The solution lies in leveraging the power of Google Apps Script, a versatile scripting language that integrates seamlessly with Google Workspace services. By creating a custom script, you can automate the process of extracting attachments from emails received in your Google Group and saving them to a specific folder in Google Drive.

Here’s how you can achieve this:

  1. Creating the Script: Begin by creating a Google Apps Script project within your Google Drive. This project will contain the code that automates the attachment-saving process.
  2. Retrieving Email Attachments: Utilize GmailApp, a built-in service in Google Apps Script, to search for emails in your Google Group that contain attachments. Loop through these emails, extract the attachments, and prepare them for saving.
  3. Accessing Google Drive: To save the attachments, use DriveApp, another service in Google Apps Script. You can identify the destination folder in Google Drive by its unique folder ID.
  4. Automating Execution: Set up a time-based trigger for your script. This trigger will periodically run the script, ensuring that new attachments are automatically saved to Google Drive.

Create the Script

Below is a sample Google Apps Script that automatically saves attachments from emails received in your Google Group to a specified folder in Google Drive. Please note that you’ll need to customize some parts of the script, such as the folder ID and the search query, to fit your specific use case.

  1. Open Google Drive.
  2. Create a new Google Apps Script project by clicking on “New” > “More” > “Google Apps Script.”
  3. Replace the default code with the script provided below.
  4. Save the script and give it a name.
  5. Run the script manually the first time to grant permissions for accessing Gmail and Drive.
  6. Set up a trigger to run the script periodically (e.g., every hour).
function saveNewAttachmentsToDrive() {
  var folderId = "PUT_YOUR_FOLDER_ID_HERE"; // Replace with the ID of the destination folder in Google Drive
  var searchQuery = "to:[email protected] has:attachment"; // Replace with the search query to find emails with attachments
  var lastExecutionTime = getLastExecutionDate();
  var threads = GmailApp.search(searchQuery + " after:" + lastExecutionTime);
  var driveFolder = DriveApp.getFolderById(folderId);
  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    for (var j = 0; j < messages.length; j++) {
      var message = messages[j];
      var attachments = message.getAttachments();
      for (var k = 0; k < attachments.length; k++) {
        var attachment = attachments[k];
        var attachmentBlob = attachment.copyBlob();
        var fileName = attachment.getName();
        driveFolder.createFile(attachmentBlob).setName(fileName);
      }
    }
  }
  updateLastExecutionDate();
}

function getLastExecutionDate() {
  var properties = PropertiesService.getUserProperties();
  return properties.getProperty("lastExecutionDate") || "2023-09-01";
}

function resetLastExecutionDate() {
  PropertiesService.getUserProperties().deleteProperty("lastExecutionDate");
}

function updateLastExecutionDate() {
  var now = new Date();
  var dateString = now.toISOString().split("T")[0];
  var properties = PropertiesService.getUserProperties();
  properties.setProperty("lastExecutionDate", dateString);
}

Important Notes:

Make sure to replace PUT_YOUR_FOLDER_ID_HERE with the actual ID of the destination folder in your Google Drive. To get the folder ID, open the folder in Google Drive, and the ID can be found in the URL after “folders/”. Modify the searchQuery variable to match the criteria for emails you want to process. The example query looks for emails from a specific email address ([email protected]) with attachments, but you can adjust it based on your requirements. Remember that running the script will save attachments from the matching emails in the specified folder in Google Drive. Ensure that you have the necessary permissions to access the Google Group and the destination folder in Drive.

Automating Execution with Triggers

Once you’ve created your Google Apps Script, the next step is to ensure that the script runs automatically at specified intervals. This is achieved through triggers, which schedule the execution of your script according to your desired timeframe.

Here’s how you can set up a trigger for your script:

  1. Open Script Editor: In your Google Apps Script project, click on the menu “Extensions” > “Apps Script.” This will open the Script Editor.
  2. Create a Trigger: In the Script Editor, click on the clock icon (Triggers) located on the left sidebar. This will open the triggers panel.
  3. Add New Trigger: Click on the “+ Add Trigger” button in the bottom right corner. This will open the trigger configuration window.
  4. Configure Trigger: In the trigger configuration window, you’ll need to specify the following details:
  5. Choose which function to run: Select the function you want to trigger. In our case, it’s the function responsible for saving attachments (saveNewAttachmentsToDrive).
  6. Choose which deployment should run: Select “Head.”
  7. Select event source: Choose “Time-driven.”
  8. Select type of time based trigger: Select your preferred interval (e.g., every hour, every day, every week).
  9. Save Trigger: Once you’ve configured the trigger settings, click the “Save” button. The trigger will now be active and will automatically execute your script at the specified intervals.
  10. Review and Manage Triggers: You can view and manage your triggers at any time by returning to the triggers panel in the Script Editor. Here, you can edit, delete, or adjust the schedule of your triggers as neede

Conclusion

Automating tasks using Google Apps Script can significantly enhance productivity by eliminating manual, repetitive processes. In this post, we explored how to use Google Apps Script to automatically save email attachments from a Google Group to a designated folder in Google Drive. By implementing this solution, you can ensure that important documents are organized and accessible while minimizing the time and effort spent on manual tasks.