Skip to content

Instantly share code, notes, and snippets.

@vladbabii
Last active February 24, 2024 15:09
Show Gist options
  • Save vladbabii/b7ee417662ddc435960cbf08eedc7c80 to your computer and use it in GitHub Desktop.
Save vladbabii/b7ee417662ddc435960cbf08eedc7c80 to your computer and use it in GitHub Desktop.
google apps script for gmail to auto move totrash (run daily)
function cleanUpAll(){
clean7DaysAutoPrune();
clean6MonthsAutoPrune();
clean1YearAutoPrune();
}
function clean7DaysAutoPrune(){
cleanUpWithParams(7,'auto-prune/auto-prune-7d');
}
function clean6MonthsAutoPrune(){
cleanUpWithParams(182,'auto-prune/auto-prune-6mo');
}
function clean1YearAutoPrune(){
cleanUpWithParams(365,'auto-prune/auto-prune-1yr');
}
function cleanUpWithParams(delayDays,labelName) {
if(typeof delayDays!=='number'){
return false;
}
if(typeof labelName !== 'string'){
return false;
}
labelName=labelName.trim();
if(labelName.length<3){
return false;
}
var maxDate = new Date();
maxDate.setDate(maxDate.getDate()-delayDays);
var label = GmailApp.getUserLabelByName(labelName);
if(typeof(label)!=='object'){
console.error('could not read label '+labelName);
return 1;
}
var threads = label.getThreads();
var maxThreads = 1000;
let lastDate;
for (var i=0; i < threads.length; i++){
if(i<=maxThreads){
try {
lastDate=threads[i].getLastMessageDate();
}catch(err){
lastDate=undefined;
}
if(typeof(lastDate)!=='undefined'){
if(threads[i].getLastMessageDate() < maxDate) {
try{
threads[i].moveToTrash();
threads[i].removeLabel(label);
console.log('thread '+i+' / '+maxThreads+': deleted ') //,threads[i].getFirstMessageSubject(),' ',lastDate);
}catch(error){
console.log('thread '+i+' / '+maxThreads+': error',error);
}
}else{
console.log('thread '+i+' / '+maxThreads+': skipped '); //,threads[i].getFirstMessageSubject(),' ',lastDate);
}
} else {
try{
console.error('could not get last date of',i,'/',maxThreads,': ',threads[i].getFirstMessageSubject());
}catch(erx){
console.error('could not get last date or email subject of',i,'/',maxThreads,': ',threads[i].getId(),erx);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment