Let us connect to your Google email account and read the first email message. If you don't delete it, the first email message would be the welcome message from Google.
Listing 5.5 shows us how to check Google email with IMAP as follows:
#!/usr/bin/env python # Python Network Programming Cookbook, Second Edition -- Chapter - 5 # This program is optimized for Python 2.7.12 and Python 3.5.2. # It may run on any other version with/without modifications. import argparse import getpass import imaplib GOOGLE_IMAP_SERVER = 'imap.googlemail.com' def check_email(username): mailbox = imaplib.IMAP4_SSL(GOOGLE_IMAP_SERVER, '993') password = getpass.getpass(prompt="Enter your Google password: ") mailbox.login(username, password) mailbox.select('Inbox') typ, data = mailbox.search(None, 'ALL') for num in data[0].split(): typ, data = mailbox.fetch(num, '(RFC822)') print ('Message %s %s ' % (num, data[0][1])) break mailbox.close() mailbox.logout() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Email Download Example') parser.add_argument('--username', action="store",
dest="username", default=getpass.getuser()) given_args = parser.parse_args() username = given_args.username check_email(username)
If you run this script, this will show the following output. In order to remove the private part of the data, we truncated some user data:
$ python 15_5_check_remote_email_via_imap.py --username=<USER_NAME> Enter your Google password: Message 1 Received: by 10.140.142.16; Sat, 17 Nov 2007 09:26:31 -0800 (PST) Message-ID: <...>@mail.gmail.com> Date: Sat, 17 Nov 2007 09:26:31 -0800 From: "Gmail Team" <[email protected]> To: "<User Full Name>" <USER_NAME>@gmail.com> Subject: Gmail is different. Here's what you need to know. MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="----=_Part_7453_30339499.1195320391988" ------=_Part_7453_30339499.1195320391988 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline Messages that are easy to find, an inbox that organizes itself, great spam-fighting tools and built-in chat. Sound cool? Welcome to Gmail. To get started, you may want to: [TRUNCATED]