Sunday, September 11, 2011

"Star Drafts" script

This script is a productivity tool which I use to make me remember that I forgot to send an email or just started a draft message to note something down and did not act on it yet.

If it is set up properly, then it runs once a day, and stars your draft messages which do not have certain labels.

Here is how to install the script:
  • Create a new spreadsheet in Google Docs: "Create new" / "Spreadsheet".
  • Create a new script: "Tools" / "Script Manager" / "New...".
  • Copy-paste the following code into the editor:
    // Config
    var MAX_DRAFTS_PER_HOUR = 30;
    var LABELS_PREFIXES_TO_SKIP = ['Snooze/', 'Later/', 'NoAction'];
    var MOVE_TO_INBOX = false;
    
    function starDrafts() {
      var drafts = GmailApp.search("in:drafts", 0, MAX_DRAFTS_PER_HOUR);
      for (var i = 0; i < drafts.length; i++) {
        if(needsStarring(drafts[i])) {
          starThread(drafts[i]);
          if (MOVE_TO_INBOX) {
            drafts[i].moveToInbox();
          }
        }
      }
    }
    
    function needsStarring(thread) {
      // The thread does not need starring if it already has a starred message.
      if (thread.hasStarredMessages()) {
        return false;
      }
      // If the thread has a snooze label, we don't need to star it either.
      var labels = thread.getLabels();
      for (var i = 0; i < labels.length; i++) {
        if (labelNameToSkip(labels[i].getName())) {
          return false;
        }
      }
      // Ok, here is something to star.
      return true;
    }
          
    function labelNameToSkip(labelName) {
      for (var i = 0; i < LABELS_PREFIXES_TO_SKIP.length; i++) {
        var l = LABELS_PREFIXES_TO_SKIP[i];
        if (labelName.slice(0, l.length) == l) {
          return true;
        }
      }
      return false;
    }
    
    function starThread(thread) {
      var messages = thread.getMessages();
      messages[messages.length-1].star();
    }
    
    
  • Save the script with the Disk (save) icon.
  • Try to run it once. Select the "starDrafts" function in the "select function" dropdown, then press the "Run" (play) icon. You can check how it works if you have a draft message in Gmail.
  • At the first run, you have to authorize the script to access your Gmail account. Just click through it once and then try to run it again, next time it would work.
  • You can tweak the script if you want in the config section.
  • If you are happy how it works, set it up to run every day: "Triggers" / "Current script's triggers" / "Add a new trigger". Select "starDrafts", "time driven", "Day timer", "4am to 5am" (or any other unlikely time you are up).
Now you are ready, happy starring!

No comments:

Post a Comment