Skip to content

Instantly share code, notes, and snippets.

@DeanHickerson
Last active August 22, 2023 11:35
Show Gist options
  • Select an option

  • Save DeanHickerson/47f391baa45b14c7e29bf6443ccb3bdd to your computer and use it in GitHub Desktop.

Select an option

Save DeanHickerson/47f391baa45b14c7e29bf6443ccb3bdd to your computer and use it in GitHub Desktop.
Gmail Mail Manager MailMan v2.0

MailMan Gmail Mail Manager v2.0

This is an overhauled approach to an older script that I was running for a while to clean up my Gmail. This script can delete old emails automatically and sort old emails from the inbox to folders (labels).

Setup

  1. Create a new Google Apps Script at https://script.google.com and overwrite the placeholder content with the javascript below.
  2. Create a google spreadsheet which will be used to store and easily update your configurations.
  3. In the Spreadsheet create a table with the same headers from the following example.
Labels Sender_Addresses filter_to
Shopping noreply@mailer.com Mailer
Junk
Emails From Jim

NOTE:

  • The 1st column is just a list of the labels (folders) that you have in your Gmail that you already filter things into with the typical gmail filters. The default setting of the script is to delete emails from these folders when they reach 120+ days old.
  • The 2nd column is email addresses that you receive emails from on a regular basis that you want to move from the inbox to a folder after the specified amount of time in the script (120 days).
  • The 3rd column is for the labels (folders) that you want to filter the email in the adjacent column to after the specified amount of days.
  • Columns 2 and 3 are optional and it essentially works like a filter rule on your inbox that is on a delay.
  1. Open the script file and configure your settings.
    1. Grab the ID of the spreadsheet which you setup for your configuration. The ID is the part of the URL of the spreadsheet which is inbetween the .../d/ and the /edit.... Example: https://docs.google.com/spreadsheets/d/icvp_M9Sk5gg4-f_xoJWK/edit#gid=0. The ID of this URL would be icvp_M9Sk5gg4-f_xoJWK. Paste the ID into the SPREADSHEET_ID variable in the script file.
    2. Edit the DELETE_TIME_THRESHOLD and FILTER_TIME_THRESHOLD values if you would like to set them to different numbers of days.
    3. To the left menu of the script file select Triggers. ⏰
    4. Setup your trigger to execute the script's mailMan function on a reoccurring basis of your choosing. I like to have mine run every night at 1am.
    5. Naviage back to the script editor via the left menu and then at the top select the install function and run it.
    6. Then select the mailMan function and run it to run your first batch. You will see the console output in the executions pane informing you of how many emails are being handled.
  2. Fin.
// Gmail Manager v2.0
// Run install to auth the script's access to Gmail and Sheets
function install() {
return;
}
// Be sure to create a Google Spreadsheet to store the labels and emails that you want to target.
// For example if your sheet URL is: https://docs.google.com/spreadsheets/d/icvp_M9Sk5gg4-f_xoJWK/edit#gid=0
// then your sheet ID would be icvp_M9Sk5gg4-f_xoJWK
const SPREADSHEET_ID = 'YOUR_SHEET_ID_HERE';
const SHEET_VALUES = SpreadsheetApp.openById(SPREADSHEET_ID).getSheets()[0].getDataRange().getValues();
// Set the number of days that we want to delete after
const DELETE_TIME_THRESHOLD = `120`;
const FILTER_TIME_THRESHOLD = `120`;
// Get the Labels we want to archive from our spreadsheet data values
const LABELS_TO_DELETE = SHEET_VALUES.map(row => row[0]).slice(1);
// Get the special senders we want to handle.
const ADDRESSES = SHEET_VALUES.slice(1).map(row => {
return {address:row[1],label:row[2]}
}).filter(obj => obj.address);
function mailMan() {
// Start labeling of emails
console.log(`Beginning organization process of specified emails to specified folders...`)
let results = {};
ADDRESSES.forEach(address => {
results[address.address] = GmailApp.search(`from:${address.address} older_than:${FILTER_TIME_THRESHOLD}d is:inbox`,0,150);
});
for(sender in results) {
ADDRESSES.forEach(address => {
if(address.address == sender) {
if(address.label) {
console.log(`Sorting ${results[sender].length} emails from ${address.address} to ${address.label}...`);
results[sender].forEach(thread => {
try {
thread.addLabel(GmailApp.getUserLabelByName(address.label));
thread.moveToArchive();
} catch(error) {
console.log(`Unable add ${thread.getFirstMessageSubject()} to label. Might not have been able to find label: ${address.label}`);
console.log(error);
}
});
}
}
});
}
// Start archive process of old emails in folders
console.log(`Beginning deletion process of old emails in specified folders...`)
LABELS_TO_DELETE.forEach(label => {
let trashThreads = GmailApp.search(`label:${label} older_than:${DELETE_TIME_THRESHOLD}d`,0,150);
console.log(`Sending ${trashThreads.length} from ${label} to the trash...`);
trashThreads.forEach(thread => {
try {
thread.moveToTrash();
} catch(error) {
console.log(`Unable to move thread: ${thread.getFirstMessageSubject()} to trash.`)
console.log(error);
}
});
});
}
@bachhavdipak
Copy link

Whats YOUR_SHEET_ID_HERE?

@DeanHickerson
Copy link
Author

In setup Step #2 it says:

Create a google spreadsheet which will be used to store and easily update your configurations.

This version of the script requires you to create a Google Sheet which you use to store your email labels in. This way, later on, to modify the script email label variables (add more or remove some), all you have to do is edit the google sheet instead.

Then in Step #4 Grab the ID of the spreadsheet which you setup for your configuration. The ID is the part of the URL of the spreadsheet which is inbetween the .../d/ and the /edit.... Example: https://docs.google.com/spreadsheets/d/icvp_M9Sk5gg4-f_xoJWK/edit#gid=0. The ID of this URL would be icvp_M9Sk5gg4-f_xoJWK. Paste the ID into the SPREADSHEET_ID variable in the script file.

Example:

const SPREADSHEET_ID = 'icvp_M9Sk5gg4-f_xoJWK';

@DeanHickerson
Copy link
Author

I updated the script with some comments to help explain on lines 8-10.

Alternatively, if you don't want to use a spreadsheet to store the target labels and emails you could replace lines 8-24 with the following.

// Set the number of days that we want to delete after
const DELETE_TIME_THRESHOLD = `120`;
const FILTER_TIME_THRESHOLD = `120`;

// List the Labels (folders) that you want the script to delete from.
// Example: ['Shopping', 'Junk', 'Emails From Jim']
const LABELS_TO_DELETE = [];

// List the email addresses and the corresponding label (folder) that you want to send them to.
// Example: [{address: 'noreply@mailer.com', label: 'Mailer'}]
const ADDRESSES = [];

@bachhavdipak
Copy link

Thanks @DeanHickerson , Its working as expected. Also can we extend it so it will automatically deletes old emails that match the specified label?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment