Search code examples
pythonpython-2.7emailimap

Use IMAP4 in python to move mail from a mailbox to another mailbox


I very new in Python, but i need to build a IMAP handler, i have now build so i can get the mails out, and i can save the attached files right now.

the next step i need to move the message after i have readed it and downloaded the attached items to my computer, i have build a class to handle it and what happen now you can see in my code here.

class IMAPHandler
    mailFolder = "INBOX"
    mailFolderCopyTo = "INOBX/Parsed"
    localPath = "./tmp"

    """ Defined server, username and password """
    def __init__(self, server, username, password): ...

    """ Connect to your IMAP mailbox """
    def __login(self): ...

    """ Close connection to your IMAP mailbox """
    def __close(self): ...

    """ Get all mailbox messegt """
    def getAll(self):

        self.__login()

        rv, data = self.mailbox.search(None, 'UNSEEN', '(HEADER FROM "{mail-from}")')

        if rv != 'OK':
            print("No messages found!")

        for num in data[0].split():
            rv, data = self.mailbox.fetch(num, '(RFC822)')
            print(rv)

            email_body = data[0][1]
            mail = email.message_from_string(email_body)

            print "["+mail["From"]+"] :" + mail["Subject"]
            print "-"

            self.__saveAttachedFiles(mail)

        self.__close()

    def __saveAttachedFiles(self,mail): ...

after self.__saveAttachedFiles(mail) i need to move the mail-messegt, but i don't know how i do it.


Solution

  • I have trying the most of this day and the resolved are

    """ Move mail messegt to parsed folder after its handle """
    def __moveMailToParsedFolder(self,num):
        mail_uid = num
    
        apply_lbl_msg = self.mailbox.copy(mail_uid, self.mailFolderCopyTo)
    
        if apply_lbl_msg[0] == 'OK':
            self.mailbox.store(mail_uid, '+FLAGS', '\Deleted')
            self.mailbox.expunge()
    

    Now i only need to know why its only take 50% each time....