Skip to content

Instantly share code, notes, and snippets.

Last active May 25, 2021 19:36
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Move(archive) emails from one label to another automatically after X days. Useful for reducing Newsletter FOMO and pile-up.

Gmail Label Modifier: Automatically move emails b/w labels after X days. One time setup!

Follow the steps in this blogpost. I basically copied and modified some code from 2-3 sources, all are mentioned in the blogpost. Reply below or DM on twitter if this was helpful :)

// The name of the Gmail Label(s) that are to be moved to an Archiving Label (which you've already made earlier).
//Note: I need to do a small modification. For now, add just 1 label to LABELS_TO_DELETE like shown below
var ARCHIVE_LABEL= "Old Newsletters";
var TRIGGER_NAME = "dailyDeleteGmail";
// Purge messages in the above label automatically after how many days?
//Add your timezone
// Maximum number of threads to process per run
var PAGE_SIZE = 150;
// If number of threads exceeds page size, resume job after X mins
// (max execution time is 6 mins. info regarding other quota limits in Google AppScript docs)
function Initialize() {
function Install() {
// First run 2 mins after install
.at(new Date((new Date()).getTime() + 1000*60*2))
// Run daily there after
function Uninstall() {
var triggers = ScriptApp.getProjectTriggers();
for (var i=0; i<triggers.length; i++) {
function dailyDeleteGmail() {
var age = new Date();
age.setDate(age.getDate() - DELETE_AFTER_DAYS);
var purge = Utilities.formatDate(age, TIMEZONE, "yyyy-MM-dd");
var search = "(label:" + LABELS_TO_DELETE.join(" OR label:") + ") before:" + purge;
Logger.log("PURGE: " + purge);
Logger.log("SEARCH: " + search);
try {
var threads =, 0, PAGE_SIZE);
// Resume again in 10 minutes
if (threads.length == PAGE_SIZE) {
Logger.log("Scheduling follow up job...");
.at(new Date((new Date()).getTime() + 1000*60*RESUME_FREQUENCY))
// MOVE threads which meet age criteria from LABELS_TO_DELETE to ARCHIVE_LABEL.
Logger.log("Processing " + threads.length + " threads...");
for (var i=0; i<threads.length; i++) {
var label1 = GmailApp.getUserLabelByName(LABELS_TO_DELETE[0]); // FROM
var label2 = GmailApp.getUserLabelByName(ARCHIVE_LABEL); // TO
var thread = threads[i];
if (thread.getLastMessageDate() < age) {
} catch (e) {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment