uid fetch get 5 latest emails

To fetch the 5 latest emails using the UID FETCH command in IMAP, you can use the syntax
UID FETCH <start>:<end> (items).
Because UIDs are assigned in ascending order, the messages with the highest UIDs are the most recent. 

Standard Method (Sequence Numbers to UIDs)

Since UID FETCH requires specific UIDs and you may not know the exact five highest UID values, the most reliable approach is to first find the total number of messages (which corresponds to the highest sequence number) and then fetch their UIDs. 

Select the Mailbox: Issue a SELECT INBOX command. The server will return an EXISTS response indicating the total number of messages (e.g., * 100 EXISTS).
Fetch UIDs for the Range: Use the message sequence numbers to get the UIDs of the last five messages. If you have 100 messages, the command would be:
FETCH 96:100 (UID).
Fetch Message Data: Once you have the UIDs (e.g., 501, 502, 503, 504, 505), use the UID FETCH command to get the content:
UID FETCH 501:505 (FLAGS BODY[HEADER.FIELDS (DATE FROM SUBJECT)]) 

Advanced Methods

UID Range with Wildcard: You can attempt to fetch a range using the wildcard *, which represents the highest UID currently in the mailbox.
Example: UID FETCH <some_lower_uid>:* (FLAGS ENVELOPE)
Note: This will fetch all messages from that starting point to the newest, which might be more than five.
IMAP Partial Extension (RFC 9394): If your server supports the PARTIAL extension, you can fetch the last five messages directly in one command:
UID FETCH 1:* (UID FLAGS) (PARTIAL -1:-5). 

Implementation in Common Languages

Python (imaplib): Use search(None, 'ALL') to get all IDs, then slice the last five.
PHP (imap_search): Typically used with filters, but you can sort by date and limit the results.
MailCore2 (iOS/macOS): Uses fetchMessagesByNumberOperationWithFolder to target specific ranges. 