Last active
December 29, 2023 07:25
-
-
Save giovaneliberato/b3ebce305262888633c1 to your computer and use it in GitHub Desktop.
Python script to delete emails from a specific sender at gmail
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#coding: utf-8 | |
import imaplib | |
import sys | |
''' | |
Simple script that delete emails from a given sender | |
params: | |
-username: Gmail username | |
-pw: gmail pw | |
-label: If you have a label that holds the emails, specify here | |
-sender: the target sender you want to delete | |
usage: python delete_emails.py username='[email protected]' pw='bla' label='e-commerce' sender='[email protected]' | |
see http://stackoverflow.com/a/5366205 for mode details | |
''' | |
args = dict([arg.split('=') for arg in sys.argv[1:]]) | |
print("Logging into GMAIL with user %s\n" % args['username']) | |
server = imaplib.IMAP4_SSL('imap.gmail.com') | |
connection_message = server.login(args['username'], args['pw']) | |
print(connection_message) | |
if args.get('label'): | |
print("Using label: %s" % args['label']) | |
server.select(args['label']) | |
else: | |
print("Using inbox") | |
server.select("inbox") | |
print("Searching emails from %s" % args['sender']) | |
result_status, email_ids = server.search(None, '(FROM "%s")' % args['sender']) | |
email_ids = email_ids[0].split() | |
if len(email_ids) == 0: | |
print("No emails found, finishing...") | |
else: | |
print("%d emails found, sending to trash folder..." % len(email_ids)) | |
server.store('1:*', '+X-GM-LABELS', '\\Trash') | |
server.expunge() | |
print("Done!") |
Deletes everything when not provided with a label.
Not working. With correct email id and password, it is failing.
You need to go to your google account settings and enable 'less secure app access'
Deletes everything when not provided with a label.
Change line 42 to
for email_id in email_ids:
server.store(email_id, '+X-GM-LABELS', '\\Trash')
Thank you
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not working. With correct email id and password, it is failing.