Retrieving emails with imapclient

IMAPClient is a complete IMAP client library written in Python that uses the imaplib module from the Python standard library. It provides an API for creating a connection and reads messages from the inbox folder.

You can install imapclient with the following command:

$ pip install imapclient

The IMAPClient class is the core of the IMAPClient API. You can create a connection to an IMAP account by instantiating this class and interacting with the server calling methods on the IMAPClient instance.

The following script shows how to interact with an IMAP server, displaying all of the messages in the inbox folder and the information related to the message ID, subject, and date of the message.

You can find the following code in the folder_info_imapclient.py file:

#!/usr/bin/env python3

from imapclient import IMAPClient
import getpass

username = input('Enter your username:')
password = getpass.getpass(prompt='Enter your password:')

server = IMAPClient('imap.gmail.com', ssl=True)
server.login(username, password)
select_info = server.select_folder('INBOX',readonly=True)
for k, v in list(select_info.items()):
print('%s: %r' % (k, v))

server.logout()

In this script, we open an IMAP connection with the IMAPClient and get information about its capabilities and mailboxes.

You can find the following code in the listing_mailbox_imapclient.py file:

#!/usr/bin/env python3

import sys
from imapclient import IMAPClient
import getpass

username = input('Enter your username:')
password = getpass.getpass(prompt='Enter your password:')

server = IMAPClient('imap.gmail.com', ssl=True)

try:
server.login('user', 'password')
except server.Error as e:
print('Could not log in:', e)
sys.exit(1)

print('Capabilities:', server.capabilities())
print('Listing mailboxes:')
data = server.list_folders()
for flags, delimiter, folder_name in data:
print(' %-30s%s %s' % (' '.join(str(flags)), delimiter, folder_name))

server.logout()

This could be the output of the previous script, where we can see capabilities and mailboxes that are available in your Gmail account:

Capabilities: ('UNSELECT', 'IDLE', 'NAMESPACE', 'QUOTA', 'XLIST','AUTH=XOAUTH')
Listing mailboxes:
Noselect HasChildren / [Gmail]
HasChildren HasNoChildren / [Gmail]/All Mail
HasNoChildren / [Gmail]/Drafts
HasChildren HasNoChildren / [Gmail]/Sent Mail
HasNoChildren / [Gmail]/Spam
HasNoChildren / [Gmail]/Starred
HasChildren HasNoChildren / [Gmail]/Trash

In this section we have reviewed the imapclient and imaplib modules which provide the methods can for accessing emails with IMAP protocol.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset