Send Email when value changes in Google Spreadsheet

瘦欲@ 提交于 2019-11-29 04:03:15

I can get you started:

  1. Add a trigger in Resources>Current project's triggers that triggers sendEmail() "on edit".
  2. ...

I just wrote a script that does that kind of thing but I wanted it to keep an eye on all the changes in the sheet but send a message only once every hour to avoid spamming my mailBox.

The script has 2 functions, one that collects the changes and stores them in text format and a second that sends email if any change occurred in the last hour.

The first function is called grabData and must be triggered by an onEdit installable trigger and goes like this :

function grabData(e){
  Logger.log(JSON.stringify(e));
  var cell = e.range.getA1Notation();
  var user = e.user.email;
  var time = Utilities.formatDate(new Date(),Session.getScriptTimeZone(),'dd-MM-yyyy')+' à '+Utilities.formatDate(new Date(),Session.getScriptTimeZone(),'hh:mm');;
  if(user!='email1@email.com'&&cell!='A1'){ 
  var dataUser1 = PropertiesService.getScriptProperties().getProperty('contentUser1');
  if(dataUser1==null){dataUser1=''};
  dataUser1+='\nCellule '+cell+' modifiée le '+time+' par '+user+' (nouvelle valeur = '+e.range.getValue()+')';
  PropertiesService.getScriptProperties().setProperty('contentUser1',dataUser1);
  }
  if(user!='email2@email.com'&&cell!='A1'){
  var dataUser2 = PropertiesService.getScriptProperties().getProperty('contentUser2');
  if(dataUser2==null){dataUser2=''};
  dataUser2+='\nCellule '+cell+' modifiée le '+time+' par '+user+' (nouvelle valeur = '+e.range.getValue()+')';
  PropertiesService.getScriptProperties().setProperty('contentUser2',dataUser2);
}
}

The other function has a timer trigger, I set it to fire every hour but you can change it to your best fit.

function sendReport(){
  var dataUser1 = PropertiesService.getScriptProperties().getProperty('contentUser1');
  var dataUser2 = PropertiesService.getScriptProperties().getProperty('contentUser2');
  if(dataUser1.length>1){
    MailApp.sendEmail('email2@email.com', 'Modification dans le planning FFE', dataUser1);
    PropertiesService.getScriptProperties().setProperty('contentUser1','');
  }
  if(dataUser2.length>1){
    MailApp.sendEmail('email1@email.com', 'Modification dans le planning FFE', dataUser2);
    PropertiesService.getScriptProperties().setProperty('contentUser2','');
  }
}

after a mail has been sent, the stored data is deleted. No mail is sent if no change was recorded.

You can also notice that I have 2 different users and 2 different storage places so that each of them can see what the other does without being notified for his own modifications.

Since both function use installable triggers, this will run on your account so beware not to explode your quotas if you set the timer to a very short period.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!