Search code examples
javascriptgoogle-apps-scriptgoogle-sheetsgmailgoogle-forms

How to include an IF statement within a MailApp message?


I've created a Google Form and now creating a script to send automatic emails to sender with responses. The MailApp function is working just fine but I'm wondering if it is possible to include an IF statement within the message (htmlbody), so that the message changes depending on a variable's value.

I've included and IF statement, but I can't get the text to be included in the message.

// Email content
  var subject = FormName;
  var message = 

      "Hi,<br><br>"+

      "Thank you for submitting the Questionnaire<br><br>"+

      "Here are your responses:<br><br>"+

      "1. "+Question1+": "+Response1+"<br>"+
      "2. "+Question2+": "+Response2+"<br>"+
      "3. "+Question3+": "+Response3+"<br>"

   if(Response1 == "Yes")
{
"Since you answered yes to question 1, you need to do XYZ."
}

   MailApp.sendEmail(emailAddress, subject, message,{'htmlBody':message});
}

I've tried adding a + after the last question and response combo but it gives me a syntax error. The code, as above, omits to include "Since you answered yes, you need to do XYZ." in the email message which is not the desired outcome.


Solution

  • You can check for javascript operators, Especially for += because this operator takes the value of a variable and attach it with a new value.

    for example:

    var ex1 = "Hey";
    ex1 += " Friend";
    // ext1 = "Hey Friend";
    

    As you can see you can take this concept and use in your example. Then you going to have something like this

    // Email content
    var subject = FormName;
    var message = 
    
      "Hi,<br><br>"+
    
      "Thank you for submitting the Questionnaire<br><br>"+
    
      "Here are your responses:<br><br>"+
    
      "1. "+Question1+": "+Response1+"<br>"+
      "2. "+Question2+": "+Response2+"<br>"+
      "3. "+Question3+": "+Response3+"<br>";
    
     if(Response1 == "Yes")
      {
       message += "Since you answered yes to question 1, you need to do XYZ."
      }
    
      MailApp.sendEmail(emailAddress, subject, message,{'htmlBody':message});
    }
    

    I hope you catch idea.