Skip to main content

Save Gmail Attachments to Google Drive using Google Apps Script


Introduction

Do you want to automatically save your attached files in a Gmail message to Google Drive?
This tutorial will do just that without you required to manually saving each attachment to a Drive folder.

This Google Apps Script will look for attachments in a Gmail Message and store it in a Google Drive folder.
The Script can be set to execute automatically through time driven triggers and can be initiated manually. 
You can modify the below code as per your specific requirements.

To copy the script please go to this Github Gist

Installation

  1. Make a copy of this script project.
  2. Click on the Triggers menu as shown in the below imagegoogle-apps-script-triggers
  3. Set the trigger interval as follows

  4. Authorize the script. If you are running the script first time, it will ask you to authorize the script for “Gmail” and “Google Drive” access. Authorize it. Now the script installation is complete.

This procedure can be followed with any Gmail account.
Once the installation is complete, script will run as per the specified interval, look for messages in Gmail which are not labelled and have attachments as file types specified.
It will extract the attachment to a Google Drive folder and label the Gmail Message 'GmailToDrive'.

apps script trigger setup


Complete Installation Process


Configure the script


// GLOBALS
//Array of file extension which you would like to extract to Drive
var fileTypesToExtract = ['jpg', 'tif', 'png', 'gif', 'bmp', 'svg'];
//Name of the folder in google drive i which files will be put
var folderName = 'GmailToDrive';
//Name of the label which will be applied after processing the mail message
var labelName = 'GmailToDrive';

var fileTypesToExtract = ['jpg', 'tif', 'png', 'gif', 'bmp', 'svg'];
This is an array for file types to look for. You may add or remove file types from this array.

var folderName = 'GmailToDrive';
This is the name of the folder to which files will be extracted to in Google Drive. If the script does not finds a folder with this name, it will create the folder in drive.

var labelName = 'GmailToDrive';

This label name is Gmail Label name. This is used by the script to identify which message has been processed and which has not not. Once a message is processed, script will put a label on those messages with below name. You may change the label name too.

/*
 * Note:
 * Gist created by CloudFort info@cloudfort.in
 * We provide Google Apps Script Development services.
 */

// GLOBALS
//Array of file extension which you would like to extract to Drive
var fileTypesToExtract = ['jpg', 'tif', 'png', 'gif', 'bmp', 'svg'];
//Name of the folder in google drive i which files will be put
var folderName = 'GmailToDrive';
//Name of the label which will be applied after processing the mail message
var labelName = 'GmailToDrive';



function GmailToDrive() {
  //build query to search emails
  var query = '';
  //filename:jpg OR filename:tif OR filename:gif OR fileName:png OR filename:bmp OR filename:svg'; //'after:'+formattedDate+
  for (var i in fileTypesToExtract) {
    query += (query === '' ? ('filename:' + fileTypesToExtract[i]) : (' OR filename:' + fileTypesToExtract[i]));
  }
  query = 'in:inbox has:nouserlabels ' + query;
  var threads = GmailApp.search(query);
  var label = getGmailLabel_(labelName);
  var parentFolder;
  if (threads.length > 0) {
    parentFolder = getFolder_(folderName);
  }
  var root = DriveApp.getRootFolder();
  for (var i in threads) {
    var mesgs = threads[i].getMessages();
    for (var j in mesgs) {
      //get attachments
      var attachments = mesgs[j].getAttachments();
      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);
        parentFolder.addFile(file);
        root.removeFile(file);
      }
    }
    threads[i].addLabel(label);
  }
}

//This function will get the parent folder in Google drive
function getFolder_(folderName) {
  var folder;
  var fi = DriveApp.getFoldersByName(folderName);
  if (fi.hasNext()) {
    folder = fi.next();
  }
  else {
    folder = DriveApp.createFolder(folderName);
  }
  return folder;
}

//getDate n days back
// n must be integer
function getDateNDaysBack_(n) {
  n = parseInt(n);
  var date = new Date();
  date.setDate(date.getDate() - n);
  return Utilities.formatDate(date, Session.getScriptTimeZone(), 'yyyy/MM/dd');
}

function getGmailLabel_(name) {
  var label = GmailApp.getUserLabelByName(name);
  if (!label) {
    label = GmailApp.createLabel(name);
  }
  return label;
}

//this function will check for filextension type.
// and return boolean
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;
}

If you require any assistance in setting up the script or need any modifications, contact us at info@cloudfort.in

Comments

Popular posts from this blog

How to generate certificate in google form automatically

Are you tired of manually creating and sending certificates for your participants? With the Smart Certificates add-on for Google Forms, you can automate this process and save yourself time and effort. In this tutorial, we'll guide you through the steps of setting up automated certificate generation and email delivery. Prerequisites Before we begin, make sure you have the following: A Google account A Google Form with relevant fields for certificate information (e.g., name, email) The Smart Certificates add-on installed from the Google Workspace Marketplace Step-by-Step Guide Install the Smart Certificates Add-on Check out the " Smart Certificates " add-on from here Install the add-on to your Google account. Connect to Your Google Form Open your Google Form and click on the "Add-ons" menu. Select "Smart Certificates" and open the sidebar. Authorize the add-on to access your Drive and form responses. Design Your Certificate Template In the Smart Certifi...

Welcome.

Welcome to CloudFort Blog.  A blog where you will find tutorials, walkthroughs and solutions for automating your Google Workspace. Periodic publishing of articles about Google Workspace, Apps Script and Google Cloud Platform. Let's dive in!