1

I am trying to fetch my Gmail account's folder (or it terms of Google, label) names using python and IMAP protocol. To achieve this, I have the following code (omitting exception handling and other details for simplicity):

mail = imaplib.IMAP4_SSL('imap.gmail.com')
rv, data = mail.login(EMAIL_ACCOUNT, psw)
rv, folders = mail.list()

if rv != 'OK':
    for folder in folders:
        list_response_pattern = re.compile(r'\((?P<flags>.*?)\) "(?P<delimiter>.*)" (?P<name>.*)')
        folder = folder.decode("utf-8")
        flags, delimiter, name = list_response_pattern.match(folder).groups()
        name = mailbox_name.strip('"')
        print(name)

The output is the list of my mailboxes ("INBOX", "Junk", "Important", etc). However, the issue with this code is that if the mailbox name is in a language other than English (say, Russian), I get strange strings instead of real names (I guess, this is sort of encoding). For example, one of my mailboxes is named "Личное". Instead of "Личное", I get something like '&BBsEOARHBD0EPgQ1' in the output.

Some time ago, someone already asked an identical question, but it remains unanswered up to now. I decided to repeat the question, because I have spent a whole day trying to google this. And nothing...Help me please. I am completely stuck at this stage.

P.S. It looks like in PHP, there's a function for solving this issue

Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121

1 Answers1

1

You can use from imapclient import imap_utf7 to decode bytes to cyrrillic, than split name with '|'. Like:

from imapclient import imap_utf7
# Вывожу список папок
for folder in mail.list()[1]:
    # b'(\\Marked \\HasNoChildren) "|" "&BB0EEAQRBB4EIA-"'
    decoded_folder = imap_utf7.decode(folder)
    # (\Marked \HasNoChildren) "|" "НАБОР"
    folder_name = decoded_folder.split(' "|" ')
    # "НАБОР"
sortas
  • 1,527
  • 3
  • 20
  • 29