09.11.2016 Views

Foundations of Python Network Programming 978-1-4302-3004-5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 15 ■ IMAP<br />

Listing 15–7. A Simple IMAP Client<br />

#!/usr/bin/env python<br />

# <strong>Foundations</strong> <strong>of</strong> <strong>Python</strong> <strong>Network</strong> <strong>Programming</strong> - Chapter 15 - simple_client.py<br />

# Letting a user browse folders, messages, and message parts.<br />

import getpass, sys<br />

from imapclient import IMAPClient<br />

try:<br />

» hostname, username = sys.argv[1:]<br />

except ValueError:<br />

» print 'usage: %s hostname username' % sys.argv[0]<br />

» sys.exit(2)<br />

banner = '-' * 72<br />

c = IMAPClient(hostname, ssl=True)<br />

try:<br />

» c.login(username, getpass.getpass())<br />

except c.Error, e:<br />

» print 'Could not log in:', e<br />

» sys.exit(1)<br />

def display_structure(structure, parentparts=[]):<br />

» """Attractively display a given message structure."""<br />

» # The whole body <strong>of</strong> the message is named 'TEXT'.<br />

» if parentparts:<br />

» » name = '.'.join(parentparts)<br />

» else:<br />

» » print 'HEADER'<br />

» » name = 'TEXT'<br />

» # Print this part's designation and its MIME type.<br />

» is_multipart = isinstance(structure[0], list)<br />

» if is_multipart:<br />

» » parttype = 'multipart/%s' % structure[1].lower()<br />

» else:<br />

» » parttype = ('%s/%s' % structure[:2]).lower()<br />

» print '%-9s' % name, parttype,<br />

» # For a multipart part, print all <strong>of</strong> its subordinate parts; for<br />

» # other parts, print their disposition (if available).<br />

» if is_multipart:<br />

» » print<br />

» » subparts = structure[0]<br />

» » for i in range(len(subparts)):<br />

» » » display_structure(subparts[i], parentparts + [ str(i + 1) ])<br />

» else:<br />

» » if structure[6]:<br />

» » » print 'size=%s' % structure[6],<br />

» » if structure[8]:<br />

» » » disposition, namevalues = structure[8]<br />

» » » print disposition,<br />

» » » for i in range(0, len(namevalues), 2):<br />

» » » » print '%s=%r' % namevalues[i:i+2]<br />

253

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!