由于163有封数限制,所以要进行自动清理
#!/usr/bin/python #-*- encoding: utf-8 -*- import imaplib import time host = 'imap.qiye.163.com' username = '账号' password = "密码" debug=1 #保留的邮件封数和一次删除邮件的封数 mail_num=1000 conn = imaplib.IMAP4_SSL("imap.qiye.163.com",993) conn.login(username,password) print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) if conn.list("")[0] == 'OK': for i in conn.list("")[1]: #获取邮箱列表 mailbox_name=i.replace('"','').split(' ')[2] print(mailbox_name) print(conn.select(mailbox_name)) #发现有时候一次删除不干净多清除几次,直到邮件封数等于小于1000封 while int(conn.select(mailbox_name)[1][0]) > mail_num: mailbox_num_status=conn.select(mailbox_name) #邮件封数 print(mailbox_num_status) #邮件数大于1000执行 if mailbox_num_status[0] == 'OK' and int(mailbox_num_status[1][0]) > mail_num: #获取所有邮件 mailbox_type,mailbox_data=conn.search(None, 'ALL') #获取大于1000封的的邮件删除 mail_id=[] #获取id msgList = sorted(mailbox_data[0].split()) #循环总数 for_num=1 #临时存储 tmp=[] #计算循环次数大于1000则把tmp数据加入到mail_id num=0 for i in msgList: tmp.append(i) num+=1 for_num+=1 if num >= mail_num: num=0 mail_id.append(tmp) tmp=[] for_num+=1 elif for_num >=int(len(msgList)-mail_num): #print(for_num) mail_id.append(tmp) break #删除邮件 for i in mail_id: #print(",".join(i)) if i != '': #标记删除 conn.store(",".join(i), '+FLAGS', '\Deleted') #执行删除重置id conn.expunge() conn.logout() else: print("Error login")