-
-
Save zoidy/38773c6f128d4dfb94e77df99af7c446 to your computer and use it in GitHub Desktop.
Auto Delete / Archive Emails in Gmail
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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); | |
} |
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.
Well we do use Gmail for the server, even then you don't think it's
possible? I have no clue of even where to start with coding so I honestly
don't even know what I was modifying lol
…On Tue, Jul 2, 2024, 10:08 PM Fernando Rios ***@***.***> wrote:
***@***.**** commented on this gist.
------------------------------
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 <https://developers.google.com/apps-script/reference/gmail> 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 <https://developers.google.com/gmail/api/reference/rest> directly.
Good luck.
—
Reply to this email directly, view it on GitHub
<https://gist.github.com/zoidy/38773c6f128d4dfb94e77df99af7c446#gistcomment-5109321>
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/ALOOBRMBKE2DWFXSQBY2AV3ZKNMILBFKMF2HI4TJMJ2XIZLTSKBKK5TBNR2WLJDUOJ2WLJDOMFWWLO3UNBZGKYLEL5YGC4TUNFRWS4DBNZ2F6YLDORUXM2LUPGBKK5TBNR2WLJDHNFZXJJDOMFWWLK3UNBZGKYLEL52HS4DFVRZXKYTKMVRXIX3UPFYGLK2HNFZXIQ3PNVWWK3TUUZ2G64DJMNZZDAVEOR4XAZNEM5UXG5FFOZQWY5LFVEYTENZTGAYTKNJQU52HE2LHM5SXFJTDOJSWC5DF>
.
You are receiving this email because you commented on the thread.
Triage notifications on the go with GitHub Mobile for iOS
<https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675>
or Android
<https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub>
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.