Chapter 15 ■ IMap
275
if name == 'main':
main()
When run, this program displays results such as this:
$ ./folder_info.py imap.example.com [email protected]
Password:
EXISTS: 3
PERMANENTFLAGS: ('\Answered', '\Flagged', '\Draft', '\Deleted',
'\Seen', '\*')
READ-WRITE: True
UIDNEXT: 2626
FLAGS: ('\Answered', '\Flagged', '\Draft', '\Deleted', '\Seen')
UIDVALIDITY: 1
RECENT: 0
This shows that my INBOX folder contains three messages, none of which have arrived since I last checked. If your
program is interested in using UIDs that it stored during previous sessions, remember to compare the UIDVALIDITY to
a stored value from a previous session.
Downloading an Entire Mailbox
With IMAP, the FETCH command is used to download mail, which an IMAPClient exposes as its fetch() method.
The simplest way to fetch involves downloading all messages at once in a single big gulp. Although this is the
simplest and requires the least network traffic (because you do not have to issue repeated commands and receive
multiple responses), it does mean that all of the returned messages will need to sit in memory together as your program
examines them. For very large mailboxes whose messages have lots of attachments, this is obviously not practical!
Listing 15-6 downloads all of the messages from the INBOX folder into your computer’s memory in a Python data
structure, and then displays a bit of summary information about each one.
Listing 15-6. Downloading All Messages in a Folder
#!/usr/bin/env python3
Foundations of Python Network Programming, Third Edition
https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter15/folder_summary.py
Opening an IMAP connection with IMAPClient and retrieving mailbox messages.
import email, 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)