Created
October 11, 2017 00:40
-
-
Save cghiban/e8d18ebe670c0432377919a5252e2a61 to your computer and use it in GitHub Desktop.
delete email via imap
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
| import datetime | |
| import email | |
| import sys | |
| import imaplib | |
| m = imaplib.IMAP4_SSL("email.domain.com", 993) | |
| try: | |
| m.login("user","abcxyz") | |
| except Exception, e: | |
| print e | |
| sys.exit(1) | |
| print "------------- logged in" | |
| try: | |
| m.select() | |
| except Exception, e: | |
| print e | |
| sys.exit(1) | |
| print "------------- selected Inbox folder" | |
| since = (datetime.date.today() - datetime.timedelta(30)).strftime("%d-%b-%Y") | |
| print "------------- searching for messages since %s " % (since) | |
| #typ, data = m.search(None, '(SENTSINCE {0})'.format(since)) | |
| typ, data = m.search(None, 'ALL') | |
| print "------------- search done, found", len(data[0].split()), "items" | |
| checked = 0 | |
| removed = 0 | |
| for num in data[0].split()[::-1]: | |
| checked += 1 | |
| typ, data = m.fetch(num, '(RFC822)') | |
| msg = email.message_from_string(data[0][1]) | |
| From = msg['From'] | |
| if From and 'user@domain' not in From: | |
| continue | |
| #date_tuple = email.utils.parsedate_tz(msg['Date']) | |
| #print num, msg['From'], date_tuple, msg['To'] | |
| m.store(num, '+FLAGS', '\\Deleted') | |
| removed += 1 | |
| if checked % 500 == 0: #or removed % 100 == 0: | |
| print "------------- checked = %d, removed = %d" % (checked, removed) | |
| if removed >= 2500: | |
| break | |
| print "------------- done deleting" | |
| try: | |
| m.expunge() | |
| print "------------- done expunging" | |
| except Exception, e: | |
| print e | |
| try: | |
| m.close() | |
| except Exception, e: | |
| print e | |
| m.logout() | |
| print 'removed =', removed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment