Skip to content

Instantly share code, notes, and snippets.

@sagarchauhan005
Created May 15, 2023 11:24
Show Gist options
  • Save sagarchauhan005/c449c361d10c340d8ab37e9e11789a91 to your computer and use it in GitHub Desktop.
Save sagarchauhan005/c449c361d10c340d8ab37e9e11789a91 to your computer and use it in GitHub Desktop.
Delete gmail email in bulk
function purgeGmail() {
// Define your search query
let SEARCH_QUERY='from:info@example.com';
try {
// We are processing 100 messages in a batch to prevent script errors.
let totalFound = 0;
let totalDeleted = 0;
// Search for threads matching the specified search syntax
const threads = GmailApp.search(SEARCH_QUERY, 0, 100);
if (threads.length > 0) {
for (let i = 0; i < threads.length; i++) {
const messages = threads[i].getMessages();
for (let j = 0; j < messages.length; j++) {
const email = messages[j];
// Delete the email directly
Gmail.Users.Messages.remove('me', email.getId());
totalDeleted++;
}
totalFound += messages.length;
}
console.log("Total " + totalFound + " emails found");
console.log("Total " + totalDeleted + " emails deleted");
} else {
console.log("No emails found matching the search criteria");
}
} catch (e) {
console.log("Exception found",e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment