Save files to Google Drive automatically from Gmail

I have been using Gmail since it’s inception when it was still an invite only email service and haven’t looked back. It’s flexibility and speed have made it my personal email account of choice and with Google steadily adding more services to Gmail and their other online collaboration tools it’s always getting better. So I was intrigued when I found out that Google were giving you a way to extend their Google Apps services further with Google App Script. Although it’s primarily aimed towards businesses that are leveraging Google Apps, you can use App Script to automate your own workflows to make your digital life that little bit easier.

For more information on App Script please visit the App Script Developer Site

In this post I will share a quick Google App Script that I wrote to save email bills sent as PDF’s automatically to my Google Drive, in the correct folder and then label the original email with a Gmail label. It’s pretty annoying having to go through your email and click save and then placing the file into the right folder each time, why not just automate it, so it’s in the right folder with the month-year of when it was received and synced to my laptop.

So let’s start by first creating our App Script Project, head over to script.google.com and change the project name to something descriptive, like Save PDF’s from Telstra. Following the Project name, copy and paste the following JavaScript code to the App Script IDE:

function Telstra() {
  
  //Create folder Telstra_Bills, if it doesn't exist
   var folderName = 'Telstra_Invoices'
   
   //Control Folder
   var controlLabel = GmailApp.getUserLabelByName("attachmentsSavedtoDrive");
   var fileLabel = GmailApp.getUserLabelByName("Finance/Telstra");

  var folder = DriveApp.getFoldersByName(folderName);
    if (folder.hasNext()) {
    folder = folder.next();
  } else {
    folder = DriveApp.createFolder(folderName);
  }
  
  //search for the following in Gmail to create a list of threads
  var threads = GmailApp.search('from:*@online.telstra.com and has:attachment -label:attachmentsSavedtoDrive'); 
  
  //From Threads, get the first message in the thread, in this case the received message
  var msgs = GmailApp.getMessagesForThreads(threads);
  
  //Loop over each message, saving all attachements in given 
  for (var i = 0 ; i < msgs.length; i++) {
    for (var j = 0; j < msgs[i].length; j++) {
      var attachments = msgs[i][j].getAttachments();
      for (var k = 0; k < attachments.length; k++) {
        var fileName = msgs[i][j].getDate().toString();
        file = folder.createFile(attachments[k].copyBlob());
        file.setName(fileName.match(/\d{4}/) + " " + fileName.match(/\s\w{3}/) + " Telstra Invoices.pdf");
      }
   }
  }

  //loop through each thread and apply attachmentsSavedtoDrive, so that these files aren't indexed next time
  for (var x = 0; x < threads.length; x++) {
     controlLabel.addToThread(threads[x]);
     fileLabel.addToThread(threads[x]);
  }
}

Lines 5 – 8 (highlighted) are variables that you will need to change for your own particular bill or purpose.

Continuing on, we now need to save and run the script’s Main function(), when you run the script initially you will be presented with the following dialog box’s asking you to authorise the code to be run against your Google services.

If you allow the script to be run, you should see a new folder created in your Google Drive called Bills with the relevant bills saved and with the correct timestamp of the year-month they were received.

So the last thing you need to do is to add a trigger, the trigger is when you want the script to be run automatically without any user interaction.

Screen Shot 2015-12-04 at 10.02.04 AM

Clicking the timepiece icon will present the following dialogue:

Screen Shot 2015-12-04 at 10.02.20 AM

I run my script once a week, but you can run it however often you would like.

So there you have it, a script to save email attachments sent via Gmail to Google Drive automatically, hopefully you can use this snippet of code for your own workflows.

Advertisements

2 thoughts on “Save files to Google Drive automatically from Gmail”

  1. Hi
    I try to use same Script but for jpg attachments and I got error when run it that said “ReferenceError: “controlLabel” is not defined. (line 47, file “Code”)”

    here is my complete scrips after I edit it

    // Created by nashry
    function main() {
    // Variables that should be changed by the user
    var controlLabel = (“attachmentsSavedtoDrive”);
    var gmailLabel = (“0 NVR alarm”);
    var driveFolder = (“0 NVR alarm Test”);
    var fromEmail = (“nvrashry@gmail.com”);
    // Apply a suffix to the autogenerated filename, year-month-fileSuffix
    var fileSuffix = (“NVR alarm”);
    // Call functions to create labels and save jpg files
    createLabels(controlLabel);
    createLabels(gmailLabel);
    savejpgEmails(fromEmail, fileSuffix, controlLabel, gmailLabel, driveFolder);
    }

    function savejpgEmails(fromEmail, fileSuffix, controlLabel, gmailLabel, driveFolder){

    // Create Google Drive Folder
    var folder = DriveApp.getFoldersByName(driveFolder);
    if (folder.hasNext()) {
    folder = folder.next();
    } else {
    folder = DriveApp.createFolder(folderName);
    }

    //search for the following in Gmail to create a list of threads
    var threads = GmailApp.search(‘from:(‘+ fromEmail + ‘) has:attachment -label:’ + controlLabel);

    //From Threads, get the first message in the thread, in this case the received message
    var msgs = GmailApp.getMessagesForThreads(threads);

    //Loop over each message, saving all attachements in given
    for (var i = 0 ; i < msgs.length; i++) {
    for (var j = 0; j < msgs[i].length; j++) {
    var attachments = msgs[i][j].getAttachments();
    for (var k = 0; k < attachments.length; k++) {
    var fileName = msgs[i][j].getDate().toString();
    file = folder.createFile(attachments[k].copyBlob());
    file.setName(fileName.match(/\d{4}/) + " " + fileName.match(/\s\w{3}/) + " – " + fileSuffix + ".jpg");
    }
    }
    }}

    /* loop through each thread and apply attachmentsSavedtoDrive,
    and user defined gmail label, so that these files aren't indexed next time */

    var ctrlLabel = GmailApp.getUserLabelByName(controlLabel);
    var fileLabel = GmailApp.getUserLabelByName(gmailLabel);

    for (var x = 0; x < threads.length; x++) {
    ctrlLabel.addToThread(threads[x]);
    fileLabel.addToThread(threads[x]);}

    // Create Gmail Label – if the label doesn't already exist

    function createLabels(labelName) {

    if (GmailApp.getUserLabelByName(labelName) == null) {
    GmailApp.createLabel(labelName);
    }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s