python-3.ximapimaplibgmail-imap

How do I select a custom gmail label with special characters using imaplib in Python?


I am trying to select one of my Gmail labels called ""📚 Education/Email zum löschen/Emails zum löschen".

import imaplib

IMAP_SERVER = "imap.gmail.com"
EMAIL = "myemail"
PASSWORD = "myapppassword"

imap = imaplib.IMAP4_SSL(IMAP_SERVER)

imap.login(EMAIL, PASSWORD)

status, messages = imap.select("📚 Education/Email zum löschen/Emails zum löschen", readonly=True)

This gives the following error:

UnicodeEncodeError: 'ascii' codec can't encode character '\U0001f4da' in position 0: ordinal not in range(128)

When trying to encode it with "utf-7" just as I am receiving the encoded labels with the imap.list() command, I get the following error:

import imaplib
from imapclient import imap_utf7

IMAP_SERVER = "imap.gmail.com"
EMAIL = "myemail"
PASSWORD = "myapppassword"

imap = imaplib.IMAP4_SSL(IMAP_SERVER)

imap.login(EMAIL, PASSWORD)

label_to_select = imap_utf7.encode("📚 Education/Email zum löschen/Emails zum löschen")


status, messages = imap.select(label_to_select, readonly=True)
imaplib.error: EXAMINE command error: BAD [b'Could not parse command']

How would I be able to select the label with the emoji?

I've tried to search for solutions but could only find them as to how to deal with spaces in label names. Appreciate any help!


Solution

  • My main error was that I had the single and double quotes switched when using imap.select(). It's important that the double quotes are inside the single quotes. My final code down below (a little more complex since I want the user to enter the label name in a simple text file and then use that as the input).

    # Encode the label with UTF-7
    label_to_select = imap_utf7.encode("📚 Education/Email zum löschen/Emails zum löschen")
    
    # Convert the encoded label to a string and remove the bytes formatting characters
    label_to_select = str(label_to_select)[2:-1]
    
    status, messages = imap.select(f'"{label_to_select}"', readonly=True)
    

    this would work just fine too:

    status, messages = imap.select('"&2D3c2g- Education/Email zum l&APY-schen/Emails zum l&APY-schen"', readonly=True)
    

    If you need the encoded version you can call imap.list().