如何从 IMAP 服务器 select 指定邮箱?

How to select a specific mailbox from IMAP server?

我的 IMAP 服务器上有以下邮箱(请参阅随附的屏幕截图)。

我只想select邮箱Folder1,看看有没有子目录。我已经尝试过以下代码:

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)

我认为将 'inbox' 更改为 'folder1'(用箭头表示的语句)会 select Folder1 然后我可以检索子目录。但什么也没发生,它仍然显示与 'inbox' 相同的结果。

谁能帮我理解我做错了什么。

因为我不知道文件夹的名称,所以我尝试了另一种方法。我会先收集根目录下的所有文件夹,然后一个一个解析,看有没有子目录存在。

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)

虽然这是根据我的脚本定制的代码,但这应该是提出的问题的解决方案。