Foundations of Python Network Programming

(WallPaper) #1
Chapter 15 ■ IMap

277

Of course, if the messages contained large attachments, it could be ruinous to download them in their entirety
just to print a summary; but because this is the simplest message-fetching operation, I thought that it would be
reasonable to start with it!


Downloading Messages Individually

E-mail messages can be quite large, and so can e-mail folders—many e-mail systems permit users to have hundreds
or thousands of messages, each of which can be 10MB or more. That kind of mailbox can easily exceed the RAM on
the client machine if its contents are all downloaded at once, as was done in the previous example.
To help network-based e-mail clients that do not want to keep local copies of every message, IMAP supports
several operations besides the big “fetch the whole message” command discussed in the previous section.


•    An e-mail’s headers can be downloaded as a block of text, separately from the message.

•    Particular headers from a message can be requested and returned without downloading
them all.

•    The server can be asked to recursively explore and return an outline of the MIME structure
of a message.

•    The text of particular sections of the message can be returned.

This allows IMAP clients to perform very efficient queries that download only the information they need to
display for the user, decreasing the load on the IMAP server and the network and allowing results to be displayed
more quickly to the user.
For an example of how a simple IMAP client works, examine Listing 15-7, which puts together a number of ideas
about browsing an IMAP account. This should provide more context than would be possible if these features were
spread out over a half-dozen shorter program listings at this point in the chapter! You can see that the client consists of
three concentric loops that each takes input from users as they view the list of e-mail folders, then the list of messages
within a particular e-mail folder, and finally the sections of a specific message.


Listing 15-7. A Simple IMAP Client


#!/usr/bin/env python3


Foundations of Python Network Programming, Third Edition


https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter15/simple_client.py


Letting a user browse folders, messages, and message parts.


import getpass, sys
from imapclient import IMAPClient


banner = '-' * 72


def main():
if len(sys.argv) != 3:
print('usage: %s hostname username' % sys.argv[0])
sys.exit(2)


hostname, username = 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)

Free download pdf