Question

I am using imaplib with Python to fetch the contents of my inbox or GMail labels.

My problem is: imaplib returns the UIDs when I'm querying the inbox, but not my email labels.

If I query the inbox, I get UIDs:

inbox EMAIL_UIDS: 24408 24599 25193 25224 25237 25406 25411 25412 25413 25415

But if I query my label "New" (which contains two of the messages in the inbox, thus should contain two of the above UIDs), I get only the ordered indices:

New EMAIL_UIDS: 1 2

My code is:

#Main file
if folder_name is None:
    email_uids = obtain_inbox_email_uids(mail)
else:
    email_uids = obtain_folder_email_uids(folder_name,mail)
email_uids = list(email_uids)

and:

#Email utilities file
def obtain_folder_email_uids(folder_name, mail):
    """
    Given an IMAP instance,
    return the UIDs of the emails in a specific folder.
    """

    mail.select(folder_name)

    result, data = mail.uid('search', None, "ALL")
    print "RESULT, DATA",result,data
    email_uids = data[0]

    print folder_name,"EMAIL_UIDS:",email_uids
    email_uids = email_uids.split(" ")
    email_uids = reversed(email_uids)

    return email_uids

def obtain_inbox_email_uids(mail):
    """
    Given an IMAP instance,
    return the UIDs of the inbox emails.
    """

    return obtain_folder_email_uids('inbox', mail)

Does anybody know why imaplib returns UIDs for the inbox but ordered indices for the specific labels, and how can I get it to return the UIDs?

Thank you

Was it helpful?

Solution

Found out the problem. The UIDs were being returned correctly.

My problem was: I was using a function to manually fetch an email based on its UID. So in the case of the inbox, I obtained the UIDs, then used this function to obtain each mail in specific. With each label, the same.

However, each specific email was being returned for the inbox, but in the case of a label, I wasn't able to fetch each mail. I therefore assumed I wasn't passing the correct UID to the function.

My mistake was not related. Inside the function to fetch a specific mail, instead of fetching it from the label in question, I was always fetching from the inbox.

So in this case, for the inbox I would obtain a list of UIDs, then use this function to successfully obtain each mail in specific, but in the case of a specific GMail label I would obtain the list of UIDs, then fail to fetch each specific mail because I was performing select on the inbox.

Changed the select from the inbox to the specific label inside the function that fetches each specific mail, and now works perfect.

OTHER TIPS

IMAP UIDs are unique per mailbox. If you just created the mailbox, 1 and 2 are almost certainly the correct UIDs for those two messages. Why do you think they aren't?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top