Skip to content

Instantly share code, notes, and snippets.

@viperadnan-git
Last active September 5, 2022 12:16
Show Gist options
  • Save viperadnan-git/fcb0ecda32de0b9a27ec03829a7c12e8 to your computer and use it in GitHub Desktop.
Save viperadnan-git/fcb0ecda32de0b9a27ec03829a7c12e8 to your computer and use it in GitHub Desktop.
Delete Junk Email from GMail in Bulk

Delete Junk Emails from you Gmail Account easily with python.

Generate Mail App Password
Configure What to delete
  • Default it will delete all email which contains Custom String in subject. Change it in line 5.
  • To delete all email from a specific sender, replace line 10 with typ, data = box.search(None, 'from', 'specific@sender.email')
  • To delete all unread email, replace line 10 with typ, data = box.search(None, 'UnSeen') or set value of query to UnSeen`
Run snippet with python

Use python3.8.0 or older.

python3 delete_email.py
import imaplib
GmailId = "YourUsername@gmail.com"
AppPassword = "YourAppPassword"
query = r'(X-GM-RAW "subject:\"Custom String\"")'
box = imaplib.IMAP4_SSL('imap.gmail.com', 993)
box.login(GmailId, AppPassword)
box.select('Inbox')
typ, data = box.search(None, query)
count = 0
for num in data[0].split():
box.store(num, '+FLAGS', '\\Deleted')
count += 1
box.expunge()
box.close()
box.logout()
print(f"Deleted {count} junk emails successfully")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment