Search code examples
google-apps-scriptgmailgmail-api

How to handle & process new Gmail messages with the same subject line (and sender) as old messages?


In Gmail, I have two filters for incoming email:

  • Filter 1 - When an email arrives with a specific subject line (we'll call it "Subject 1"), it applies a Label to the email.
  • Filter 2 - When an email arrives with a different specific subject ("Subject 2"), it applies the same Label (as "Subject 1"'s label) to the email.

The sender of ALL of these emails is the same sender. The emails are order confirmations. As such, within the "Subject 1" emails (same with "Subject 2"), the email format is the same, just different customer names, etc. The unique identifier is the order # across all emails.

Then I have a Google Apps Script script that runs every x minutes, looking to see if there are any emails with the label. Here is part of the script:

var gmailLabelName = "GmailLabelIGaveTheEmails"
var gmailLabelObject = GmailApp.getUserLabelByName(gmailLabelName);
var threads = gmailLabelObject.getThreads();

for (var i = 0; i < threads.length; i++) {
  messages = threads[i].getMessages();

  for (var j = 0;  j < messages.length;  j++) {
    message = messages[j];
    emailText = message.getPlainBody();

    --- Process the order ---

The problem is that when you label an incoming email, Gmail also effectively labels ALL emails from the past (1 day?) that have that same subject.

So, when you loop through the messages (j loop above), you get not only the new order that just was placed / the new email that just arrived, you also get all of the recent already-processed orders/emails as well.

What I have been doing is keeping track of which order #s have already been processed. If the message (variable is shown above) order # already has been processed, then I use "continue" to go to the next message [j].

However, this is very inefficient - to have to look at every email, look through your list of order #s already processed, and then process if it hasn't already been processed.

This all stems from the fact that Gmail groups the same subject line emails together into a thread, so that when you label a new email, it therefore effectively labels them all.

Does anyone know of a better way of doing this so that only the brand new order emails/orders get processed without having to look at the older ones and determine if they have already been processed?


Solution

  • Oleg Valter had the right solution. See his comments above, below my question.

    When an email arrives, through a Gmail filter, I now not only apply a label it, but also star it.

    In the code shown above, where it says --- Process the order ---

    I then have the following code:

    if (!message.isStarred()) {
      continue;
    }
    

    Then at the bottom of the script, before looping back to the top and getting the next message:

    message.unstar();