0

I get an automated email when an event occurs, but need to be notified if it isn't received. It's easy to overlook something that doesn't happen.

Here's what I have, but the var c remains 0 when script ends (I'm expecting it to not be 0 if email is found, and be 0 and send email if subject is not found.

function CheckForSubjectInEmail() {

var threads = GmailApp.search("in:Inbox");  
var subject = "Testing";
var c = 0;
for (var i = 0; i < threads.length; i++) {

  var messages = threads[i].getMessages();

  for (var m = 0; m < messages.length; m++) {
    var msg = messages[m].getSubject();

    // Does the message subject match?
    if (msg = subject) {
    c = c++
    }

 if (c = 0) {  
  MailApp.sendEmail("email@domain.com",
                   "Important email not received.",
                   "The Testing email has not yet been received.");    
    }   
   }
  }  
 }

Cheers, Dave

Dave
  • 13
  • 3

2 Answers2

2

You've got a few problems - two of them work together to explain your observation.

First, you've used assignment (=) where you meant to test for equality (== or ===). The way your comparisons are written, you're assigning subject to msg, and 0 to c, and then testing their "truthiness". (Turns out msg is always "truthy" unless it's null or empty, while 'c' is always "falsy", because it's always 0.) You should instead have:

if (msg == subject) {
  ...

and

if (c == 0) {
  ...

If you're wondering about which equality operator to use, see the ridiculously popular question Which equals operator (== vs ===) should be used in JavaScript comparisons?

You should be able to see the second problem clearer if you format your code properly. I personally like jsbeautifier.org for this. Here's how the code cleans up:

function CheckForSubjectInEmail() {

  var threads = GmailApp.search("in:Inbox");
  var subject = "Testing";
  var c = 0;
  for (var i = 0; i < threads.length; i++) {

    var messages = threads[i].getMessages();

    for (var m = 0; m < messages.length; m++) {
      var msg = messages[m].getSubject();

      // Does the message subject match?
      if (msg == subject) {
        c = c++
      }

      if (c == 0) {
        MailApp.sendEmail("email@domain.com",
          "Important email not received.",
          "The Testing email has not yet been received.");
      }
    }
  }
}

Do you see it? The if (c == 0) comparison isn't at the "end" of the function, rather it's inside the loop, so if ANY message doesn't have a matching subject it will fire off an error message. (That's not a normal situation, but since subjects can be edited on emails within a thread, it's possible.) You should move that outside of the loop.

Community
  • 1
  • 1
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
0

A boolean check uses the == syntax. it should read

if(c == 0){..}

and

if(msg == subject)

also I saw c = c++; You could simple express it c++;

Spencer Easton
  • 5,642
  • 1
  • 16
  • 25