Home > Back-end >  Some emails use / and some emails use . when listing the subfolders, how to account for this?
Some emails use / and some emails use . when listing the subfolders, how to account for this?

Time:06-14

I'm making a script that records email receipts in a Google Sheets, it allows the user to log in to their selected email, then prompts them to type in the mailbox folder where they want the script to run.

The thing is if you use IMAP4.list() you will notice some email services list their folders like INBOX.folder while others list it as INBOX/folder

I've tried having the code search the IMAP4.list() to determin whether the server is using . or /

I've tried doing try, except but if it fails the IMAP4.select() it doesnt move onto the except and if I pass and do two try, excepts it simply uses the latter one.

I feel like there isn't enough information on https://docs.python.org/3/library/imaplib.html to help me understand if there are arguments I can use to narrow the search

CodePudding user response:

The hierarchy separator is included in the LIST response. See e.g. the RFC, which shows an IMAP server response like this:

* LIST (\Noselect) "/" ~/Mail/foo

The second field of the response ("/") is the hierarchy separator.

In Python, calling the list method effectively gives you the raw IMAP response. Recall that list returns a (status, data) tuple, so:

>>> res = server.list()
>>> res[0]
'OK'
>>> len(res[1])
83

If we take at mailbox in the response:

>>> res[1][0]
b'(\\HasNoChildren) "/" "INBOX"'

We find the mailbox separator in the expected location.

Parsing that out will require a little work; imaplib doesn't provide any facilities for parsing IMAP responses (at least, it didn't last I looked), so you'll have to figure out how to extract that value.

CodePudding user response:

from imap_tools import MailBox

with MailBox('imap.mail.com').login('[email protected]', 'pwd') as mailbox:
    for f in mailbox.folder.list('INBOX'):
        print(f)  
        # FolderInfo(name='INBOX|cats', delim='|', flags=('\\Unmarked', '\\HasChildren'))

output:

FolderInfo(name='Archive', delim='/', flags=('\\Archive', '\\HasNoChildren'))
FolderInfo(name='Bulk', delim='/', flags=('\\Junk', '\\HasNoChildren'))
FolderInfo(name='Draft', delim='/', flags=('\\Drafts', '\\HasNoChildren'))
FolderInfo(name='Inbox', delim='/', flags=('\\HasNoChildren',))
FolderInfo(name='Sent', delim='/', flags=('\\Sent', '\\HasNoChildren'))
FolderInfo(name='Trash', delim='/', flags=('\\Trash', '\\HasNoChildren'))
FolderInfo(name='test', delim='/', flags=('\\HasChildren',))
FolderInfo(name='test/base', delim='/', flags=('\\HasNoChildren',))
FolderInfo(name='test/temp1', delim='/', flags=('\\HasNoChildren',))
FolderInfo(name='test/temp2', delim='/', flags=('\\HasNoChildren',))

Ext lib: https://pypi.org/project/imap-tools/

I am author

  • Related