【问题标题】:Converting local GmailApp.sendEmail (GAS) to Web App script将本地 GmailApp.sendEmail (GAS) 转换为 Web App 脚本
【发布时间】:2019-11-19 16:31:17
【问题描述】:

当我点击工作簿中的按钮时,我设置了一个有效的 Google 应用程序脚本以发送自动电子邮件 (GmailApp.sendEmail)。

但是,我正在尝试将脚本转换为 Google Web App,以便我组织内的任何用户都有权运行脚本并通过按下按钮触发自动电子邮件。

我对如何从 getui() 调整本地代码有点迷茫。我知道我需要添加一个诸如 doget(e) 之类的函数并部署为 Web 应用程序,但我对 Web 应用程序的了解不够,无法编辑代码。

这是我的本地工作代码:

// This constant is written in column E for rows for which an email
// has been sent successfully.
var EMAIL_SENT = 'E-MAIL SENT';
var ui = SpreadsheetApp.getUi();

/**
 * Sends non-duplicate emails with data from the current spreadsheet.
 */
function email(){
  var rng = SpreadsheetApp.getActiveSheet().getRange('A2:F2')
  var checkvalue = SpreadsheetApp.getActiveSheet().getRange('E2').getValue();
  var email = rng.getValues()[0];
  var data = rng.getValues();
  for (var i = 0; i < data.length; ++i) {
  var row = data[i];
  var emailSent = checkvalue; // emailSent confirmation cell
  if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
  GmailApp.sendEmail(email[0], email[1], email[2]);
  SpreadsheetApp.getActiveSheet().getRange('E2').setValue(EMAIL_SENT);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
  }
 }
}

非常感谢任何帮助!

【问题讨论】:

    标签: google-apps-script google-sheets web-applications


    【解决方案1】:

    试试这个:

    代码.gs:

    function email(){
      var ss=SpreadsheetApp.openById("SpreadsheetId");//need spreadsheet id
      var sh=ss.getSheetByName("SheetName");//when you open up a spreadsheet like this the active sheet is alway ss.getSheets()[0] the left most sheet so you should user get sheet by name instead.
      var rg=sh.getRange('A2:F2');
      var email=rg.getValues()[0];
      if (email[4]!="EMAIL_SENT") { 
      GmailApp.sendEmail(email[0], email[1], email[2]);
      sh.getRange('E2').setValue("EMAIL_SENT");
      }
    }
    
    function doGet() {
      return HtmlService.createHtmlOutputFromFile('html filename without extension');
    }
    

    html:

    <!DOCTYPE html>
    <html>
      <head>
      <base target="_top">
      </head>
    <body>
      <input type="button" value="Send" onClick="google.script.run.email();" />
    </body>
    </html>
    

    Client to Server Communication

    【讨论】:

    • 工作就像一个魅力。谢谢,库珀。非常感谢您清理代码并包括 html!
    • 我只是注意到我的想法出现了一个小故障。我将如何编辑 openById("SpreadsheetId") 行以使脚本主动提取 ID 而不是硬编码?我的问题是用户将保存此主模板的副本并进行工作细节编辑,然后使用上面的脚本通过电子邮件发送出去。但是,目前保存的副本会导致电子邮件从原始主模板发送......我相信因为“SpreadsheetId”是静态的。
    • 我经常将类似的东西存储在一个名为 Globals 的工作表中,其中存储了一个键值对表。然后我无法使用getGlobals('SpreadsheetID') 检索它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 2021-04-15
    相关资源
    最近更新 更多