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.
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()
In my specific case, printing "uids" gives the following list
[b'1', b'3', b'4', b'7', b'8', b'9', b'10', b'11']
Manually checking the mails by writing a list [b'1', b'2'..., b'11']
and fetching the email subjects, I find out that there are unique mails for the following UIDs:
[b'1', b'2' OR b'3', b'4', b'5', b'6', b'7', ONE OF b'8' to b'11']
b'1'
and b'2'
returns the same mail, b'6'
is missing, and b'8'
through b'11
returns the same mail
Searching around here before asking this, I came across this question: Download attachments from gmail. The answer had this bit of code that fetches id for all mails of a folder:
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
Similar to my code, just not using the uid
method. However, in my case, this makes the list:
[b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8']
So also not correct. Another answer I found Imaplib with GMail offset uids writes:
It seems like
M.uid
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:
rv, data = M.uid("search", None, 'UID', '29540:*')
And in a comment:
rv, data = M.uid("search", None, '(UID 29540:*)')
But both return an error for me: UID command error: BAD [b'Could not parse command']
What am I doing wrong, and/or is there a better way?