Google AppScript: Create Form using HTML, Publish Form as WebApp & Email Response

This article shows:

1) How to create Google Form using standalone HTML file
2) Email form submitted data to any particular email address

Create HTML file

We create a Form in a new HTML File.

  • Go to http://script.google.com
  • Go to File -> New -> Html file
  • Type the name of the file, e.g. form.html
  • Write the following code in it.

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
      function submitForm() {
        var name = document.getElementById('name').value;
        var email = document.getElementById('email').value;
        var comment = document.getElementById('comment').value;
        
        /**
         * First run submitData(name, email, comment) function of Code.gs
         * Then, run showMessage(value) function of this html file
         */
        google.script.run
              .withSuccessHandler(showMessage) // execute showMessage(value) function on success
              .submitData(name, email, comment); // call submitData(name, email, comment) function present in Code.gs file
      }
      
      function showMessage(value) {
        document.getElementById('message').innerHTML = value;
        document.getElementById('name').value = '';
        document.getElementById('email').value = '';
        document.getElementById('comment').value = '';
      }
    </script>
  </head>
  <body>
    <h2>Feedback Form</h2>
    <div id="message" style="color:green"></div>
    <input id="name" type="text" placeholder="Your Name"><p>
    <p><input id="email" type="email" placeholder="Your Email">
    <textarea id="comment" rows="10" cols="40"></textarea>
    <button onclick="submitForm(); return false;">Submit</button></p>    
  </body>
</html>

There is a Code.gs file by default in the script editor. Write the following code in it.

Note that we need doGet(e) function to publish project as WebApp. This function uses HTMLService to return HTML Output using the form.html file we created. We can also set the title of the page from here.


function doGet(e) {
  return HtmlService
    .createHtmlOutputFromFile('form.html')
    .setTitle("Simple HTML Form Example");
}

function submitData(name, email, comment) {
  var subject = 'New Feedback';
  var body = 'Name: ' + name + '<br> Email: ' + email + '<br> Comment: ' + comment;
  var to = 'your.name@example.com'; // EMAIL ADDRESS WHERE THE FEEDBACK EMAIL IS SENT
  MailApp.sendEmail({
      to: to,
      subject: subject,
      htmlBody: body
    }); 
  
  return 'Feedback Sent!';
}

About publishing your script as web app is given here: https://developers.google.com/apps-script/guides/web

Hope this helps. Thanks.