Last active
          February 24, 2025 19:48 
        
      - 
      
- 
        Save jordanlambrecht/ec6ad36b5a48271fcbb4bb811512e477 to your computer and use it in GitHub Desktop. 
    Auto Delete / Archive Emails in Gmail
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | function autoDelete() { | |
| console.log('Started autoDelete run.'); | |
| var delayDays = 2; | |
| var maxDate = new Date(); | |
| maxDate.setDate(maxDate.getDate()-delayDays); | |
| var label = GmailApp.getUserLabelByName("delete me"); | |
| var threads = label.getThreads(); | |
| if(threads.length > 0){ | |
| console.log('Found ' + threads.length + ' emails marked for deletion.'); | |
| var counter = 0; | |
| try { | |
| for(var i =0; i < threads.length; i++){ | |
| if (threads[i].getLastMessageDate()<maxDate){ | |
| Logger.log('deleted email: ' + threads[i].getFirstMessageSubject()); | |
| threads[i].markUnimportant(); | |
| threads[i].markRead(); | |
| threads[i].moveToTrash(); | |
| counter++; | |
| } | |
| } | |
| console.log('Successfully moved ' + counter + 'emails to the trash.'); | |
| } | |
| catch(e){ | |
| console.error('Could Not Start Run: ' + e); | |
| } | |
| } | |
| else{ | |
| console.log('Found ' + threads.length + 'emails marked for deletion. Exiting.'); | |
| } | |
| } | |
| function autoArchive() { | |
| console.log('Started autoArchive run.'); | |
| var delayDays = 2; | |
| var maxDate = new Date(); | |
| maxDate.setDate(maxDate.getDate()-delayDays); | |
| var label = GmailApp.getUserLabelByName("archive me"); | |
| var threads = label.getThreads(); | |
| if(threads.length > 0){ | |
| console.log('Found ' + threads.length + ' emails marked for archival.'); | |
| var counter = 0; | |
| try { | |
| for(var i =0; i < threads.length; i++){ | |
| if (threads[i].getLastMessageDate()<maxDate){ | |
| Logger.log('archived email: ' + threads[i].getFirstMessageSubject()); | |
| threads[i].markRead(); | |
| threads[i].moveToArchive(); | |
| threads[i].markUnimportant(); | |
| counter++; | |
| } | |
| } | |
| console.log('Successfully archived ' + counter + 'emails.'); | |
| } | |
| catch(e){ | |
| console.error('Could Not Start Run: ' + e); | |
| } | |
| } | |
| else{ | |
| console.log('Found ' + threads.length + 'emails marked for archival. Exiting.'); | |
| } | |
| } | 
Shoutout to @klinquist for adding a few enhancements: https://gist.github.com/klinquist/78f81e55c094111a9d3ba675c3bfd3a0
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
And just saw in the forks that someone has already done a much more complete version of this:
https://gist.github.com/zoidy/38773c6f128d4dfb94e77df99af7c446