Home > Back-end >  How do I refer to a Google form record when using HTML template in App Script?
How do I refer to a Google form record when using HTML template in App Script?

Time:01-18

Is it possible to add namedValues in a scriptlet when trying to use HTML template to send mails in App Script? If yes, how please, if no, how can I refer to each question on a Google form using scriptlets so that on form submission, the HTML template will evaluate() each record submitted? Below is the code

function sendEmail(e) {
var named_values = e.namedValues;
var name = named_values["Name"]
var timestamp = named_values["Timestamp"]
var subject = "Outlet "  timestamp  ""

const outlet = HtmlService.createTemplateFromFile('outlet');
outlet.named_values = named_values;
const message =  outlet.evaluate().getContent();

MailApp.sendEmail({
to: '[email protected]',
subject: subject,
htmlBody: message
});
}

...and below is the template code

<!DOCTYPE html>
<html>
<body>
<ul><li><b>Company:</b> <?= name ?></li>
<li><b>Loaction:</b> <?= timestamp ?></li></ul>
</body>
</html> 

I need the script to pick 'Name' and 'Timestamp' from the data submitted last from the Google form and send it to mail using the HTML template. Thanks.

CodePudding user response:

e.namedValues is an object, meaning it has properties, these properties are the form titles and their values are the answers people submits in the form.

The representation of the namedValues object on the google doc is the following:

{
 'First Name': ['Jane'],
 'Timestamp': ['6/7/2015 20:54:13'],
 'Last Name': ['Doe']
}

On your code you need to access the values of e.namedValues the specific title field you want to get. For example, in order to get the timeStamp, you do it the following way:

let named_values = e.namedValues;
let timeStamp = named_values.Timestamp;

In order to make you script work you should apply this concept to your code. A way of doing this is the following:

function sendEmail(e) {

 let named_values = e.namedValues;
 let name = named_values.Name;
 let timeStamp = named_values.Timestamp;
 let subject = "Outlet " timeStamp;

 let outlet = HtmlService.createTemplateFromFile('outlet');
 outlet.timeStamp = timeStamp;
 outlet.name = name;
 let message =  outlet.evaluate().getContent();

 MailApp.sendEmail({
  to: '[email protected]',
  subject: subject,
  htmlBody: message
 });
}

And the HTML should look like this:

<!DOCTYPE html>
<html>
 <body>
  <ul><li><b> timeStamp: </b> <?= timeStamp ?></li>
  <li><b> Name: </b> <?= name ?></li></ul>
 </body>
</html> 
  • Related