[英]Python. Imaplib moving mail to Trash
我已经阅读了一些解决方案,但似乎没有一个有效的方法,也许是因为Gmail,我不确定,问题是我想将我的电子邮件从INBOX移到“已删除邮件”,而我正在这样做:
def process_mailbox():
message={}
M = imaplib.IMAP4_SSL('imap.gmail.com')
try:
M.login('myemail@gmail.com', 'mypassword')
except imaplib.IMAP4.error:
print "LOGIN FAILED!!! "
# ... exit or deal with failure...
rv, mailboxes = M.list()
print mailboxes
if rv == 'OK':
M.select("INBOX")
rv, data = M.search(None, "ALL")
if rv != 'OK':
print "No messages found!"
for num in data[0].split(): #Read all the mails
rv, data = M.fetch(num, '(RFC822)')
if rv != 'OK':
print "ERROR getting message", num
return
msg = email.message_from_string(data[0][1])
#print 'Subject %s: %s' % (num, msg['Subject'])
message['Subject']=msg['Subject']
print 'Subject: '+message['Subject']
if msg.get_content_type() == "text_plain": #No Multipart messages
body = msg.get_payload()
message['Body']=body
else: #Multipart messages
for part in msg.walk():
if part.get_content_type() == "text/plain": # ignore attachments/html
message['Body']=body
#print message['Body']
date_tuple = email.utils.parsedate_tz(msg['Date'])
if date_tuple:
local_date = datetime.datetime.fromtimestamp(
email.utils.mktime_tz(date_tuple))
print "Local Date:", local_date.strftime("%Y-%m-%d")
message['Date']=local_date.strftime("%Y-%m-%d")
#send_mail(message)
#insert_vulnerability_mail(message['Subject'],message['Date'],message['Body'].encode('utf-8'))
# M.store(num, '+FLAGS', '\\Deleted')
M.copy(num,'[Gmail]/Trash')
M.close()
M.logout()
因此,如您所见,它是:M.copy(num,'[[Gmail] / Trash')),结果是我移动了一些电子邮件,可以说,如果我有7个,我从7个中移了4个,那么我得到这个错误:
Traceback (most recent call last):
File "mail.py", line 116, in <module>
process_mailbox()
File "mail.py", line 75, in process_mailbox
msg = email.message_from_string(data[0][1])
TypeError: 'NoneType' object has no attribute '__getitem__'
我不明白,因为当我下次执行程序时,我移动了更多的电子邮件,收到另一封电子邮件的错误,执行了,最终我移动了所有内容,但是我必须执行几次。
有人知道发生了什么吗? 谢谢你提前
尝试这个:
imap.store(mail_to_be_deleted, '+FLAGS', r'(\Deleted)')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.