Get the number of unread emails
I am working on a tiny piece of software to check if there are >0 UNread emails on my mail account (any free mail, imap).
I am coding in C, but I'm not an expert...
How can C's imap4-api (or just sth comparable) be used to check if th开发者_如何学JAVAere are any unread emails (without fetching them)?
Thanks in advance
There are several ways to do it. I'll explain at the protocol level, and I'd bet that your C library will expose at least one of these...
In general the most efficient way is to issue the STATUS command and ask for the folder's UNSEEN count:
A001 STATUS "INBOX" (UNSEEN)
* STATUS "INBOX" (UNSEEN 16)
A001 OK STATUS completed
You can SELECT the folder and check whether the [UNSEEN] response code comes back on an untagged OK:
A002 SELECT INBOX
* 223 EXISTS
* 223 RECENT
* OK [UNSEEN 1] mailbox contains unseen messages
* OK [UIDVALIDITY 1] UIDs are valid for this mailbox
* OK [UIDNEXT 554] next expected UID is 554
* FLAGS (\Answered \Deleted \Draft \Flagged \Seen $Forwarded $MDNSent)
* OK [PERMANENTFLAGS (\Answered \Deleted \Draft \Flagged \Seen $Forwarded $MDNSent \*)] junk-related flags are not permanent
* OK [HIGHESTMODSEQ 504] modseq tracked on this mailbox
A002 OK [READ-WRITE] SELECT completed
Once the folder has been selected, you can issue a SEARCH command and ask for UNSEEN messages (if anything comes back, you've got unread mail):
A003 SEARCH UNSEEN
* SEARCH 1 2 12 13 14 155 156 157 158 159 183 184 185 215 216 218
A003 OK SEARCH completed
Note that all of these operate on a per-folder basis. If you want to know about all the folders in your mailbox, you'll have to iterate over them all. To get the full folder list, use the LIST command:
A004 LIST "" "*"
* LIST (\HasNoChildren) "/" "Drafts"
* LIST (\HasNoChildren) "/" "INBOX"
* LIST (\NoInferiors) "/" "Junk"
* LIST (\HasNoChildren) "/" "Sent"
* LIST (\HasNoChildren) "/" "Trash"
* LIST (\HasNoChildren) "/" "Unread Messages"
A004 OK LIST completed
Given that you indeed seem to be using the C API, you can do an imap4_search for UNSEEN messages. That should allow you to count the number of unread messages. A similar PHP example can be found here: http://www.electrictoolbox.com/php-imap-unread-messages/
精彩评论