Skip to content

Instantly share code, notes, and snippets.

@juananpe
Created May 25, 2019 18:46
Show Gist options
  • Save juananpe/85cfc82782ace2a96179d0b992f51a5e to your computer and use it in GitHub Desktop.
Save juananpe/85cfc82782ace2a96179d0b992f51a5e to your computer and use it in GitHub Desktop.
import imaplib
import datetime
def connect_imap():
m = imaplib.IMAP4_SSL("imap.gmail.com") # server to connect to
print("{0} Connecting to mailbox via IMAP...".format(datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")))
m.login('tucorreo@gmail.com', 'tupassword')
return m
def move_to_trash_before_date(m, folder, days_before):
no_of_msgs = int(m.select(folder)[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.date.today() - datetime.timedelta(days_before)).strftime("%d-%b-%Y") # date string, 04-Jan-2013
typ, data = m.search(None, '(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))
m.store("1:{0}".format(no_msgs_del), '+X-GM-LABELS', '\\Trash') # move to trash
#print("Deleted {0} messages.".format(no_msgs_del))
else:
print("- Nothing to remove.")
return
def empty_folder(m, folder, do_expunge=True):
print("- Empty '{0}' & Expunge all mail...".format(folder))
m.select(folder) # select all trash
m.store("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
else:
print("Expunge was skipped.")
return
def disconnect_imap(m):
print("{0} Done. Closing connection & logging out.".format(datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")))
m.close()
m.logout()
#print "All Done."
return
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
disconnect_imap(m_con)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment