Skip to content

Instantly share code, notes, and snippets.

@nikhilbhatt
Created April 29, 2023 19:18
Show Gist options
  • Save nikhilbhatt/4b92c065a0f204e9629d7036da85a10a to your computer and use it in GitHub Desktop.
Save nikhilbhatt/4b92c065a0f204e9629d7036da85a10a to your computer and use it in GitHub Desktop.
Google App Script to Delete emails permanently
function searchMails(searchQuery) {
return GmailApp.search(searchQuery, 0, 100);
}
function moveEmailsToTrash(emailThread) {
emailThread.moveToTrash();
}
function deleteEmailsPermanently(emailThread) {
Gmail.Users.Threads.remove('me', emailThread.getId());
}
function moveEmailsToTrash() {
const searchQuery = "from:(xyz.com OR abc.com)";
let searchResult = searchMails(searchQuery);
let emailInTrashCount = searchResult.length;
while(searchResult.length) {
console.log('Started moving emails with search query', searchQuery, 'To Trash count is :', searchResult.length);
GmailApp.moveThreadsToTrash(searchResult);
searchResult = searchMails(searchQuery);
emailInTrashCount += searchResult.length;
}
console.log('Total Emails moved to trash are', emailInTrashCount);
// One by one deletion of email
// searchResult.forEach((emailThread) => {
// console.log('Moving email to trash', ' \nSubject: ', emailThread.getMessages()[0].getSubject());
// emailThread.moveToTrash();
// emailInTrashCount += 1;
// })
// console.log('Total Emails moved to trash are: ', emailInTrashCount);
}
function deleteTrashEmailsPermanently() {
const trashMailThreads = GmailApp.getTrashThreads();
console.log('Trash Emails Count is', trashMailThreads.length);
console.log('Now Deleting Trash Emails permanently');
trashMailThreads.forEach((trashMailThread) => {
console.log('Deleting email with Subject :', trashMailThread.getMessages()[0].getSubject());
deleteEmailsPermanently(trashMailThread);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment