Skip to content

Instantly share code, notes, and snippets.

@bcicen
Last active July 17, 2018 10:55
Show Gist options
  • Save bcicen/9696d7888e2aea130d8b to your computer and use it in GitHub Desktop.
Save bcicen/9696d7888e2aea130d8b to your computer and use it in GitHub Desktop.
#!usr/bin/python
import os
import email
import imaplib
from operator import itemgetter
username = '[email protected]'
password = 'mypass'
imap = imaplib.IMAP4_SSL("imap.gmail.com")
imap.login(username, password)
def read_mailboxes():
res, mailboxes = imap.list()
if res != 'OK':
raise Exception(res)
return [ m.split('"/"')[-1].replace('"', '').strip() for m in mailboxes ]
def select_mailbox(options):
os.system('clear')
selection = None
sorted_options = sorted(options.items(), key=itemgetter(0))
for idx,o in enumerate(sorted_options):
if o[1]:
print('[%s] (*) %s ' % (idx, o[0]))
else:
print('[%s] () %s ' % (idx, o[0]))
print('[done] Purge selected mailboxes')
while not selection:
selection = raw_input("Toggle mailbox/label to purge: ")
if selection == 'done':
return [ o for o in options if options[o] ]
try:
name = sorted_options[int(selection)][0]
options[name] = not options[name]
return select_mailbox(options)
except:
print("Invalid choice")
sleep(1)
return select_mailbox(options)
mailbox_names = select_mailbox({ k:False for k in read_mailboxes() })
for m in mailbox_names:
print('purging %s...' % m)
success = 0
while success == 0:
try:
imap.select(m)
imap.store("1:*",'+X-GM-LABELS', '\\Trash')
success = 1
except:
print('sysfail, restarting %s purge' % m)
imap = imaplib.IMAP4_SSL("imap.gmail.com")
imap.login(username, password)
print('\ndone')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment