Search code examples
google-apps-scriptgmail

Delete email with google apps script matching certain time conditions


Delete gmail received between midnight and 1am matching certain conditions


Solution

  • Create a filter that assigns a label to a messages from a server, for example, MyServer. Then you can use code like this:

    function delMsg() {
      // Setting the time range for checking
      var FROM = 0; // Minutes after midnight (start of range)
      var TO = 75; // Minutes after "FROM" (length of range)
      var label = GmailApp.getUserLabelByName("MyServer");
      var threads = label.getThreads();
      for (var i = 0; i < threads.length; i++) {
        var messages = threads[i].getMessages();
        var date = messages[0].getDate();
        var hour = date.getHours();
        var minutes = date.getMinutes();
        if ((hour * 60 + minutes >= FROM) && (hour * 60 + minutes <= FROM + TO)) {
          Logger.log(messages[0].getDate());
          Logger.log(messages[0].getSubject());
          messages[0].star();
          // messages[0].moveToTrash();
        }
      }
    }
    

    In this example messages sent between midnight and 1:15 will be starred. To remove them uncomment messages[0].moveToTrash()