Retrieving e-mails by using IMAP with imaplib

As we mentioned previously, accessing e-mail over the IMAP protocol doesn't necessarily download the message to the local computer or mobile phone. So, this can be very efficient, even when used over any low bandwidth Internet connection.

Python provides a client-side library called imaplib, which can be used for accessing e-mails over the IMAP protocol. This provides the IMAP4() class, which implements the IMAP protocol. It takes two arguments, that is, host and port for implementing this protocol. By default, 143 has been used as the port number.

The derived class, that is, IMAP4_SSL(), provides a secure version of the IMAP4 protocol. It connects over an SSL encrypted socket. So, you will need an SSL friendly socket module. The default port is 993. Similar to POP3_SSL(), you can supply the path to a private key and a certificate file path.

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')
    tmp, data = mailbox.search(None, 'ALL')
    for num in data[0].split():
        tmp, data = mailbox.fetch(num, '(RFC822)')
        print('Message: {0}
'.format(num))
        pprint.pprint(data[0][1])
        break
    mailbox.close()
    mailbox.logout()
    

if __name__ == '__main__':
    username = input("Enter your email username: ")
    password = getpass.getpass(prompt="Enter you account password: ")
    check_email(username, password)

In this example, an instance of IMPA4_SSL(), that is, the mailbox object, has been created. In this, we have taken the server address and port as arguments. Upon successfully logging in with the login() method, you can use the select() method for choosing the mail box folder that you want to access. In this example, the Inbox folder has been selected. In order to read the messages, we need to request for the data from the Inbox. One way to do that is to use the search() method. Upon the successful reception of some mail metadata, we can use the fetch() method for retrieving the e-mail 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.

The preceding code will display an output similar to the following:

$ python3 fetch_email_imap.py 
Enter your email username: [email protected]
Enter you Google password: 
Message b'1'
b'X-Gmail-Received: 3ec65fa310559efe27307d4e37fdc95406deeb5a
Delivered-To: [email protected]
Received: by 10.54.40.10 with SMTP id n10cs1955wrn;
    [Message omitted]
..................Content has been hidden....................

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