Google Apps 脚本 - 在发送电子邮件之前不替换变量

问题描述 投票:0回答:0

我有一个 Google Apps 脚本,它通过用 Google 表格中的数据替换 {{ }} 之间的变量在 Google 文档中生成一个文档。然后脚本将文档转换为 PDF 并通过电子邮件发送。然而,当我收到邮件时,变量并没有被替换。

当我在代码运行时检查我的 Google Drive 时,我可以看到文档已生成并且变量已被替换,但似乎需要一段时间,首先文档保存为变量未替换然后变量被替换.由于 pdf 实际上是在没有变量被替换的情况下发送的,我的猜测是电子邮件是在变量被替换之前发送的。

我试着在发送邮件前加了10秒的睡眠,但结果是一样的。 请注意,

console.log(body.getText());
log 正确记录了替换所有变量的文本。

如何确保在发送电子邮件之前替换变量?或者更简单地问,如果我的猜测是错误的,如何让这个脚本工作......

function generateInvitations() {
  // Open the Google Sheet
  var sheet = SpreadsheetApp.getActiveSheet();
  
  // Get the data range for the sheet
  var range = sheet.getDataRange();
  
  // Get the values in the range
  var values = range.getValues();
  
  // Get the template document
  var template = DriveApp.getFileById("1Fgve9aS6jGT3NbV6e_VcdkudDGvKv_cgUtg51DQus");
  
  // Loop through each row in the sheet
  for (var i = 1; i < values.length; i++) {
    // Get the values for the current row
    var firstName = values[i][0];
    var lastName = values[i][1];
    var meetingTime = values[i][2];
    var zoomLink = values[i][3];
    var email = values[i][4];

    // Get the template document
    var docId = DriveApp.getFileById("1Fgve9aS6jGT3NbV6e_VcdkudDGvKv_cgUtg51DQus").makeCopy("Invitation from xxxxxx").getId();
    var doc = DocumentApp.openById(docId)
    body = doc.getBody();
    // Replace placeholders with data from the sheet
    body.replaceText("{{first_name}}", firstName);
    body.replaceText("{{last_name}}", lastName);
    body.replaceText("{{meeting_time}}", meetingTime);
    body.replaceText("{{meeting_url}}", zoomLink);
    body.replaceText("{{today}}", new Date().toLocaleDateString());
   

    console.log(body.getText());
    pdf = doc.getAs("application/pdf");

  

    // Email the PDF file to the recipient
    GmailApp.sendEmail(email, "Zoom Meeting Invitation", "Please see attached invitation letter for your scheduled meeting", {
      attachments: [pdf],
      name: "Ecol Loco",
      subject: "Zoom Meeting Invitation"
    });
    
    // Delete the copy of the document
    DriveApp.getFileById(docId).setTrashed(true);
  }
}

email google-apps-script google-sheets automation google-docs
© www.soinside.com 2019 - 2024. All rights reserved.