Automatically save Gmail attachments to Google Drive

In this Post, script will Automatically save Gmail attachments to Google Drive folder. Script can be run manually or through a time-driven trigger.
Google Apps Script fetch the attachments and save them to Drive.

Automatically save Gmail attachments to Google Drive

Google Apps Script to save Gmail attachments to Google Drive

  • Create a new google apps script file.
  • And Paste the code as shown below
  • After that, you have to save the script (ctrl+s).
  • Final Step We have to set the trigger. How we set trigger
    script will run as per the specified interval.
  • We also need to authorize the script for the first time. If we are running the script first time, it will ask to authorize the script for “Gmail” and “Google Drive” access. Authorize it. You can see this post to authorize it Now the script installation is complete.
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:'+getDateNDaysBack_(1)+
  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.
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;
}

For save Gmail attachments to Google Drive we can also change a few points

  • You may change line 1, 3and 5 as per your preferences.
  • var fileTypesToExtract = [‘jpg’, ‘tif’, ‘png’, ‘gif’, ‘bmp’, ‘svg’]; You may add or remove file types from this array.
  • var folderName = ‘GmailToDrive’; name of the folder in which files will be saved automatically in Google 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 a name. You may change the label name too.