uid fetch inbox messages imap example

To fetch messages from an IMAP inbox using Unique Identifiers (UIDs), you must prefix standard IMAP commands with the UID keyword. Unlike message sequence numbers, UIDs are permanent and do not change even if other messages are deleted from the folder. 

Raw IMAP Protocol Example

To fetch a specific message (e.g., UID 101) or a range:

Select Folder: A1 SELECT INBOX
Fetch by UID: A2 UID FETCH 101 (RFC822)RFC822
returns the full message including headers and body.
To fetch multiple UIDs: A3 UID FETCH 101:105 (FLAGS ENVELOPE). 

Python Example (imaplib)
Python's standard library requires using the .uid() method to wrap commands

import imaplib

# Connect and login
mail = imaplib.IMAP4_SSL("imap.example.com")
mail.login("user@example.com", "password")
mail.select("INBOX")

# 1. Search for UIDs of unread messages
# Returns: ('OK', [b'101 102 103'])
result, data = mail.uid('search', None, "UNSEEN")
uids = data[0].split()

# 2. Fetch the body of a specific UID
# Use '(RFC822)' for the full email or '(BODY.PEEK[])' to not mark as seen
for uid in uids:
    result, data = mail.uid('fetch', uid, '(RFC822)')
    raw_email = data[0][1]
    print(f"Fetched UID {uid.decode()}")

mail.logout()

Pythlon example

Common UID Fetch Parameters

Parameter 

DescriptionUID FETCH <id> (RFC822) Fetches the entire message (headers + body).
UID FETCH <id> (ENVELOPE) Fetches metadata like Subject, From, To, and Date.
UID FETCH <id> (BODY.PEEK[]) Fetches the body without marking the message as \Seen.
UID FETCH <id> (FLAGS) Returns the current flags (e.g., \Seen, \Answered).

Key Concepts

UID vs. Sequence Number: Sequence numbers (1, 2, 3...) shift when emails are deleted; UIDs remain constant for the life of the message in that folder.
UIDVALIDITY: This value is returned when you select a folder. If it changes, all previously stored UIDs for that folder are invalid and must be refetched.
Range Syntax: Use : to define ranges (e.g., 500:* fetches everything from UID 500 to the newest message).

