Home > Software engineering >  Google App Script Error - Cannot read property 'response' of undefined and Failed to send
Google App Script Error - Cannot read property 'response' of undefined and Failed to send

Time:11-21

I have a simple script that executes once form submit. It is a simple test script applied html for email.

function sendEmail(e) {
  
  //response
  //getRespondentEmail()
  var html = HtmlService.createTemplateFromFile("email.html");
  var htmlText = html.getCode();
  
  var emailTo = e.response.getRespondentEmail();
  var subject = "Thanks for participating";
  var textBody = "This email requries HTML support, please maek sure you open with a client taht support.";
  var options = { htmlBody: htmlText };
  
  
  if(emailTo !== undefined){
    GmailApp.sendEmail(emailTo,subject,textBody,options);
  //(recipient, subject, body, options)
  }
}

But it always noticed TypeError: Cannot read property 'response' of undefined.

TypeError: Cannot read property 'response' of undefined (line 8, file "Code")

either the respose from my host email said 'Failed to send email: no recipient' enter image description here

I do not know why it does not work, but I see someone successfully applied through above google app script.

CodePudding user response:

'e' undefined:

TypeError: Cannot read property 'response' of undefined

This error means the parameter e is undefined. Which means this function is not executing via trigger.

When functions are called by triggers, the function is passed an event object as argument. But in other contexts (for example, when executing this manually, from the editor) this argument is not passed.

Therefore, this function is supposed to get executed automatically when users submit the form. Don't try to execute it manually from the editor, if you are using e inside the function.

No recipient:

Failed to send email: no recipient

This means emailTo is not defined, which means getRespondentEmail() is not returning anything.

This could happen for two reasons:

  • Either a form response was created by the script, but not submitted. Since this is getting executed via a form submission trigger, though, it's not your case.
  • The other reason, which is most likely what's going here, is that you didn't enable the option to collect the email addresses. You can do that programmatically, by calling Form.setCollectEmail(collect), or through the UI, by following the guide in Collect respondents' email addresses.

Related:

  • Related