Google apps script (Gmail) to label emails sent but not received reply to

25 Views Asked by At

I found this great script for automagically labelling emails that need a follow-up, slightly tweaked to show emails I have sent that haven't had a reply yet.

This currently works only for the current email account. I have a Gmail inbox that retrieves mail from 2 other email addresses, how might I also make this script apply to emails from them too?

https://www.gmass.co/blog/add-needs-reply-label

function labelNeedsReply() {

  // Check to see if the label exists and create it if the label does not exist

  var labelCheck = GmailApp.getUserLabelByName('Needs Reply');
  if (labelCheck == null) {
    GmailApp.createLabel('Needs Reply');
  }

  // Go through threads in inbox or messages elsewhere with the needs-reply label to see if they still need it

  var threads = GmailApp.search('in:inbox OR label:needs-reply');
  var currentUserEmail = Session.getActiveUser().getEmail();
  var needsReplyLabel = GmailApp.getUserLabelByName('Needs Reply');

  for (var i = 0; i < threads.length; i++) {
    var lastMessage = threads[i].getMessages()[threads[i].getMessageCount() - 1];
    var lastMessageFrom = lastMessage.getFrom();
    if (lastMessageFrom.indexOf(currentUserEmail) != -1) {
      needsReplyLabel.addToThread(threads[i]);
    }
    else  {
      needsReplyLabel.removeFromThread(threads[i]);
    }
  }  
}

This line evaluates only for the current Gmail account, I just need to add two other clauses somehow e.g. "[email protected]" or "[email protected]" (or any email from @domain.com).

if (lastMessageFrom.indexOf(currentUserEmail) != -1) {

Thanks!

I'm completely new to Google scripts so not sure what object/value I need :)

1

There are 1 best solutions below

2
ab.it.gcp On BEST ANSWER

Assuming you know which are the two email addresses and those are fixed.

I see two simple ways to do it :-

Solution 1: You can do it using Else If clause. Let's assume the other two email addresses are [email protected] and [email protected]. Modifiy your IF ELSE part of code in this way.

if (lastMessageFrom.indexOf(currentUserEmail) != -1) {
  needsReplyLabel.addToThread(threads[i]);
}
else if(lastMessageFrom.indexOf("[email protected]") != -1) {
  needsReplyLabel.addToThread(threads[i]);
}
else if(lastMessageFrom.indexOf("[email protected]") != -1) {
  needsReplyLabel.addToThread(threads[i]);
}
else  {
  needsReplyLabel.removeFromThread(threads[i]);
}

Solution2: Using OR "||" in the same IF condition if what you wan't to inside the IF is same for all three email addresses.

if (lastMessageFrom.indexOf(currentUserEmail) != -1 || lastMessageFrom.indexOf("[email protected]") != -1 || lastMessageFrom.indexOf("[email protected]") != -1) {
  needsReplyLabel.addToThread(threads[i]);
}
else  {
  needsReplyLabel.removeFromThread(threads[i]);
}