Learning Python Network Programming

(Sean Pound) #1

Engaging with E-mails


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 POP3SSL() 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: @gmail.com


Enter your email password:


Total emails: 330

Free download pdf