You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Sheets脚本:GmailApp.sendEmail报email未定义错误排查

解决Google Apps Script中"ReferenceError: email is not defined"的问题

这个错误的原因很直白:你调用GmailApp.sendEmail()时用到的email变量完全没被定义过!问题出在用户输入的处理环节,我来帮你一步步修正:

问题根源

你用ui.prompt()弹出了输入邮箱的窗口,但既没有提取用户输入的文本内容,也没有把它赋值给email变量;而且当前用的ui.ButtonSet.YES_NO按钮组也不适合输入场景——YES/NO是用来做二元选择的,不是配合文本输入的确认按钮。

具体修改步骤

  1. 替换Prompt按钮组:把ui.ButtonSet.YES_NO改成ui.ButtonSet.OK_CANCEL,这是输入类弹窗的标准按钮组合。
  2. 提取并赋值邮箱地址:获取用户响应后,先判断是否点击了OK,再用response.getResponseText()提取输入的邮箱字符串,赋值给email变量。
  3. 增加基础错误处理:如果用户点击取消或输入空内容,直接退出函数,避免后续代码报错。
  4. 补全PDF请求的授权头:之前的UrlFetchApp.fetch()可能会因为权限问题无法获取PDF,需要添加OAuth Token授权。

修改后的完整subFunction1函数

function subFunction1() {
  // Send the PDF of the spreadsheet to this email address
  var ui = SpreadsheetApp.getUi();
  // 替换为适合输入场景的OK_CANCEL按钮组
  var response = ui.prompt('Please input email address', ui.ButtonSet.OK_CANCEL);

  // 判断用户是否确认输入
  if (response.getSelectedButton() !== ui.Button.OK) {
    // 用户取消操作,直接退出函数
    return;
  }

  // 获取用户输入的邮箱地址并去除首尾空格
  var email = response.getResponseText().trim();
  
  // 简单校验:避免空输入
  if (!email) {
    ui.alert('请输入有效的邮箱地址!');
    return;
  }

  // Gets the URL of the currently active spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var url = ss.getUrl();
  url = url.replace(/edit$/,'');

  // Subject of email message
  var subject = "Geico Tracker Report - " + Utilities.formatDate(new Date(), "GMT", "dd-MMM-yyyy");

  // Body of email message
  var body = "\nDaily Geico Tracker Report.\n \n";

  /* Specify PDF export parameters */
  var url_ext = 'export?exportFormat=pdf' // export as pdf
  + '&format=pdf' // export as pdf
  + '&size=letter' // paper size
  + '&portrait=false' // page orientation
  + '&fitw=true' // fits width; false for actual size
  + '&sheetnames=false' // hide optional headers and footers
  + '&printtitle=false' // hide optional headers and footers
  + '&pagenumbers=false' // hide page numbers
  + '&gridlines=false' // hide gridlines
  + '&fzr=false' // do not repeat row headers
  + '&gid=0'; // the sheet's Id

  var token = ScriptApp.getOAuthToken();

  // Convert worksheet to PDF:添加授权头避免权限问题
  var pdfResponse = UrlFetchApp.fetch(url + url_ext, {
    headers: {'Authorization': 'Bearer ' + token}
  });
  // Convert the response to a blob
  var file = pdfResponse.getBlob().setName('Geico Tracker.pdf');

  // Send the email with the PDF attachment.
  if (MailApp.getRemainingDailyQuota() > 0)
    GmailApp.sendEmail(email, subject, body, {attachments:[file]});
}

现在测试一下,用户输入邮箱后就能正常发送PDF报告了。

内容的提问来源于stack exchange,提问作者Shane Nordman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:04:34