You need to enable JavaScript to run this app. Google Apps Script调用getFilesByName偶现iterator已到末尾错误求助
优惠活动
大模型
产品
解决方案
定价
更多

Google Apps Script调用getFilesByName偶现iterator已到末尾错误求助

问题根因

  • 首要原因:Google Drive存在最终一致性延迟,新创建/上传的文件完成写入后,元数据索引不会实时更新,几秒内通过getFilesByName这类搜索接口可能无法检索到文件,属于Drive API的固有特性
  • 次要排查点:直接取表格最后一行的逻辑如果遇到并发表单提交,可能出现行号不匹配的问题,但你确认目标文件存在时仍报错,核心原因仍是索引延迟。

修复方案

修改获取PDF文件的逻辑,增加存在性判断和重试机制,避免直接调用next()抛异常:

//get the email template from google doc using the url of the file
var templateUrl = 'https://docs.google.com/document/d/1I4igdjEYeV46fGbo_MiMClrmJGUrN73ZByCvNBvIVxM/edit'

//Get that template
var template = DocumentApp.openByUrl(templateUrl)

//Extract the text in the body of the document
var text = template.getBody().getText()

//Define Variables from Sheet
var sSheet = SpreadsheetApp.openById("1jGQMmLykfnL7t6JNQ7ZzRSlvEDQBJwvqMxCRpNYtZ20");
var FormResponses = sSheet.getSheetByName("Form Responses");
var LastRowRes = FormResponses.getRange(["A1:A"]).getValues().filter(String).length;

var Firstname= FormResponses.getRange(LastRowRes,3).getValue();
var Lastname = FormResponses.getRange(LastRowRes, 4).getDisplayValue();
var Id = FormResponses.getRange(LastRowRes, 5).getDisplayValue();
var Recipient = FormResponses.getRange(LastRowRes,2).getValue();
var Subject = "Participation"
  
var PDFfolder = DriveApp.getFolderById("1Y9fhQQjbfBu83Vq1UbvZFB3Cdub9dFGI");
// 以下为修改的核心逻辑
var fileName = Id+" "+Lastname+", "+Firstname+" - Participation";
var maxRetry = 5; // 最多重试5次
var retryInterval = 1000; // 每次间隔1秒
var PDF_Participation = null;

for (var i = 0; i < maxRetry; i++) {
  var fileIterator = PDFfolder.getFilesByName(fileName);
  if (fileIterator.hasNext()) {
    PDF_Participation = fileIterator.next();
    break;
  }
  Utilities.sleep(retryInterval);
}

// 兜底校验
if (!PDF_Participation) {
  throw new Error("未找到目标文件:" + fileName);
}

//send mails
var emailBody = text.replace('{Firstname}', Firstname)

MailApp.sendEmail(Recipient, Subject, emailBody, {
  noReply: true,
  name: "Organization Team",
  replyTo: "example@google.com",
  attachments: [PDF_Participation.getAs(MimeType.PDF)]
  })
}

可选优化

如果两个脚本都是绑定表单提交触发,可以把生成PDF和发邮件的逻辑合并到同一个脚本里,生成PDF后直接拿到文件ID,不需要再通过文件名搜索,从根源上避免这个问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 09:09:00