Eric K.
Eric K.

Reputation: 131

Apps Script: How to Email Google Sheet file to Email Specified in HTML Service Input?

I am working to build in an HTML Service UI within my Google Sheets file that allows the user to key in the target recipient email address inside the pop-up dialog box within the HTML form. My code is currently not working effectively as an email is not being generated upon run.

JS Code:

    function openDialog() {
      var html = HtmlService.createHtmlOutputFromFile('Index');
      SpreadsheetApp.getUi()
      .showModalDialog(html, 'Email?');
    }

    function sendEmail() {
    var to = document.getElementbyID("emailInput");
      MailApp.sendEmail( {
        email: to,
        subject: "good morning",
     })
     }

HTML:

<html>
  <head>
    <base target="_top">
</head>
 <body>
      <form id="emailForm">
      Send to Email Address:<br> <input type="email" id="emailInput" 
      name="email" size="40"/><br>
      <button onClick="sendEmail()">Send</button>
      </form>
 </body>
</html>

Upvotes: 0

Views: 352

Answers (1)

Brian
Brian

Reputation: 4344

You can't call a server-side function from the client directly. You need to use the google.script.run API to communicate between the two. Try the following:

// Inside your Apps Script .gs code

// listen for an object sent from the HTML form
function sendEmail(formObj) {

  // Extract the email address submitted
  var to = formObj.email;

  // Send the email
  MailApp.sendEmail(to,"good morning", "The email body")
}
...
<body>
  <form id="emailForm">
      <p>Send to Email Address:</p>
      <br> 
      <input type="email" id="emailInput" name="email" size="40"/> <!-- "name" becomes the key in formObject -->
      <br>
      <input type="button" value="Send Email" onclick="google.script.run.sendEmail(this.parentNode)" /> <!-- google.script.run allows you to call server-side functions -->
      </form>
</body>
...

Upvotes: 1

Related Questions