Search code examples
pythonimapimaplib

How to select a specific mailbox from IMAP server?


I have the following mailboxes on my IMAP server (refer to the attached screenshot).enter image description here

I want to only select the mailbox Folder1 and check if there are any sub-directories. I already tried the following code:

svr = imaplib.IMAP4_SSL(imap_address)
svr.login(user, pwd)
svr.select('inbox') <<<<<<<<<<<<<<<<<
rv, data = svr.search(None, "ALL")
test, folders = svr.list('""', '*')
print(folders)

I thought changing 'inbox' to 'folder1' (statement indicated with arrows) would select Folder1 and then I can retrieve the sub-directories. But nothing happened and still it shows the same result as 'inbox'.

Can somebody help me understand what I am doing wrong here.


Solution

  • As I would not be knowing the name of folder I tried a different approach. I would first collect all the folders in the root directory and then parse them one by one to check if any sub-directory exists.

    root_folders = []
    svr = imaplib.IMAP4_SSL(imap_address)
    svr.login(user, pwd)
    svr.select('inbox')
    response, folders = svr.list('""', '*')
    
    def parse_mailbox(data):
        flags, b, c = data.partition(' ')
        separator, b, name = c.partition(' ')
        return flags, separator.replace('"', ''), name.replace('"', '')
    
    def subdirectory(folder):
        #For directories 'Deleted Items', 'Sent Items', etc. with whitespaces,
        #the name of the directory needs to be passed with double quotes, hence '"' + name + '"'
        test, folders = obj.list('""','"' + name+ '/*"')
        if(folders is not None):
            print('Subdirectory exists') # you can also call parse_mailbox to find the name of sub-directory
    
    for mbox in folders:
        flags, separator, name = parse_mailbox(bytes.decode(mbox))
        fmt = '{0}    : [Flags = {1}; Separator = {2}'
        if len(name.split('/')) > 1:
            continue
        else:
            root_folders.append(name)
    
    for folder in root_folders:
        subdirectory(folder)
    

    Although this is a tailored code from my script, but this should be the solution for the question put up.