1
votes

I created a form using google docs spreadsheet, and created a script that sends an email when the user fills the form:

function sendFormByEmail(e){

      var email = "AAA"; 
      var subject = "XXX";  
      var message = "";
      for(var field in e.namedValues)
        message += field + ' = '+ e.namedValues[field].toString() + "\n\n"; 

      var advancedArgs = {replyTo:e.namedValues['E-mail'].toString()};
      MailApp.sendEmail(email, subject, message, advancedArgs);


}

the script works, but when it sends the email, data is not sorted as the fields of the form.

how can I modify my script to sort the values ​​as they are in the Spreadsheet (form)?

1
javascript's for(...in...) executes in arbitrary order. Its documentation advice for not to use it if the order is relevant. – Alejandro Silvestri

1 Answers

2
votes

You could get the columns order from the spreadsheet. Something like this:

function sendFormByEmail(e){

      var email = "AAA"; 
      var subject = "XXX";  
      var message = "";
      var s = SpreadsheetApp.getActive().getSheetByName("Sheet1");
      var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
      for(var i in headers)
        message += headers[i] + ' = '+ e.namedValues[headers[i]].toString() + "\n\n"; 

      var advancedArgs = {replyTo:e.namedValues['E-mail'].toString()};
      MailApp.sendEmail(email, subject, message, advancedArgs);
}

Naturally, you have to change the sheet name Sheet1 to your actual sheet name. By the way, I have written a script that does this a lot more, maybe you want to check it out (if this is not only a programming exercise). It's called FormEmailer and you can find it in the Script Gallery and in its site.