Exemple #1
0
 def _decode_folder_name(self, name):
     if isinstance(name, int):
         # Some IMAP implementations return integer folder names
         # with quotes. These get parsed to ints so convert them
         # back to strings.
         return str(name)
     if self.folder_encode:
         return imap_utf7.decode(name)
     return name
Exemple #2
0
    def indexOneFolder(self, messages, oldFld, folderName):
        """
        Creates an EmailFolder object and populates its EmailFolder.msgs
        dictionary that maps UID => SHA1, either by copying the UID/SHA1 from
        oldFld (for old messages that were previously backed up), or by
        retrieving the message headers from the server by UID and computing the
        SHA1.

        Returns the created EmailFolder

        @param messages     Could be None.
        @param oldFld       If None, the new folder is fully indexed, otherwise
                            reuse the oldFld data to initialize the new folder.
        @param folderName   Name of the folder to index - mandatory
        """
        folder = EmailFolder(self, folderName)
        if folder.OK:
            status("Indexing: %s\n" % imap_utf7.decode(folderName))
        else:
            logger.error("Unable to select folder: %s" % folderName)
            return None

        if folder.sameUidVal(oldFld):
            msgUIDs = folder.carryOver(oldFld, messages, None)
        else:
            msgUIDs = folder.UIDs

        msgCnt = len(msgUIDs)
        status("Retained %5d message(s). Need to transfer %5d message(s).\n" % (len(folder.msgs), msgCnt))
        i = 0
        try:
            for uid in msgUIDs:
                i += 1
                msg = EmailMsg(self, uid)
                if not msg.OK:
                    logger.error("Could not retrieve UID %d from folder %s", uid, folderName)
                    # TODO: Error handling
                    continue

                folder.msgs[uid] = msg['sha1']
                if messages is not None:
                    sha1 = msg['sha1']
                    if messages.has_key(sha1) and folderName not in messages[sha1]['folder']:
                        messages[sha1]['folder'].append(folderName)
                    else:
                        # Assumes saveAllMsgs was called first, and messages
                        # contains a full list of all current SHA1's
                        logger.warn("New message arrived in %s while indexing %d/%d ?" % (folderName, i, msgCnt))

                progress('\r%.0f%% %d/%d ' % (i * 100.0 / msgCnt, i, msgCnt))
        except:
            status("\n", False)
            logger.debug("Indexed %d/%d" % (i, msgCnt))
            logger.exception("Could not fully index folder %s" % folderName)

        status("\n", False)
        return folder
Exemple #3
0
    def _proc_folder_list(self, folder_data):
        # Filter out empty strings and None's.
        # This also deals with the special case of - no 'untagged'
        # responses (ie, no folders). This comes back as [None].
        folder_data = [item for item in folder_data if item not in ("", None)]

        ret = []
        parsed = parse_response(folder_data)
        while parsed:
            raw_flags, delim, raw_name = parsed[:3]
            parsed = parsed[3:]
            flags = [imap_utf7.decode(flag) for flag in raw_flags]
            ret.append((flags, delim, self._decode_folder_name(raw_name)))
        return ret
Exemple #4
0
    def indexOneFolder(self, messages, oldFld, folderName):
        """
        messages    could be None
        oldFld      could be None - results in full indexing
        """
        folder = EmailFolder(self, folderName)
        if folder.OK:
            status("Indexing: %s\n" % imap_utf7.decode(folderName))
        else:
            # TODO: Error handling
            logger.error("Unable to select folder: %s" % folderName)
            return None

        if folder.sameUidVal(oldFld):
            msgUIDs = folder.carryOver(oldFld, messages, None)
        else:
            msgUIDs = folder.UIDs

        msgCnt = len(msgUIDs)
        status("Retained %5d message(s). Need to transfer %5d message(s).\n" % (len(folder.msgs), msgCnt))
        i = 0
        try:
            for uid in msgUIDs:
                i += 1
                msg = EmailMsg(self, uid)
                if not msg.OK:
                    logger.error("Could not retrieve UID %d from folder %s", uid, folderName)
                    # TODO: Error handling
                    continue

                folder.msgs[uid] = msg['sha1']
                if messages is not None:
                    if messages.has_key(msg['sha1']):
                        messages[msg['sha1']]['folder'].append(folderName)
                    else:
                        # Assumes saveAllMsgs was called first, and messages
                        # contains a full list of all current SHA1's
                        logger.warn("New message arrived in %s while indexing %d/%d ?" % (folderName, i, msgCnt))

                progress('\r%.0f%% %d/%d ' % (i * 100.0 / msgCnt, i, msgCnt))
        except:
            status("\n", False)
            logger.debug("Indexed %d/%d" % (i, msgCnt))
            logger.exception("Could not index folder %s" % folderName)

        status("\n", False)
        return folder
options = imaplib_connect.readconf()
for account in options['account']:
    with imaplib_connect.open_connection(False, **account) as c:
        path = options['path']
        usernamepath = os.path.join(path, account["username"])
        if os.path.isdir(usernamepath) == False:
            os.mkdir(usernamepath)

        typ, data = c.list()
        for line in data:
            flags, delimiter, mailbox_name = parse_list_response(line)

            # 输入参数是bytes类型,返回str类型
            try:
                mailbox_name_utf8 = imap_utf7.decode(
                    mailbox_name.encode("UTF-7"))
            except Exception as err:
                #mailbox_name_utf8 = "INBOX"
                continue 

            mailboxfolder = os.path.join(usernamepath, mailbox_name_utf8)
            if os.path.isdir(mailboxfolder) == False:
                os.mkdir(mailboxfolder)

            try:
                #连接可能会断开,所以选择重新连接
                typ2, data2 = c.select(mailbox_name, readonly=False)
            except Exception as err:
                c = imaplib_connect.open_connection(False, **account)
                typ2, data2 = c.select(mailbox_name, readonly=False)
                print("连接已断开,选择重新连接")
Exemple #6
0
 def _decode_folder_name(self, name):
     if self.folder_encode:
         return imap_utf7.decode(name)
     return name