Search code examples
pythongmailimap

IMAP, view email's labels, Python & Gmail


How can I see what labels an email has?

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('myaccountxyz@gmail.com', mypassword)

mail.select("my-folder") # finds emails with this label
result, data = mail.uid('search', None, 'all')

for email_uid in data[0].split():
    result, data_single = mail.uid('fetch', email_uid, '(RFC822)')
    raw_email = data_single[0][1]
    email_message = email.message_from_string(raw_email)
    sender = email_message['From']

    # get list of this email's labels

Solution

  • I haven't tried this code myself, but according to Google IMAP Extensions, you should be able to just fetch the X-GM-LABELS item:

    typ, dat = mail.uid('fetch', email_uid, 'X-GM-LABELS')