Retrieving e-mails by using POP3 with poplib

The stored e-mail messages can be downloaded and read by the local computer. The POP3 protocol can be used to download the messages from the e-mail server. Python has a module called poplib, and it can be used for this purpose. This module provides two high-level classes, POP() and POP3_SSL(),which implement the POP3 and POP3S protocols respectively for communicating with a POP3/POP3S server. It accepts three arguments, host, port, and timeout. If port is omitted, then the default port (110) can be used. The optional timeout parameter determines the length (in seconds) of the connection timeout at the server.

The secure version of POP3() is its subclass POP3_SSL(). It takes additional parameters, such as keyfile and certfile, which are used for supplying the SSL certificate files, namely the private key and certificate chain file.

Writing for a POP3 client is also very straightforward. To do this, instantiate a mailbox object by initializing the POP3() or POP3_SSL() class. Then, invoke the user() and pass_() methods to login to the server by using the following command:

  mailbox = poplib.POP3_SSL(<POP3_SERVER>, <SERVER_PORT>) 
  mailbox.user('username')
       mailbox.pass_('password')

Now, you can call the various methods for manipulating your accounts and messages. A few interesting methods have been listed here:

  • stat(): This method returns the mailbox status according to tuples of two integers, that is, the message count and the size of the mailbox.
  • list(): This method sends a request for getting a message list, which has been demonstrated in the example shown later in this section.
  • retr(): This method gives an argument message a number that indicates the message that has to be retrieved. It also marks the message as read.
  • dele(): This method provides an argument for the message that has to be deleted. On many POP3 servers, the deletion is not performed until QUIT. You can reset the delete flag by using the rset() method.
  • quit(): This method takes you off the connection by committing a few changes and disconnecting you from the server.

Let us see how we can read out the e-mail messages by accessing the Google's secure POP3 e-mail server. By default, the POP3 server listens on port 995 securely. The following is an example of fetching an e-mail by using POP3:

#!/usr/bin/env python3
import getpass
import poplib

GOOGLE_POP3_SERVER = 'pop.googlemail.com'
POP3_SERVER_PORT = '995'

def fetch_email(username, password): 
    mailbox = poplib.POP3_SSL(GOOGLE_POP3_SERVER, POP3_SERVER_PORT) 
    mailbox.user(username)
    mailbox.pass_(password) 
    num_messages = len(mailbox.list()[1])
    print("Total emails: {0}".format(num_messages))
    print("Getting last message") 
    for msg in mailbox.retr(num_messages)[1]:
        print(msg)
    mailbox.quit()

if __name__ == '__main__':
    username = input("Enter your email user ID: ")
    password = getpass.getpass(prompt="Enter your email password:    ") 
    fetch_email(username, password)

As you can see in the preceding code, the fetch_email() function has created a mailbox object by calling POP3_SSL() along with the server socket. The username and the password are set on this object by calling the user() and pass_() method. Upon successful authentication, we can invoke the POP3 commands by using methods, such as the list() method, which is called to list the e-mails. In this example, the total number of messages has been displayed on the screen. Then, the retr() method has been used for retrieving the content of a single message.

A sample output has been shown here:

$ python3 fetch_email_pop3.py 
Enter your email user ID: <PERSON1>@gmail.com
Enter your email password: 
Total emails: 330
Getting last message
b'Received: by 10.150.139.7 with HTTP; Tue, 7 Oct 2008 13:20:42 -0700 
(PDT)'
b'Message-ID: <[email protected]>'
b'Date: Tue, 7 Oct 2008 21:20:42 +0100'
b'From: "Mr Person1" <[email protected]>'
b'To: "Mr Person2" <[email protected]>'
b'Subject: Re: Some subject'
b'In-Reply-To: <[email protected]>'
b'MIME-Version: 1.0'
b'Content-Type: multipart/alternative; '
b'	boundary="----=_Part_63057_22732713.1223410842697"'
b'References: <[email protected]>'
b'	 <[email protected]>'
b'Delivered-To: [email protected]'
b''
b'------=_Part_63057_22732713.1223410842697'
b'Content-Type: text/plain; charset=ISO-8859-1'
b'Content-Transfer-Encoding: quoted-printable'
b'Content-Disposition: inline'
b''
b'Dear Person2,'
..................Content has been hidden....................

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