get last email with curl imap

to retrieve the last (most recent) email using curl with IMAP, can use the wildcards provided by the IMAP URL format. [1, 2]

Direct Command

The simplest way to fetch the most recent email body is to use UID=* in the URL. [1]

B
curl --url "imaps://://example.com*" \
--user "user@example.com:password" 

How it Works

imaps://: Specifies a secure IMAP connection (usually port 993).
/INBOX/: Selects the target mailbox.;
UID=*: The asterisk * is a wildcard that instructs the server to fetch the last message (the one with the highest UID). [1, 2, 3, 4, 5]

Variations

If you only need specific parts of the most recent email, you can append a SECTION parameter. [1]

Fetch only the Subject:

B
curl --url "imaps://://example.com" \
--user "user@example.com:password" 

Fetch only the Text Body:

B
curl --url "imaps://://example.com" \
--user "user@example.com:password" 

Important Notes

Credentials: If your password contains special characters, wrap the credentials in quotes or use a .netrc file for better security.
Seen Status: By default, fetching a message via curl will mark it as "Seen" on the server.
Alternative Discovery: If you don't know the exact UID and UID=* doesn't work for your specific server, you can first check the message count using a custom command:
curl --url "imaps://imap.example.com" -X "STATUS INBOX (MESSAGES)" --user "user:pass"

