Foundations of Python Network Programming

(WallPaper) #1
Chapter 15 ■ IMap

269

Listing 15-1. Connecting to IMAP and Listing Folders


#!/usr/bin/env python3


Foundations of Python Network Programming, Third Edition


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


Opening an IMAP connection with the pitiful Python Standard Library


import getpass, imaplib, sys


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


hostname, username = sys.argv[1:]
m = imaplib.IMAP4_SSL(hostname)
m.login(username, getpass.getpass())
try:
print('Capabilities:', m.capabilities)
print('Listing mailboxes ')
status, data = m.list()
print('Status:', repr(status))
print('Data:')
for datum in data:
print(repr(datum))
finally:
m.logout()


if name == 'main':
main()


If you run this script with the appropriate arguments, it will start by asking for your password; IMAP
authentication is almost always accomplished through a username and password:


$ python open_imaplib.py imap.example.com [email protected]
Password:


If your password is correct, it will then display a response that looks something like the results shown in
Listing 15-2. As promised, you’ll see first the “capabilities,” which lists the IMAP features that this server supports.
And, I must admit, the type of this list is very Pythonic: whatever form the list had on the wire has been turned into a
pleasant tuple of strings.


Listing 15-2. Example Output of the Previous Listing


Capabilities: ('IMAP4REV1', 'UNSELECT', 'IDLE', 'NAMESPACE', 'QUOTA',
'XLIST', 'CHILDREN', 'XYZZY', 'SASL-IR', 'AUTH=XOAUTH')
Listing mailboxes
Status: 'OK'
Data:
b'(\HasNoChildren) "/" "INBOX"'
b'(\HasNoChildren) "/" "Personal"'
b'(\HasNoChildren) "/" "Receipts"'

Free download pdf