简体   繁体   中英

How to select a specific mailbox from IMAP server?

I have the following mailboxes on my IMAP server (refer to the attached screenshot). 在此处输入图片说明

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM