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

google.script.run无法调用sendFileToEmail()函数的问题排查求助

google.script.run无法调用sendFileToEmail()函数的问题排查求助

我正在开发一个Google Apps Script项目,用来通过邮件发送测验相关的文件。奇怪的是,sendFileToEmail()函数在Apps Script编辑器里直接运行时完全正常,但通过HTML界面的google.script.run调用时,却完全没执行,根本没反应。

HTML界面代码

<button id="reStartButton" disabled="disabled" onclick="start1()">Send files to your email</button>

<script>
  try {
    var newVal = await new Promise((resolve, reject) => {
      google.script.run
        .withSuccessHandler(resolve)
        .withFailureHandler(reject) // 新增reject处理错误
        .sendFileToEmail();
    });
    console.log("Email sent successfully:", newVal);
    loinhac2.innerHTML = "Đề thi và đáp án đã được gửi đến email của bạn, hãy lấy chúng về và in ra giấy.";
  } catch (error) {
    console.error("Error sending email:", error);
    alert("An error occurred while sending the email. Please try again later.");
  }
</script>

Apps Script后端代码

function sendFileToEmail() {
  Logger.log("Function called.");
  var myEmail = Session.getActiveUser().getEmail();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var solId = ss.getSheetByName('title').getRange('A77').getValue();
  var sol = UrlFetchApp.fetch(`https://docs.google.com/spreadsheets/d/${solId}/export?format=xlsx&id=${solId}`, {
    method: "GET",
    headers: { "authorization": "Bearer " + ScriptApp.getOAuthToken() }
  }).getBlob();
  MailApp.sendEmail(myEmail, 'Quiz', 'See attached.', { attachments: [sol] });
}

目前遇到的问题

我特意在后端函数里加了Logger.log("Function called.")日志,但不管怎么点击HTML按钮,这条日志都从未出现在编辑器的日志面板里——这说明sendFileToEmail()函数根本没被调用到。但只要我在Apps Script编辑器里直接运行这个函数,它就能正常发送邮件,完全没问题。

已配置的OAuth权限

我的appsscript.json里已经添加了以下权限:

"oauthScopes": [
  "https://www.googleapis.com/auth/spreadsheets",
  "https://www.googleapis.com/auth/drive",
  "https://www.googleapis.com/auth/script.send_mail",
  "https://www.googleapis.com/auth/gmail.send"
]

有没有大佬能帮我分析下,到底是什么原因导致google.script.run没法调用这个函数?应该怎么解决这个问题?


备注:内容来源于stack exchange,提问作者Lê Phong Nguyễn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 12:24:34