Search code examples
javascriptgoogle-apps-scriptweb-applications

Error in Google Apps Script when HTML form input field is empty


My Google Apps Script receives data from an HTML form, then sends an email confirmation to a customer. It gets the email address from input type=email, and if this input field is left blank, the script produces an error.

Here is the relevant part of my Google Apps Script:

function doPost(e) {
  var email = e.parameter.Email;
  MailApp.sendEmail({
    to: email,
    subject: "Submission Received",
    body: "We have received your submission. Thank you.",
    htmlBody: HtmlService.createHtmlOutputFromFile(
      "Confirmation"
    ).getContent()
  });
}

How can I solve this so that when my referenced form input field is empty my script doesn’t produce an error?

(I know that one way to solve this is to put required attribite on the input, but the field is optional, so that doesn’t fix my problem.)


Solution

    • You don't want to occur an error when Email is not inputted.

    If my understanding is correct, how about the following modification? Please think of this as just one of several answers.

    Modified script:

    function doPost(e) {
      if ("Email" in e.parameter && e.parameter.Email != "") { // Added
        var email = e.parameter.Email;
        MailApp.sendEmail({
          to: email,
          subject: "Submission Received",
          body: "We have received your submission. Thank you.",
          htmlBody: HtmlService.createHtmlOutputFromFile(
            "Confirmation"
          ).getContent()
        });
      } else { // Added
        // If "Email" is not inputted, for example, you can do something here.
      }
    }
    
    • From your question, Email is inputted to the type of email. So I thought that it is not required to confirm whether the value of Email is the email.

    If I misunderstood your question and this was not the result you want, I apologize.