Search code examples
pythonimapgmail-imapimaplib

Data responses in IMAP using Python


Dear users of Stack Overflow,

My question is about how to use the returned data of an imap command in python (in this case printing the amount of messages in your inbox). What I was able to find on the internet is limited to the following two descriptions:

Discription 1

Discription 2

Reading these explanations, I still have no idea how to use the EXISTS response as I’ve just started programming (one semester of C programming at Uni). So, if someone could help me understand how the responses of imap commands can be used in python, that would be awesome. I do prefer to understand the principle of the responses instead of solving just this one-time issue so I’ll be able to use responses in different situations (and other people might be able to apply it too then).

The (basic) code I’ve written so far on my Raspberry Pi including the point where I'm stuck with EXISTS (between the two question marks):

import imaplib
server = imaplib.IMAP4_SSL(‘imap.gmail.com’)
server.login(‘USERNAME’, ‘PASSWORD’)
server.list()
server.select(‘inbox’)

print ‘%d messages in the inbox’ %d ??EXISTS??

Hopefully I’m not the only one who would like to know this!

Kind regards,

I. Van Dijck

P.S. My updated code is as follow (the error is: TypeError: not all arguments converted during string formatting):

import imaplib
server = imaplib.IMAP4_SSL('imap.gmail.com')
server.login('USERNAME', 'PASSWORD')
server.list()
server.select('inbox')
number_of_messages = server.select("inbox")

print '%s messages' % number_of_messages

Solution

  • The select function returns the number from the EXISTs response. Almost all imaplib commands return two values, type, and data.

    From the documentation

    Each command returns a tuple: (type, [data, ...]) where type is usually 'OK' or 'NO', and data is either the text from the command response, or mandated results from the command. Each data is either a string, or a tuple. If a tuple, then the first part is the header of the response, and the second part contains the data (ie: ‘literal’ value).

    select, in it's list of data returns the number from the EXISTS response, apparently as a string. You will need to extract the item from the list, and convert it to a string:

    typ, dat = inbox.select()
    number_of_messages = int(dat[0])