Search code examples
google-apps-scriptgoogle-sheetsgmail-api

Google script - Gmail.App, email body with if statement


I am trying to create a tour confirmation email from a Google spreadsheet, based on some conditions.

I have created a variable to add if the statement and id don't show in the email.

var mailContent = 
'Hello '+customerName +', thank you for the booking.<br><br>'+ "You have booked: "+tourName +" - "+tourType 
+ "<br><br><b>Tour Details:</b> " 
+"<br>Travel Date: "+tourDate
 if (tourLang !== "--------"){
       +"<br>Language: "+tourLang 
  }
+"<br>Pickup adress: "+tourPickup
 if (tourTime !== ""){
    +"<br>Pickup Time: "+tourTime
 }
+"<br>Number of Participants: "+tourPax

    +"<br><br> <b>Contact Details:  </b>"
    +"<br> Main customer: "+customerName
    +"<br> Phone: "+customerPhone
    if (customerOtherNames !== ""){
    +"<br> Names of all Participants: "+customerOtherNames
    }  
GmailApp.sendEmail(
customerEmail,
'Booking Confirmation '+voucherRealNumber,
mailContent,
{
  htmlBody: mailContent,     
  attachments: [createPDF],
  bcc: "test@test.com"
});

And the email looks like this:

"Hello XYZ, thank you for the booking. You have booked: Some - Tour Tour Details: Travel Date: Fri Dec 24 2021"

It stops on the first if statement. In this particular example the if statements == true, so it supposed to add the content of it so as continue the script.


Solution

  • You need to specify the variable you are using when appending inside the if statements. You haven't specified what variable the string is to be appended that's why it didn't show the expected output. See sample script below:

    Script:

      customerName = 'XYZ';
      tourName = 'Some';
      tourType = 'Tour';
      tourDate = 'Fri Dec 24 2021';
      tourLang = 'lang';
      tourTime = 'time';
      customerOtherNames = 'other names';
      tourPickup = 'pickup';
      tourPax = 'pax';
      customerPhone = 'phone';
    
      var mailContent =
        'Hello ' + customerName + ', thank you for the booking.<br><br>' + "You have booked: " + tourName + " - " + tourType
        + "<br><br><b>Tour Details:</b> "
        + "<br>Travel Date: " + tourDate
    
      if (tourLang !== "--------") {
        mailContent += "<br>Language: " + tourLang
      }
      
      mailContent += "<br>Pickup adress: " + tourPickup
    
      if (tourTime !== "") {
        mailContent += "<br>Pickup Time: " + tourTime
      }
    
      mailContent += "<br>Number of Participants: " + tourPax
        + "<br><br> <b>Contact Details:  </b>"
        + "<br> Main customer: " + customerName
        + "<br> Phone: " + customerPhone
    
      if (customerOtherNames !== "") {
        mailContent += "<br> Names of all Participants: " + customerOtherNames
      }
    
      Logger.log(mailContent);
    
    

    Output:

    output