Chapter 15 ■ IMap
2 74
Summary Information
When you first select a folder, the IMAP server provides some summary information about it—about the folder itself
and also about its messages.
The summary is returned by IMAPClient as a dictionary. Here are the keys that most IMAP servers will return
when you run select_folder():
• EXISTS: An integer giving the number of messages in the folder.
• FLAGS: A list of the flags that can be set on messages in this folder.
• RECENT: Specifies the server’s estimate of the number of messages that have appeared in the
folder since the last time an IMAP client ran select_folder() on it.
• PERMANENTFLAGS: Specifies the list of custom flags that can be set on messages; this is usually
empty.
• UIDNEXT: The server’s guess about the UID that will be assigned to the next incoming
(or uploaded) message.
• UIDVALIDITY: A string that can be used by clients to verify that the UID numbering has not
changed. If you come back to a folder and this is a different value than the last time you
connected, then the UID number has started over and your stored UID values are no longer valid.
• UNSEEN: Specifies the message number of the first unseen message (the one without the
\Seen flag) in the folder.
Of these flags, servers are only required to return FLAGS, EXISTS, and RECENT, though most will include at least
UIDVALIDITY as well. Listing 15-5 shows a sample program that reads and displays the summary information of my
INBOX e-mail folder.
Listing 15-5. Displaying Folder Summary Information
#!/usr/bin/env python3
Foundations of Python Network Programming, Third Edition
https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter15/folder_info.py
Opening an IMAP connection with IMAPClient and listing folder information.
import getpass, sys
from imapclient import IMAPClient
def main():
if len(sys.argv) != 4:
print('usage: %s hostname username foldername' % sys.argv[0])
sys.exit(2)
hostname, username, foldername = sys.argv[1:]
c = IMAPClient(hostname, ssl=True)
try:
c.login(username, getpass.getpass())
except c.Error as e:
print('Could not log in:', e)
else:
select_dict = c.select_folder(foldername, readonly=True)
for k, v in sorted(select_dict.items()):
print('%s: %r' % (k, v))
finally:
c.logout()