Skip to content

Instantly share code, notes, and snippets.

@stevenbell
Created August 12, 2018 18:20
Show Gist options
  • Save stevenbell/64c18089fd7a4c7ee50d5d38eb93e45d to your computer and use it in GitHub Desktop.
Save stevenbell/64c18089fd7a4c7ee50d5d38eb93e45d to your computer and use it in GitHub Desktop.
Google apps script to hide incoming email and deliver it on a schedule
var LABEL_NAME = 'inbox-holding'
function setup() {
// Create a label to put paused messages in
// First go through all the labels and check that it doesn't already exist
var label = null;
allLabels = Gmail.Users.Labels.list('me');
for (var i = 0; i < allLabels.labels.length; i++) {
if(allLabels.labels[i].name == LABEL_NAME){
label = allLabels.labels[i];
break; // Found it, just quit now
}
}
if(label == null){ // Didn't find it, so create it
label = Gmail.Users.Labels.create({'name':LABEL_NAME,
'labelListVisibility':'labelHide'},
'me');
}
// Add a filter that automatically puts all incoming messages into this label
// and archives them so they don't appear in the inbox
var filter = Gmail.Users.Settings.Filters.create({'id':'schedule_inbox_filter',
'criteria':{
'from':'*',
'query':'label:inbox'
},
'action':{
'addLabelIds':[label.id],
'removeLabelIds':['INBOX']
}},
'me');
// Set up triggers to run the deliver() method at the desired times
// TODO: allow separate schedule for weekends, probably by moving this to a
// data structure rather than hard-coding it.
ScriptApp.newTrigger("deliver")
.timeBased()
.atHour(7)
.nearMinute(40)
.everyDays(1)
.create();
ScriptApp.newTrigger("deliver")
.timeBased()
.atHour(13)
.nearMinute(0)
.everyDays(1)
.create();
ScriptApp.newTrigger("deliver")
.timeBased()
.atHour(17)
.nearMinute(0)
.everyDays(1)
.create();
}
// Deliver mail stored in the special label to the inbox
// Scheduled for specific times of day, and will occur +/- 15 minutes of that time
function deliver() {
// Find the label
allLabels = Gmail.Users.Labels.list('me');
var label = null;
for (var i = 0; i < allLabels.labels.length; i++) {
if(allLabels.labels[i].name == LABEL_NAME){
label = allLabels.labels[i];
break;
}
}
if(label != null){
// Get all the threads with the label
allThreads = Gmail.Users.Threads.list('me', { 'labelIds':[label.id] } );
// If there are no messages, we're done
if(allThreads.resultSizeEstimate == 0){
return;
}
Logger.log(new Date() + ": " + allThreads.threads.length + " messages delivered");
// Now move each of these threads to the inbox and remove the label
for (var i = 0; i < allThreads.threads.length; i++) {
Gmail.Users.Threads.modify({'addLabelIds': ['INBOX'],
'removeLabelIds': [label.id]},
'me', allThreads.threads[i].id);
}
}
else{
Logger.log("Couldn't find scheduled inbox label!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment