【问题标题】:how to pass parameters to a triggered function in google-app-script如何将参数传递给 google-app-script 中的触发函数
【发布时间】:2017-09-21 01:33:03
【问题描述】:

我有一组收件人和必须发送邮件的预定时间。我很想知道是否有办法创建一个触发器,我可以将这些参数(收件人)传递给它

function send_mail(recipients)
{
  var id = DocumentApp.getActiveDocument().getId();
  for(i=0;i<recipients.length;i++)
 {
   var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+id+"&exportFormat=html";
   var param = 
    {
      method      : "get",
      headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
      muteHttpExceptions:true,
    };
   var html = UrlFetchApp.fetch(url,param).getContentText();
   var raw = Utilities.base64EncodeWebSafe("Subject: Test\r\n" +
                                        "To:" +recipients[i]+"\r\n" +
                                        "Content-Type: text/html; charset=UTF-8\r\n\r\n" +
                                        html+"\r\n\r\n");
   var message = Gmail.newMessage();
   message.raw = raw;
   var sentMsg = Gmail.Users.Messages.send(message, recipients[i]);
 }
}
function schedule_mail(recipients,schedule)
{
  ScriptApp.newTrigger("send_mail").timeBased().at(schedule).create();
}

如果无法将参数传递给基于时间的触发器,那么还有其他解决方法吗?

【问题讨论】:

  • 我认为您不能将参数传递给触发器。你有没有考虑使用PropertiesService
  • 如果我将变量存储在 PropertiesService 中如何管理触发器,例如我应该何时创建触发器以及如何在执行后删除触发器@Pierre-MarieRichard
  • 您创建触发器并将变量存储在 PropertiesService 中。然后,您可以在函数中添加一段代码以从 PropertiesService 中取回变量。函数完成后,清除触发器: function delTrigger(){ var triggers = ScriptApp.getProjectTriggers(); for (var i = 0; i

标签: google-apps-script google-docs gmail-api


【解决方案1】:

没有直接的方法可以做到这一点。但这里有一个解决方法。 注意:这只是说明而不是实际代码。在代码中检查我的 cmets。

function send_mail(recipients)
{
  ............
  ............
}

function triggerHandler(e){
  var triggerId = e.triggerUid;
  //Iterate through all triggers and get the matching triggerId and corresponding recipient
  send_mail(recipient);
}

function schedule_mail(recipients,schedule)
{
  var trigger = ScriptApp.newTrigger("triggerHandler").timeBased().at(schedule).create();
  var ID = trigger.getUniqueId();
  //Save this ID against the recipient details in user properties
}

【讨论】:

  • 感谢@Hari Das 的工作。效果很好。
  • 对于像我这样想知道“e”是什么的人,它不是函数参数吗?在此处查看“事件对象”:developers.google.com/apps-script/guides/triggers/events。要点如下: >当触发器触发时,Apps 脚本将事件对象作为参数传递给函数,通常称为 e。事件对象包含有关导致触发器触发的上下文的信息。
猜你喜欢
  • 2015-12-18
  • 2019-07-16
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-24
  • 2011-07-14
相关资源
最近更新 更多