Search code examples
google-apps-scriptgmail

Gmail script: Filters, stars and gmailApp.search, but some emails fall through the cracks


FACTS:

I have a script that searches inbox for unread email, and anything that isn't starred are removed from inbox and applied label. There are filters in place to label certain email addys as starred.

GOAL:

To move everything from inbox to a folder that is not relevant. Except the items that are starred. Also have a method that allows for manually dragging back to inbox and make sure they stay there.

PROBLEM:

Most all emails are processed as needed. Only some of the starred emails are still getting the script applied to, and are thus moved from inbox and labeled "newLabel"

Thanks for your help. If there is a better way to accomplish the same thing, I'll switch it up.

/**
* Get the label, or create it if it doesn't exist
 */
function _getAssistLabel() {
  /**
   * If you'd like your label to say something different, modify it here
   */
  var assist_label_text = "newLabel";
 /** 
  *Get the label
  */
  var label = GmailApp.getUserLabelByName(assist_label_text);
 /**
  *if Label isn't found, create it
  */
  if (label == null) {
    var label = GmailApp.createLabel(assist_label_text);
  }

  return label;
}


/**
 * Search for starred, unread messages in the inbox 
 * apply a label 
 * then archive message (remove from inbox)
 */
function addAssistLabels() {
  var label = _getAssistLabel();

 /**
  * If a message is unread, and is in the inbox and is NOT starred...
  */
  var threads = GmailApp.search('is:unread in:inbox -label:Starred  -label:Sales');

 /**  ..then label the message and remove it from the inbox.
  * This will make the message show up in the "folder"
  */
  for (var i = 0; i < threads.length; i++) {
    label.addToThread(threads[i]);
      threads[i].moveToArchive();
  }
}






/**  
  * Force threads with starred emails and any with label "forBoss" to return to inbox
  */

function forceInbox() {
  var label = GmailApp.getUserLabelByName("newLabel"); 
  var threads = GmailApp.search('label: newLabel label:forBoss');

  for (var i = 0; i < threads.length; i++) {
   label.removeFromThread(threads[i]);
      threads[i].moveToInbox();
  }
}

I used this link for part of this: Gmail Script: search then move to inbox, remove label


Solution

  • Your first thread is not picking up mails correctly.

    var threads = GmailApp.search('is:unread in:inbox -label:Starred -label:Sales');
    

    You indicated that

    I have a standalone script that searches inbox for unread email, and anything that isn't starred are removed from inbox and applied label.

    GmailApp.search() should only use is:unread in:inbox for what you want. Also, using the search query parameter label: shouldn't have a dash before it.

    Check out the documentation for the list of accepted search query parameters here