imap - 如何删除邮件
我该怎么从邮箱里删除消息呢?我用这个代码,但信件没有被删除。抱歉我的英语不好。
def getimap(self,server,port,login,password):
import imaplib, email
box = imaplib.IMAP4(server,port)
box.login(login,password)
box.select()
box.expunge()
typ, data = box.search(None, 'ALL')
for num in data[0].split() :
typ, data = box.fetch(num, '(UID BODY[TEXT])')
print num
print data[0][1]
box.close()
box.logout()
9 个回答
9
这是我用的方法,速度非常快,因为我不是一个个删除邮件,而是直接传递邮件的列表索引。这个方法适用于个人的Gmail和企业版的Gmail(Google Apps for Business)。首先,它会选择要使用的文件夹或标签,使用m.list()可以查看所有可用的选项。接着,它会搜索一年前的邮件,然后将这些邮件移动到垃圾箱。最后,它会给垃圾箱里的所有邮件加上删除标记,并彻底清除所有内容:
#!/bin/python
import datetime
import imaplib
m = imaplib.IMAP4_SSL("imap.gmail.com") # server to connect to
print "Connecting to mailbox..."
m.login('gmail@your_gmail.com', 'your_password')
print m.select('[Gmail]/All Mail') # required to perform search, m.list() for all lables, '[Gmail]/Sent Mail'
before_date = (datetime.date.today() - datetime.timedelta(365)).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 = data[0].split()[-1] # last msg id in the list
print "To be removed:\t", no_msgs, "messages found with date before", before_date
m.store("1:{0}".format(no_msgs), '+X-GM-LABELS', '\\Trash') # move to trash
print "Deleted {0} messages. Closing connection & logging out.".format(no_msgs)
else:
print "Nothing to remove."
#This block empties trash, remove if you want to keep, Gmail auto purges trash after 30 days.
print("Emptying Trash & Expunge...")
m.select('[Gmail]/Trash') # select all trash
m.store("1:*", '+FLAGS', '\\Deleted') #Flag all Trash as Deleted
m.expunge() # not need if auto-expunge enabled
print("Done. Closing connection & logging out.")
m.close()
m.logout()
print "All Done."
24
我觉得你应该先把要删除的邮件标记出来,比如:
for num in data[0].split():
box.store(num, '+FLAGS', '\\Deleted')
box.expunge()
40
这是一个可以用来删除你收件箱里所有邮件的有效代码:
import imaplib
box = imaplib.IMAP4_SSL('imap.mail.microsoftonline.com', 993)
box.login("user@domain.com","paswword")
box.select('Inbox')
typ, data = box.search(None, 'ALL')
for num in data[0].split():
box.store(num, '+FLAGS', '\\Deleted')
box.expunge()
box.close()
box.logout()