'How to have cURL only fetch unread email, and mark it as read after?

I have the script below and it is working fine to get all the email subject lines. Basically it checks a specific folder on my imap server for emails, and outputs the subject line of all the emails into a file.

Now I just need to tweak it a little so that it only fetches the subject line of unread emails, and then marks the email as read when its done so it doesn't get fetched again next time I run the script. That's it, and I cant seem to find the answer anywhere.

#!/bin/sh

id=1

while true  ; do
     echo "Message ${id}"
     curl \
         --url "imaps://mail.domain.com/somefolder;UID=${id};SECTION=HEADER.FIELDS%20(SUBJECT)" \
         --user "user:password" \
         -K tmp >> ontmp || exit
     id=`expr $id + 1`
done


Solution 1:[1]

Suggesting to read this article. A different approach with more robust solution.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dudi Boy