Python imaplib Introduction

Python imaplib Introduction


  A python client-side library (available on versions 1.5.2 and later) that enables the users to access, retrieve, read, and process the e-mails sent by a sender, is the 'imaplib'. The imaplib library is the set of methods and modules that governs the commands of the IMAP (Internet Mail Access Protocol), created for email retrieval. The main difference between the email retrieval protocols POP3 and IMAP is that the former downloads the email on the client machine and deletes it from the server machine and then enables it to be read whereas the latter stores the email on the server side the whole time, beneficial in case of low bandwidth.

  1) Import the Modules: The huge flexibility of python enables users to import the already available, built-in modules. The modules to be imported are imaplib, email, webbrowser (for the interface of processing web applications),  decode_header (to decode the encoded header), os (to properly function on the machine).
  2) Providing User Account Details: The username and password of the email trying to be accessed mu st be entered. The entered credentials must be correct to properly access the emails.

  3) Create Object of IMAP4 class: The types of client classes available are as follows,
      a) IMAP4: Uses clear text sockets.
      b) IMAP4_SSL: Encrypts the communications over the SSL sockets.
      c) IMAP4_stream: Uses the standard input/output for the external command.
  4) Login to the Server: Login using the credentials and the method, login() for authentication.

  5) Select The Mailbox: Select the mailbox from which e-mails are to be retrieved from. Mailbox depends on the provider, in the case of Gmail, it could be either inbox, spam, updates, and so on.
  6) The 'status' variable represents the state of the email (received, sent etc.) and the 'messages' variable represents the number of emails in the specific mailbox.
  7)'N' is the number of topmost emails wished to be read. It is an arbitrary value.

  8) The emails can be retrieved and read by processing further using the necessary methods from the modules imported.
  9) The session must be terminated in the end, using the close() method.

NOTE: It is important to note that the Gmail account associated with the credentials specified must allow 'less secure apps', in the settings for authorization from the program written.

  OUTPUT: The number of emails, i,e, the messages is printed. The output depicts that I have 120 emails in my inbox.

  CONCLUSION: In such a way, imaplib is used as a part of an application, to read the emails from CLI.

More Articles of Hima Parasa:

Name Views Likes
Python imaplib Introduction 55 3