Search code examples
google-apps-scriptgoogle-docsgmail-api

how to pass parameters to a triggered function in google-app-script


I have a array of recipients and a scheduled time at which the mail has to be sent. I am eager in knowing if there is someway to create a trigger to which i can pass these params(recipients)

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();
}

If params cannot be passed to a timeBased trigger, then is there any other work around?


Solution

  • There is no direct way to do this. But here is a workaround. Note: This is just the instruction and not the actual code. Check my comments in code.

    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
    }