Search code examples
emailimapimaplib

Why are these two IMAP Search results different from one another?


I'm using imaplib, and trying to fetch emails with a certain subject header value.

My code:

    res, tmp = self.mail.uid('search', None, 'HEADER Subject "SUBJECT_HERE"')
    print(tmp)
    print(res)

    print("test 2 goes:")
    rr, tt = self.mail.search(None, 'HEADER Subject "SUBJECT_HERE"')
    print(tt)
    print(rr)

Result:

[b'225 232 323 324 346 366 382 419 420 425 450 463 517 607 670 751 833 911 1043 1129 1133 1134 1287 1350 1799 1854 1957 1960 1962 1991 2005 2040 2071 2110 2119 2121 2153 2158 2182 2188 2189 2228 2230 2239 2249 2334 2335 2372 2378 2396 2435 2497 2567 2568 2573 2574 2575 2632 2633 2634 2648 2649 2709 2785 2819 2821 2828 2829 2868 2885 2895 2902 2906 2920 2993 2997 2998 3000 3001 3009'] OK test 2 goes:
[b'220 227 318 319 340 360 376 413 414 419 444 457 511 601 664 745 827 905 1037 1123 1127 1128 1281 1344 1793 1848 1951 1954 1956 1985 1999 2034 2065 2104 2113 2115 2147 2152 2176 2182 2183 2222 2224 2233 2243 2328 2329 2366 2372 2390 2429 2491 2561 2562 2567 2568 2569 2625 2626 2627 2641 2642 2702 2778 2812 2814 2821 2822 2861 2878 2888 2895 2899 2913 2986 2990 2991 2993 2994 3002'] OK

I thought that those two commands result in the same results.

But as shown above, those two fetch different emails.

What is the difference??


Solution

  • One (SEARCH) returns message sequence numbers (MSN), which are numbered from 1 to N and change as messages are added and deleted. A message that is number 5 now could be number 4 tomorrow if you delete a message before it.

    The other (UID SEARCH) returns UIDs, which do not change as messages are deleted. They're two completely different set of identifiers. A message with UID 5 will remain UID 5 until it is deleted it (or moved, etc.).

    The UID will never reused in that incarnation of a folder. If the folder is deleted and recreated, or the mail server is rebuilt, the folder's UIDVALIDITY should change so you can detect that your cache is no longer valid.