1
votes

DISCLAIMER: I'm new to Stack Overflow and I'm not a developer.

I work in IT and we are currently trying to take all of our paper/electronic forms and turn them into Google Forms. I am currently trying to write a script (see below) that will send an email to a specific person based on one of the answers. The good news is that the script works (woot!).

The problem that I'm having is that I get 2 - 3 of the exact email when I test it. It's especially bad in with my gmail account.

If the below code looks atrocious, I'm open to suggestions! Thanks in advance for the help!!

function myFunction() {
var form = FormApp.getActiveForm()

var formResponses = form.getResponses();

for (var i = 0; i < formResponses.length; i++) {
 var formResponse = formResponses[i];
 var itemResponses = formResponse.getItemResponses();
 var work = itemResponses[3];
 var problem = itemResponses[2].getResponse();
 var location = itemResponses[4].getResponse();
 var name = itemResponses[0].getResponse()
 var sheetsLink = docs.google.com/sheetid
}

if (work.getResponse() === "Food Services") {
  MailApp.sendEmail('[email protected]', 'Kitchen Maintenance', name + ' has a problem with ' + problem + ' in the kitchen at ' + location + '.  More information for this request can be found at: ' + sheetsLink + '.');                    

} else {
  MailApp.sendEmail('mymail@schoolacct', 'Maintenance', name + ' has a problem with ' + problem + ' at ' + location + '.  More information for this request can be found at: ' + sheetsLink + '.');
 } 
}
1
If you have multiple editors in the Form, duplicate emails will be sent. You must remove all editors to the Form. This can be done through Drive or in the Form. There is an Add-on that will send emails depending upon a conditional test. Link to Google Form Add-onAlan Wells
Couple of questions? Do you manually run this function or have you trigger setup for it to run when some one submits the form? Secondly your for loop doesn't do anything except give you the response from the last form entry, is that behaviour you are looking for?Jack Brown
@SandyGood, your suggestion worked. Thanks!Mitch Toler
@JagannathanAlagurajan, the function is run with an "on submit" trigger. I just use the for loop to put the answers in an array so I can easily create variables from any of the answers. I don't know if that's the proper way to create variables, but it works for me. :)Mitch Toler

1 Answers

0
votes

It might be easier for you to get the form responses saved in a spreadsheet then tie the apps script to the spreadsheet with an on form submit trigger. This will allow you to have a record of all form responses in the spreadsheet and if anything goes wrong, you can always recheck. On the multiple emails sent, the multiple editors is the thing to check.