蟒蛇。 Imaplib将邮件移至垃圾箱

时间:2015-07-28 09:25:51

标签: python email imaplib

我已经阅读了一些解决方案,但没有一个显然有用,可能是因为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__'

我不理解,因为当我下次执行程序时,我会移动更多电子邮件,在其他电子邮件中获取错误,执行并最终移动所有内容,但我必须多次执行。

有谁知道发生了什么事?提前谢谢

1 个答案:

答案 0 :(得分:1)

试试这个:

imap.store(mail_to_be_deleted, '+FLAGS', r'(\Deleted)')