Trigger Google Apps Script by email

后端 未结 3 1368
执笔经年
执笔经年 2020-12-08 22:30

I\'m looking for examples of a pattern where a demon script running within a GoogleAppsForBusiness domain can parse incoming email messages. Some messages will will contain

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 22:56

    You can find script examples in the Apps Script user guide and tutorials. You may also search for related discussions on the forum. But I don't think there's one that fits you exactly, all code is out there for sure, but not on a single script.

    It's possible that someone wrote such script and never published it. Since it's somewhat straightforward to do and everyone's usage is different. For instance, how do you plan on marking your emails (the ones you've already read, executed, etc)? It may be nice to use a gmail filter to help you out, putting the "command" emails in a label right away, and the script just remove the label (and possibly set another one). Point is, see how it can differ a lot.

    Also, I think it's easier if you can keep all functions in the same script project. Possibly just on different files. As calling different scripts is way more complicated.

    Anyway, he's how I'd start it:

    //set a time-driven trigger to run this function on the desired frequency
    function monitorEmails() {
      var label = GmailApp.getUserLabelByName('command');
      var doneLabel = GmailApp.getUserLabelByName('executed');
      var cmds = label.getThreads();
      var max = Math.min(cmds.length,5);
      for( var i = 0; i < max; ++i ) {
        var email = cmds[i].getMessages()[0];
        var functionName = email.getBody();
        //you may need to do extra parsing here, depending on your usage
    
        var ret = undefined;
        try {
          ret = this[functionName]();
        } catch(err) {
          ret = err;
        }
        //replying the function return value to the email
        //this may make sense or not
        if( ret !== undefined )
          email.reply(ret);
        cmds[i].removeLabel(label).addLabel(doneLabel);
      }
    }
    

    ps: I have not tested this code

提交回复
热议问题