Search code examples
google-apps-scriptgmail

Mark auto-replied emails a certain label during out of work hours


Currently I am using the following code, which works fine but I wonder if it is possible that I can mark emails which were auto-replied by a specific label, so that I can check when I return to work?

  function autoReply() {
  var interval = 5;    //  if the script runs every 5 minutes; change otherwise
  var date = new Date();
  var day = date.getDay();
  var hour = date.getHours();
  if ([4,5,6,0].indexOf(day) > -1 || (day == 1 && hour < 9) || (day == 3 && hour >= 17)) {
    var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
    var threads = GmailApp.search('is:inbox after:' + timeFrom);
    var files = DriveApp.getRootFolder().getFilesByName('autoreply.html');
    var htmlbody;
    while (files.hasNext()) {
      var file = files.next();
      htmlbody = file.getBlob().getDataAsString('utf8');      
    }
    for (var i = 0; i < threads.length; i++) {
      if (threads[i].isUnread()){
      threads[i].reply("", {
          htmlBody: htmlbody
        });
      threads[i].markRead();
      threads[i].markImportant();
      }
    }
  }
}

So far, I can only get threads[i].markImportantwork, but threads[i].markStarred or other customised labels won't.


Solution

  • You need to use the method starMessages(messages)

    Sample:

    for (var i = 0; i < threads.length; i++) {
          if (threads[i].isUnread()){
          threads[i].reply("", {
              htmlBody: htmlbody
            });
          GmailApp.starMessages(threads[i].getMessages());
          }
        }