Data responses in IMAP using Python
<p>Dear users of Stack Overflow,</p>

<p>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:</p>

<p><a href="http://i.stack.imgur.com/P9V0D.png" rel="nofollow">Discription 1</a></p>

<p><a href="http://i.stack.imgur.com/oOzmR.png" rel="nofollow">Discription 2</a></p>

<p>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). </p>

<p>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):</p>

<pre><code>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??
</code></pre>

<p>Hopefully Iâm not the only one who would like to know this!</p>

<p>Kind regards,</p>

<p>I. Van Dijck</p>

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

<pre><code>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
</code></pre>

<p>The select function returns the number from the EXISTs response.  Almost all imaplib commands return two values, <code>type</code>, and <code>data</code>.</p>

<p>From the <a href="https://docs.python.org/2/library/imaplib.html" rel="nofollow">documentation</a></p>

<blockquote>
  <p>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).</p>
</blockquote>

<p><code>select</code>, 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:</p>

<pre><code>typ, dat = inbox.select()
number_of_messages = int(dat[0])
</code></pre>

python imap gmail-imap imaplib