Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger Google Apps Script by email

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 a call to yet a different GAScript that could, for example, change the ACL setting of a specific document.

I'm assuming someone else has already implemented this pattern but not sure how I go about finding examples.

thx

like image 420
justSteve Avatar asked May 02 '12 19:05

justSteve


People also ask

Can a Google Sheet trigger an email?

Set up email notifications In Google Sheets, open the spreadsheet where you want to set notifications. Notification rules. Select when and how you want to receive notifications. Click Save.


1 Answers

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

like image 68
Henrique G. Abreu Avatar answered Oct 06 '22 07:10

Henrique G. Abreu