Skip to content

Instantly share code, notes, and snippets.

Created May 25, 2019
What would you like to do?
import imaplib
import datetime
def connect_imap():
m = imaplib.IMAP4_SSL("") # server to connect to
print("{0} Connecting to mailbox via IMAP...".format("%Y-%m-%d %H:%M:%S")))
m.login('', 'tupassword')
return m
def move_to_trash_before_date(m, folder, days_before):
no_of_msgs = int([1][0]) # required to perform search, m.list() for all lables, '[Gmail]/Sent Mail'
print("- Found a total of {1} messages in '{0}'.".format(folder, no_of_msgs))
before_date = ( - datetime.timedelta(days_before)).strftime("%d-%b-%Y") # date string, 04-Jan-2013
typ, data =, '(BEFORE {0})'.format(before_date)) # search pointer for msgs before before_date
if data != ['']: # if not empty list means messages exist
no_msgs_del = data[0].split()[-1] # last msg id in the list
print("- Marked {0} messages for removal with dates before {1} in '{2}'.".format(no_msgs_del, before_date, folder))"1:{0}".format(no_msgs_del), '+X-GM-LABELS', '\\Trash') # move to trash
#print("Deleted {0} messages.".format(no_msgs_del))
print("- Nothing to remove.")
def empty_folder(m, folder, do_expunge=True):
print("- Empty '{0}' & Expunge all mail...".format(folder)) # select all trash"1:*", '+FLAGS', '\\Deleted') # Flag all Trash as Deleted
if do_expunge: # See Gmail Settings -> Forwarding and POP/IMAP -> Auto-Expunge
m.expunge() # not need if auto-expunge enabled
print("Expunge was skipped.")
def disconnect_imap(m):
print("{0} Done. Closing connection & logging out.".format("%Y-%m-%d %H:%M:%S")))
#print "All Done."
if __name__ == '__main__':
m_con = connect_imap()
move_to_trash_before_date(m_con, '[Gmail]/All Mail', 3650) # inbox cleanup, older_than:10y
empty_folder(m_con, '[Gmail]/Trash', do_expunge=True) # can send do_expunge=False, default True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment