这是我编写的一个程序,基于上面的代码:
https://github.com/AndrewDJohnson/py-purge-email/
import imaplib
import sys
import traceback
import datetime
import re
from getpass import getpass
"""
PyPurge Email V1.0
==================
Andrew Johnson
ad.johnson@ntlworld.com
06 Nov 2019
This Python 3 program will scan an email account using IMAP for messages older than
a certain age and delete them.
Old email can be deleted from all folders or each folder.
Because of the length of time bulikng deleting takes, folders can be scanned first
then the deletions can be left running (which might take several hours for many
thousands of messages.)
After running this, you may need to "empty" your deleted items/Trash folder to recover the space.
With hotmail/live/outlook accounts (i.e. online Microsoft ones) you will need to manually empty "recoverable items" too.
This is done within the "deleted items" folder when viewing your webmail.
"""
host = ''
port = 993
user=''
password = ''
imap_hosts=[["GMail","imap.gmail.com","Trash"],
["Hotmail, Live, Outlook","imap-mail.outlook.com","Deleted"],
["Yahoo","imap.mail.yahoo.com","Trash"]]
days_old=365
deleted_mail_folder_name="Trash"
list_response_pattern = re.compile(r'\((?P<flags>.*?)\) "(?P<delimiter>.*)" (?P<name>.*)')
def parse_list_response(line):
flags, delimiter, mailbox_name = list_response_pattern.match(line).groups()
mailbox_name = mailbox_name.strip('"')
if flags.lower().find("noselect") >= 0:
mailbox_name=""
return (flags, delimiter, mailbox_name)
def do_folders(imap,days_old,check_or_del,deletion_list):
if check_or_del != "check":
resp = input ("Are you sure you want to delete emails? (Enter 'Yes') to confirm)>>>")
if resp.lower()!="yes":
return
resp, data = imap.list()
totalMsgs = 0
actioned= "Nothing to do!"
if resp == 'OK':
for mbox in data:
flags, separator, name = parse_list_response(bytes.decode(mbox))
if name == "":
continue
print ("Checking folder: ",name)
imap.select('"{0}"'.format(name), (check_or_del=="check"))
before_date = (datetime.date.today() - datetime.timedelta(days_old)).strftime("%d-%b-%Y")
resp, msgnums = imap.search(None, '(BEFORE {0})'.format(before_date))
msg_count = len(msgnums[0].split())
print('{:<30} : {: d}'.format(name, msg_count))
if (msg_count > 0):
if (check_or_del=="check"):
print ("Delete mail older than {0} in {1} folder? (Enter y to delete)>>> ".format(before_date, name))
resp=input("")
if resp.lower()=='y':
deletion_list.append (name)
totalMsgs = totalMsgs + msg_count
actioned="Total found to Delete:"
continue
else:
actioned="Deleted: "
if name in deletion_list or len(deletion_list) == 0:
totalMsgs = totalMsgs + msg_count
print (msg_count, "messages found with date before ", before_date, "will be moved to trash")
if (msg_count > 50000):
print ("This could take several hours!")
elif (msg_count > 5000):
print ("This could take an hour or more!")
elif (msg_count > 500):
print ("This could take a few minutes")
imap.store("1:{0}".format(msg_count), '+FLAGS', '\\Deleted')
continue
else:
continue
print('{:<30} : {: d}'.format(actioned, totalMsgs))
return (deletion_list)
folder = ''
deletion_list=[]
print ("*********--------****-----***************")
print ("* Python Email Purger - V1.0 - Nove 2019 *")
print ("*********--------****-----***************")
print (" ")
exit_prog=False
input_needed=True
while exit_prog==False:
if user != "":
print ("Server:\t\t", host)
print ("Username:\t",user)
print ("Message Age:\t",days_old)
resp=input("Enter 'y' to use the values above>>> ")
if resp != "y":
user=""
if user == "":
while input_needed:
for i in range (0,len (imap_hosts)):
print (i+1,imap_hosts[i][0], " - ",imap_hosts[i][1])
input_needed=True
host_input=input("Enter imap server name number, as given above, or type the address>>> ")
max_host_index=str(len(imap_hosts))
if len (host_input)==1 and (host_input >"0") and (host_input <= max_host_index):
host=imap_hosts[int(host_input)-1][1]
deleted_mail_folder_name=imap_hosts[int(host_input)-1][2]
input_needed=False
else:
if len(host_input) < 10:
print ("Please enter a valid host address.")
input_needed=True
else:
host=host_input
user=input ("Username:")
print ("Password:")
password=getpass()
input_needed=True
while input_needed:
input_needed=False
resp = input("Deleted messages older than how many days? Default is '365'>>> ")
if len (resp) > 0:
days_old = int (resp)
if days_old == 0:
print ("You must enter a value greater than 0.")
input_needed=True
print ("Connecting to ",host,"...")
imap = None
try:
imap = imaplib.IMAP4_SSL(host, port)
resp, data = imap.login(user, password)
if resp == 'OK':
print ("Logged in... Looking for messages older than", days_old, "days.")
while not resp in ["c","a"]:
resp = input ("Enter 'c' to check each folder, or 'a' to delete from all folders >>>")
if resp=="c":
deletion_list = do_folders(imap,days_old,"check", deletion_list)
deletion_list = do_folders(imap,days_old,"delete", deletion_list)
else:
deletion_list = do_folders(imap,days_old,"delete", deletion_list)
if deleted_mail_folder_name!="":
print("Emptying Trash & Expunge...")
imap.select(deleted_mail_folder_name)
imap.store("1:*", '+FLAGS', '\\Deleted')
imap.expunge()
except:
resp = input ("Something went wrong... enter 'd' to see details, otherwise just press 'Enter' to exit...")
if resp=='d':
print('Error was : {0}'.format(sys.exc_info()[0]))
traceback.print_exc()
print ("Are you any the wiser? :-)")
resp = input ("Enter 'Y' to delete more messages.")
if resp.lower()!='y':
exit_prog=True;
if imap != None:
imap.logout()
imap = None
print ("Finished...")