通过电子邮件接收Google文档表单数据

时间:2012-12-20 16:00:05

标签: google-apps-script google-form

我使用过多个我在网络上找到的脚本,并遇到了同样的问题。我有几个谷歌文档表格,我需要通过电子邮件接收提交的数据(不仅仅是表格已提交的通知和相应的电子表格已更新)。这个脚本工作正常,但由于某种原因已停止:

function sendFormByEmail(e) 
{    
// Remember to replace XYZ with your own email address
var email = "info.wchs@gmail.com"; 

// Optional but change the following variable
// to have a custom subject for Google Docs emails
var subject = "Google Docs Form Submitted";  

// The variable e holds all the form values in an array.
// Loop through the array and append values to the body.

var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];    
var message = "";    

// Credit to Henrique Abreu for fixing the sort order

for(var i in headers)
  message += headers[i] + ' = '+ e.namedValues[headers[i]].toString() + "\n\n"; 

// This is the MailApp service of Google Apps Script
// that sends the email. You can also use GmailApp here.

MailApp.sendEmail(email, subject, message); 

// By Amit Agarwal - www.labnol.org
}

我收到错误:TypeError:无法从undefined中读取属性“namedValues”。 (第20行)

我什么都没改变,现在我找不到任何表单 - 提交给电子邮件脚本工作。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

您必须在那里进行一些调试,插入测试用例直到您解决问题,例如,line 20出现namedValues错误,请先检查e像这样访问它:

for(var i in headers)
    if (e && e.namedValues)
       message += headers[i] + ' = '+ e.namedValues[headers[i]].toString() + "\n\n"; 

答案 1 :(得分:0)

这可能是因为某些列中的空白数据。我建议删除/删除表单中所有现有的触发器,然后使用下面的代码(我参考代码作者:Amit Agarwal - www.labnol.org)

function Initialize() {

  var triggers = ScriptApp.getProjectTriggers();

  for(var i in triggers) {
    ScriptApp.deleteTrigger(triggers[i]);
  }

  ScriptApp.newTrigger("SendGoogleForm")
  .forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
  .onFormSubmit()
  .create();

}

function SendGoogleForm(e) 
{  
  // The variable e holds all the form values in an array.
  // Loop through the array and append values to the body.
  try 
  {      
    // You may replace this with another email address
    var email = "xyw@mail.com";

    // Optional but change the following variable
    // to have a custom subject for Google Form email notifications
    var subject = "Training Application Form Submitted";  

    var s = SpreadsheetApp.getActiveSheet();
    var columns = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];    
    var message = "";    

    // Only include form fields that are not blank
    for ( var i in columns ) 
    {
      var header = columns[i];
      if ( e.namedValues[header] && (e.namedValues[header] != "") ) 
      {
        message += header + ' :: '+ e.namedValues[header] + "\n\n"; 
      }
    }
    // This is the MailApp service of Google Apps Script
    // that sends the email. You can also use GmailApp for HTML Mail.

    MailApp.sendEmail(email, subject, message); 

  } 
  catch (e) 
  {
    Logger.log(e.toString());
  }

}

然后只需保存,运行Initilize功能,接受权限。