Learning Python Network Programming

(Sean Pound) #1

Engaging with E-mails


A typical example of what an IMAP client looks like can be seen here:


mailbox = imaplib.IMAP4_SSL(<IMAP_SERVER>, <SERVER_PORT>)
mailbox.login('username', 'password')
mailbox.select('Inbox')

The aforementioned code will try to initiate an IMAP4 encrypted client session.
After the login() method is successful, you can apply the various methods on the
created object. In the aforementioned code snippet, the select() method has been
used. This will select a user's mailbox. The default mailbox is called Inbox. A full
list of methods supported by this mailbox object is available on the Python Standard
library documentation page, which can be found at https://docs.python.org/3/
library/imaplib.html.


Here, we would like to demonstrate how you can search the mailbox by using the
search() method. It accepts a character set and search criterion parameter. The
character set parameter can be None, where a request for no specific character will
be sent to the server. However, at least one criterion needs to be specified. For
performing advance search for sorting the messages, you can use the sort() method.


Similar to POP3, we will use a secure IMAP connection for connecting to the server by
using the IMAP4_SSL() class. Here's a lightweight example of a Python IMAP client:


#!/usr/bin/env python3
import getpass
import imaplib
import pprint

GOOGLE_IMAP_SERVER = 'imap.googlemail.com'
IMAP_SERVER_PORT = '993'

def check_email(username, password):
mailbox = imaplib.IMAP4_SSL(GOOGLE_IMAP_SERVER,
IMAP_SERVER_PORT)
mailbox.login(username, password)
mailbox.select('Inbox')
Free download pdf