Reputation: 6918
I am trying to add Auto-Reply Email to my Google Contact Form. I created a function:
function sendAutoReply(e)
{
var myemail = "myemail";
var email = "";
var subject = "Re: ";
var message = "Thanks!";
try {
for(var field in e.namedValues) {
message += field + ' :: '+ e.namedValues[field].toString() + "\n\n";
if (field == 'Subject') {
subject += e.namedValues[field].toString();
}
if (field == 'Email') {
email = e.namedValues[field].toString();
}
}
MailApp.sendEmail(email, subject, message, {replyTo:myemail});
} catch(e){
MailApp.sendEmail(myemail, "Error in Auto replying to contact form submission. No reply was sent.", e.message);
}
}
I connected this function to the submit button. However when I press the the submit button I get an e-mail saying:
Failed to send e-mail: no recipient
How do I fix that?
Thanks in advance!
Upvotes: 0
Views: 2211
Reputation: 46802
You are make a few confusions about variables. field
is an integer that you use as an index so a condition like if (field == 'Email')
can never be true.
You have to get the key values from the form response object and use that to select values.
The other answer shows a possible way to achieve that by reading the spreadsheet but there is a more simple and direct way to do it directly from the object.
for(var k in e.namedValues){ keys.push(k) };
Logger.log("total " + keys.length + " keys: " + keys);
Then you can use that to check every response element. Returned values from text questions are string so you don't need to use toString()
.
The full code is shown below:
function formSubmit(e){
var keys = [];
var email = '';
var subject = '';
var message = '';
var myemail = Session.getActiveUser().getEmail();
for(var k in e.namedValues){
keys.push(k);
}
Logger.log("total " + keys.length + " keys: " + keys);
for(var field in keys) {
message += field + ' :: '+ e.namedValues[keys[field]] + "\n\n";
if (keys[field] == 'Subject') {
subject += e.namedValues[keys[field]];
}
if (keys[field] == 'Email') {
email = e.namedValues[keys[field]];
}
}
MailApp.sendEmail(email, subject, message, {replyTo:myemail});
}
btw, you don't need to hardcode your email address since GS has a method for it, the onFormSubmit
trigger being an installable trigger it runs as you and you can use Session.getActiveUser().getEmail()
.
Upvotes: 2
Reputation: 21091
See the links below for workarounds.
Example workaround code:
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
// Credit to Henrique Abreu for fixing the sort order
for(var i in headers) {
if (headers[i] = "Name") {
name = e.namedValues[headers[i]].toString();
}
if (headers[i] = "Email") {
email = e.namedValues[headers[i]].toString();
}
if (headers[i] = "Subject") {
subject = e.namedValues[headers[i]].toString();
}
if (headers[i] = "Message") {
message = e.namedValues[headers[i]].toString();
}
}
Upvotes: 3