Last active
March 22, 2019 04:01
-
-
Save daleysoftware/788e46f6e2d5e8e8d708 to your computer and use it in GitHub Desktop.
Script to delete large folder in 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
""" | |
Script to delete large folder in gmail. | |
Adapted from: http://ae.ro/1upv7rt | |
Notes: | |
1. For this to work with gmail, you will need to adjust into your IMAP settings | |
so that they look like this: | |
* IMAP: enabled | |
* Auto-expunge: off | |
* When a message is marked as deleted and expunged: immediately delete | |
2. If you have 2FA enabled, you will need to disable it to use this script, or | |
you can use an application specific password. | |
3. For extremely large folders (1M+ messages), this will take a _long_ time. | |
Run it overnight. | |
4. To handle occasional failure (network or otherwise), run in a retry loop, | |
e.g.: | |
``` | |
until python delete_large_gmail_folder.py <email> <password> <label>; do sleep 10; done | |
``` | |
""" | |
import imaplib | |
import sys | |
if len(sys.argv) != 4: | |
print("Usage: python %s <email> <password> <label>" % sys.argv[0]) | |
sys.exit(1) | |
email = sys.argv[1] | |
password = sys.argv[2] | |
label = sys.argv[3] | |
CHUNK_SIZE = 250 | |
def mail_connect(): | |
mail = imaplib.IMAP4_SSL("imap.gmail.com") | |
mail.login(email, password) | |
mail.select(label) | |
return mail | |
def chunks(arr, num): | |
for i in xrange(0, len(arr), num): | |
yield arr[i:i + num] | |
print("Connecting...") | |
mail = mail_connect() | |
print("Acquiring message IDs...") | |
_, data = mail.search(None, "UNDELETED") | |
ids = data[0].split() | |
length = len(ids) | |
counter = 1 | |
print("Messages to delete: " + str(length)) | |
print("Deleting messages...") | |
for i in list(chunks(ids, CHUNK_SIZE)): | |
# Add deleted flag and remove from inbox, i.e. delete irrevocably. | |
mail.store(",".join(i), "-X-GM-LABELS", "\\Inbox") | |
mail.store(",".join(i), "+X-GM-LABELS", "\\Trash") | |
mail.store(",".join(i), "+FLAGS", "\\Deleted") | |
print(".") | |
if counter % 10 == 0: | |
mail.expunge() | |
print("Processed " + str(counter * CHUNK_SIZE) + "/" + str(length)) | |
counter += 1 | |
# Final expunge to make sure everything is committed. | |
mail.expunge() | |
print("Done.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment