title: Imaplib search returns wrong UIDs after moving some mails to trash
body: <p>I am trying to get all the UID's of the INBOX folder in a gmail account using imaplib (account is new for testing purposes). It worked fine at first (i.e. when I had only sent mails to the account), but after moving some mails to trash, my code now returns both a wrong amount of UIDs (8, with 7 emails in the inbox folder), while also missing a UID.</p>
  
  <pre><code>con = imaplib.IMAP4_SSL(imap_server, imap_port)
  con.login(user, password)
  con.select("INBOX")
  result, numbers = con.uid('search', None, 'ALL')
  uids = numbers[0].split()
  </code></pre>
  
  <p>In my specific case, printing "uids" gives the following list</p>
  
  <pre><code>[b'1', b'3', b'4', b'7', b'8', b'9', b'10', b'11']
  </code></pre>
  
  <p>Manually checking the mails by writing a list <code>[b'1', b'2'..., b'11']</code> and fetching the email subjects, I find out that there are unique mails for the following UIDs:</p>
  
  <pre><code>[b'1', b'2' OR b'3', b'4', b'5', b'6', b'7', ONE OF b'8' to b'11']
  </code></pre>
  
  <p><code>b'1'</code> and <code>b'2'</code> returns the same mail, <code>b'6'</code> is missing, and <code>b'8'</code> through <code>b'11</code> returns the same mail</p>
  
  <p>Searching around here before asking this, I came across this question: <a href="https://stackoverflow.com/questions/348630/how-can-i-download-all-emails-with-attachments-from-gmail?lq=1">Download attachments from gmail</a>. The answer had this bit of code that fetches id for all mails of a folder:</p>
  
  <pre><code>resp, items = m.search(None, "ALL") # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)
  items = items[0].split() # getting the mails id
  </code></pre>
  
  <p>Similar to my code, just not using the <code>uid</code> method. However, in my case, this makes the list:</p>
  
  <pre><code>[b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8']
  </code></pre>
  
  <p>So also not correct. Another answer I found <a href="https://stackoverflow.com/questions/34435872/imaplib-with-gmail-offsets-uids">Imaplib with GMail offset uids</a> writes:</p>
  
  <blockquote>
    <p>It seems like <code>M.uid</code> simply specifies that the return value will be UID's, so it is still necessary to specify that the parameters sent will be UID's and not message ID's. This fixes it:</p>
  </blockquote>
  
  <pre><code>rv, data = M.uid("search", None, 'UID', '29540:*')
  </code></pre>
  
  <p>And in a comment:</p>
  
  <pre><code>rv, data = M.uid("search", None, '(UID 29540:*)')
  </code></pre>
  
  <p>But both return an error for me: <code>UID command error: BAD [b'Could not parse command']</code></p>
  
  <p>What am I doing wrong, and/or is there a better way?</p>