Retrieving emails with imaplib

As we mentioned earlier, accessing emails over the IMAP protocol doesn't necessarily download them onto the local device.

Python provides a library called imaplib, which can be used for accessing messages over the IMAP protocol. This library provides the IMAP4() class, which takes the host and port for implementing this protocol as arguments. The default port is 143.

The IMAP4_SSL() class has the capacity to connect over an SSL encrypted socket and provides a secure version of the IMAP4 protocol by using 993 as the default port.

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 previous 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 previous 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 that are 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 an advanced search for sorting the messages, you can use the sort() method.

We can use a secure IMAP connection for connecting to the server by using the IMAP4_SSL() class.

If you are using a Gmail account and want to store all of your emails messages in your Gmail Sent folder, go to the Forwarding and POP/IMAP tab and enable IMAP.

In the following screenshot, we can see the Gmail configuration for the IMAP protocol:

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

#!/usr/bin/env python3

import argparse
import imaplib

def check_email(username,password):
mailbox = imaplib.IMAP4_SSL('imap.gmail.com', '993')
mailbox.login(username, password)
mailbox.select('Inbox')
type, data = mailbox.search(None, 'ALL')
for num in data[0].split():
type, data = mailbox.fetch(num, '(RFC822)')
print ('Message %s %s ' % (num, data[0][1]))
mailbox.close()
mailbox.logout()

In the previous code block we define check_email() method that establish the connection with imap gmail server with username and password parameters, select the inbox for recover messages and search for specific RFC number protocol inside the mailbox. In the next code block we define our main program that request information about username and password used for establish the connection.

if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Email Download IMAP')
parser.add_argument('--username', action="store", dest="username")
given_args = parser.parse_args()
username = given_args.username
import getpass
password = getpass.getpass(prompt='Enter your password:')
check_email(username, password)

In this example, an instance of IMPA4_SSL(), that is, the mailbox object, has been created. Here, we have taken the server address and port as arguments. Upon successfully logging in with the login() method, you can use the select() method to choose the mailbox folder that you want to access. In this example, the inbox folder has been selected. To read the messages, we need to request the data from the inbox. One way to do that is by using the search() method. Upon successful reception of some email metadata, we can use the fetch() method to retrieve the email message envelope part and data. In this example, the RFC 822 type of standard text message has been sought with the help of the fetch() method.

We can use the Python pretty print or the print module for showing the output on the screen. Finally, apply the close() and the logout() methods to the mailbox object.

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

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