由于我不知道文件夹的名称,我尝试了另一种方法。我首先收集根目录中的所有文件夹,然后逐个解析它们,以检查是否存在任何子目录。
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)
虽然这是我脚本中定制的代码,但这应该是提出的问题的解决方案。