-
-
Save zoidy/38773c6f128d4dfb94e77df99af7c446 to your computer and use it in GitHub Desktop.
/* | |
Original Sources: | |
- https://pixelbakery.com/recipes/gmail-automatically-delete-or-archive-emails | |
- https://benbjurstrom.com/purge-email | |
v1.1 | |
https://gist.github.com/zoidy | |
Auto-archive and delete Gmail messages based on a defined retention period. Functionality: | |
- Uses Gmail labels to apply retention rules (archive or delete) | |
- Ability to customize retention period using the label text | |
- Handles large numbers of emails to process via (side steps the Google Apps Script execution limit by processing in batches). | |
To set up | |
1. Create a new Apps Script in your Google Drive and paste this code, then click the Save button | |
2. Under Services on the left hand side of the Apps Script editor, add Gmail | |
2. Run the install() function manually once to set up the permissions to gmail (select it from dropdown in the toolbar and click Run) | |
3. Add labels to Gmail messages to indicate what to archive and delete. The format is | |
ARCHIVE_LABEL:#[d|w] A single message can have one ARCHIVE_LABEL and one DELETE_LABEL simultaneously. | |
Example: | |
Archive:2d = archive the message after 2 days | |
Delete:12w = deletes the message after 12 weeks (84 days). | |
*/ | |
ARCHIVE_LABEL = "Archive"; // label for messages that should be archived | |
DELETE_LABEL = "Delete"; // label for messages that should be deleted | |
DEFAULT_TIMEPERIOD_DAYS = 2.0; //retention period if none is specified | |
// Maximum number of message threads to process per run. | |
// It takes about 1.2 sec per email thread, so a 4 minute delay between processing runs | |
// when there are more than 175 items in a page is safe. | |
PAGE_SIZE = 175; | |
NEXT_RUN_DELAY = 4; | |
// How often to run the check, in hours. After installing the script, the interval can | |
// be changed either by running the uninstall function, changing the interval, and | |
// running the install function again, or by manually editing the existing trigger in the | |
// AppsScript editor | |
PURGE_INTERVAL = 8; | |
// #################################################################################### | |
/** | |
* Create a trigger that executes the purge function every day. | |
* Execute this function to install the script. | |
*/ | |
function install() { | |
GmailApp.getUserLabels(); | |
ScriptApp.newTrigger('purge').timeBased().everyHours(PURGE_INTERVAL).create(); | |
} | |
/** | |
* Deletes all of the project's triggers | |
* Execute this function to unintstall the script. | |
*/ | |
function uninstall() { | |
var triggers = ScriptApp.getProjectTriggers(); | |
for (var i = 0; i < triggers.length; i++) { | |
ScriptApp.deleteTrigger(triggers[i]); | |
} | |
} | |
/** | |
* Create a trigger that executes the purgeMore function NEXT_RUN_DELAY minutes from now | |
*/ | |
function setPurgeMoreTrigger(){ | |
ScriptApp.newTrigger('purgeMore').timeBased() | |
.at(new Date((new Date()).getTime() + (1000 * 60 * NEXT_RUN_DELAY))).create(); | |
} | |
/** | |
* Deletes all triggers that call the purgeMore function. | |
*/ | |
function removePurgeMoreTriggers(){ | |
var triggers = ScriptApp.getProjectTriggers(); | |
for (var i = 0; i < triggers.length; i++) { | |
var trigger = triggers[i]; | |
if(trigger.getHandlerFunction() === 'purgeMore'){ | |
ScriptApp.deleteTrigger(trigger); | |
} | |
} | |
} | |
/** | |
* Wrapper for the purge function | |
*/ | |
function purgeMore() { | |
purge(); | |
} | |
function getDaysFromLabel(label) { | |
/* | |
Expected format of label is LABEL:#T where LABEL is one of ARCHIVE_LABEL or DELETE_LABEL, | |
# is a number, T is a time unit, currently only 'd' and 'w' is supported. Default is 'd'. | |
Returns a number representing the number of days. | |
*/ | |
var timeunit = label.substring(label.length-1); | |
var convertMult; | |
var days; | |
switch(timeunit) { | |
case "d": | |
// days | |
convertMult = 1; | |
break; | |
case "w": | |
// convert weeks to days | |
convertMult = 7; | |
break; | |
default: | |
return DEFAULT_TIMEPERIOD_DAYS; | |
} | |
days = parseFloat(label.substring(label.indexOf(":")+1,label.length-1)) * convertMult; | |
if(isNaN(days)) | |
days = DEFAULT_TIMEPERIOD_DAYS; | |
return days; | |
} | |
function process(action, labels) { | |
/* | |
Performs the action on the labels in the given array, extracting the retention period from the label. | |
*/ | |
console.log('Started ' + action + ' run.'); | |
var threadActions = []; | |
switch(action) { | |
//other actions are ["markRead", "markUnimportant"] but it slows things down | |
case "autoArchive": | |
threadActions = ["moveToArchive"]; | |
break; | |
case "autoDelete": | |
threadActions = ["moveToTrash"]; | |
break; | |
default: | |
Logger.log("Unrecognized action " + action); | |
return; | |
} | |
for (var i = 0; i < labels.length; i++) { | |
var labelToProcess = labels[i].getName(); | |
var retentiondays = getDaysFromLabel(labelToProcess); | |
Logger.log("Processing " + labelToProcess + ", with retention " + retentiondays + " days."); | |
var maxDate = new Date(); | |
maxDate.setDate(maxDate.getDate()-retentiondays); | |
var totalthreads = GmailApp.getUserLabelByName(labelToProcess).getThreads().length; | |
var processthreads = GmailApp.search('label:' + labelToProcess.replace(' ', '-') + ' older_than:' + retentiondays + 'd', | |
0, PAGE_SIZE); | |
if(processthreads.length > 0){ | |
Logger.log('Found ' + (totalthreads == 500 ? 'at least ' + totalthreads : totalthreads) + | |
' emails tagged with ' + labelToProcess + '. Processing ' + Math.min(processthreads.length, PAGE_SIZE)); | |
if (processthreads.length === PAGE_SIZE) { | |
Logger.log('PAGE_SIZE exceeded. Processing will continue in ' + NEXT_RUN_DELAY + ' minutes.'); | |
setPurgeMoreTrigger(); | |
} | |
var counter = 0; | |
try { | |
for(var j=0; j < processthreads.length; j++){ | |
var thread = processthreads[j]; | |
var threadDate = thread.getLastMessageDate(); | |
if (threadDate<maxDate){ | |
for(var k=0; k < threadActions.length; k++){ | |
thread[threadActions[k]](); | |
} | |
thread.removeLabel(labels[i]); //so processed items don't get reprocessed on future runs | |
counter++; | |
//uncomment for debugging but it slows things down | |
//Logger.log('processed: ' + thread.getFirstMessageSubject() + ' [date: ' + threadDate + ']'); | |
} | |
} | |
Logger.log('Successfully processed ' + counter + ' emails.'); | |
} | |
catch(e){ | |
Logger.log('Error processing: ' + e); | |
} | |
} | |
else | |
Logger.log('Found ' + processthreads.length + ' emails marked for processing. Exiting.'); | |
} | |
} | |
function purge(){ | |
removePurgeMoreTriggers(); | |
var allLabels = GmailApp.getUserLabels(); | |
var archiveLabels = allLabels.filter((label) => { | |
return label.getName().startsWith(ARCHIVE_LABEL); | |
}); | |
var deleteLabels = allLabels.filter((label) => { | |
return label.getName().startsWith(DELETE_LABEL); | |
}); | |
process('autoArchive', archiveLabels); | |
process('autoDelete', deleteLabels); | |
} |
I wasn't able to get the quotes to work, but you are right about the space. I changed my labels to use an underscore instead of space (archive_me:21d) and that worked! Also, I'm not sure why, but only 21d works, not 3w. Even googles search doesn't seem to like trying to use weeks. I've edited my labels to only use days now and those all work as well.
Thank you, again, for this script and the quick responses! Super excited to see my inbox stay clean now :)
I wasn't able to get the quotes to work, but you are right about the space. I changed my labels to use an underscore instead of space (archive_me:21d) and that worked! Also, I'm not sure why, but only 21d works, not 3w. Even googles search doesn't seem to like trying to use weeks. I've edited my labels to only use days now and those all work as well.
Thank you, again, for this script and the quick responses! Super excited to see my inbox stay clean now :)
Sure thing. Using 'w' is working for me so I'm not sure where the issue is there. As for the space, I'll play around with the code a bit when I get the chance. I feel like it should have a solution!
Edit: bug with using spaces in the label name is fixed with v1.1
If you wouldn't mind helping me, i'm just trying to set up a way to automatically delete sent emails, not put them in the trash but delete for good. This account is our SMTP server and gets filled up very quickly by sent emails and it a pain to have to go in every day to delete them manually as i've only been able to use Gmails standard filters to sort them into trash.
If you wouldn't mind helping me, i'm just trying to set up a way to automatically delete sent emails, not put them in the trash but delete for good. This account is our SMTP server and gets filled up very quickly by sent emails and it a pain to have to go in every day to delete them manually as i've only been able to use Gmails standard filters to sort them into trash.
I'm sorry, that's not what this script does, nor it is feasible to modify it to do what you ask. This script uses the Google Apps Script Gmail service to perform its actions. This service does not support deleting things permanently. In order to delete permanently, you'd have to use the Gmail API directly. Good luck.
Thanks for this. I copied and pasted your code exactly, but am getting a 'Max Date is not defined' error, and cannot even install the script. I am in Australia, is this a time zone issue? As I understand it, the max date is defined at line 150 as 'var maxDate = new Date();' and 'new Date()' means 'now' - is that right? So, time zone should not matter.... Why else would max date be seen as not defined by the script? Any help would be really appreciated.
Thanks for this. I copied and pasted your code exactly, but am getting a 'Max Date is not defined' error, and cannot even install the script. I am in Australia, is this a time zone issue? As I understand it, the max date is defined at line 150 as 'var maxDate = new Date();' and 'new Date()' means 'now' - is that right? So, time zone should not matter.... Why else would max date be seen as not defined by the script? Any help would be really appreciated.
What line is that error being thrown for? If you are trying to install following the instructions (running the install() function), line 150 isn't even called
I'm not sure what the issue could be. Retrieving the threads to process involves using Gmail's built-in search (line 149). You can try manually searching in the Gmail search box using the query "label:archive me:3w older_than:21d" and see what is returned.
Edit: I just realized the issue could be the space in the label. You can try modifying Line 149 to add quotes around the label like so:
'label:"' + labelToProcess + '" older_than:'
. If it works, let me know and I can update the script