Python -根据条件搜索不同的imap收件箱

w51jfk4q  于 2023-05-27  发布在  Python
关注(0)|答案(4)|浏览(164)

有没有一种方法可以使用pythonimap4库根据条件搜索不同的收件箱?我只是不能把我的头绕在一个方法来检查某些子文件夹的基础上的条件。到现在为止,我从“收件箱”中选择子文件夹如下:

imap = imaplib.IMAP4_SSL(host=imap_host)
imap.login(imap_user, imap_pass)

unseen_mails = imap.select('Inbox.Private.folder1')

# this is the second subfolder within "Private"
# unseen_mails = imap.select('Inbox.Private.folder2')

unseen_mails = imap.search(None, '(UNSEEN)')
unseen_mails = unseen_mails[1]
print(unseen_mails)

如果有人能弄清楚我的大脑停止运作的地方会很高兴。

w8f9ii69

w8f9ii691#

imap.list()列出所有文件夹和子文件夹,imap.list(directory = 'Inbox')列出Inbox的所有子文件夹。然后,您可以提取文件夹名称并搜索名称中包含/的所有文件夹,以找到子文件夹。

for folder in (imap.list()[1]):
    folder = folder.decode()                        # folder = '(\Marked \HasNoChildren) "/" "Inbox/Privare/Subfolder1"'
    flags, name = folder.split(' "/" ')             # name = 'Inbox/Private/Subfolder1'

    if '/' in name:
        split_val = name.split('/')
        folderName = split_val[-1]                  # folderName = 'Subfolder1'
        parents = split_val[0:-1]                   # parents = ['Inbox', 'Private']

    flags = flags.split('\\')
    flags.remove(flags[0])
    flags = [each.strip(' )') for each in flags]    # flags = ['Marked', 'HasChildren']

name = 'Inbox'    # Example of fetching list for directory
typ, data = imap.list(directory = name) 

# [ b'(\\Marked \\HasChildren) "/" "Inbox"',
#   b'(\\HasNoChildren) "/" "Inbox/Subfolder"' ]

希望这个能帮上忙

o4hqfura

o4hqfura2#

谢谢你们的帮助。我自己也想明白了。当你获取收件箱的状态时,你会得到一个dict,dict[1]是未读邮件的数量。如果它是空的,它只是返回“[b'']”,所以我写了一个if子句,它将我的输出与空收件箱no_mails = [b'']的输出进行比较,并告诉代码在所有子文件夹中运行这个。

rggaifut

rggaifut3#

from imap_tools import MailBox
with MailBox('imap.mail.com').login('test@mail.com', 'password') as mailbox:
    # get all folders
    for f in mailbox.folder.list():
        print(f['name'])
    # get INBOX subfolders
    for f in mailbox.folder.list('INBOX'):
        print(f['name'])

https://github.com/ikvk/imap_tools

a64a0gku

a64a0gku4#

我遇到了这个答案,试图使它只会列出子文件夹内的收件箱,而不是所有文件夹。例如,如果文件夹设置为;

-INBOX
--folder1
---folder1-1
---folder1-2
--folder2

我只需要folder 1和folder 2,而不是folder 1 -1和folder 1 -2。做;

for folder in imap.list(pattern="/%")[1]:
    print(folder.decode().split(' "/" ')[1])

印刷品

INBOX/folder1
INBOX/folder2

https://readthedocs.org/projects/imapclient/downloads/pdf/master/
“%匹配0个或多个字符,但文件夹分隔符”(“/")除外。

相关问题