Access Mails Through POP3 in Python

pradeep's Avatar author of Access Mails Through POP3 in Python
This is an article on Access Mails Through POP3 in Python in Python.
Post Office Protocal version 3 (POP3) is protocol of the TCP/IP stack's application layer, used to fetch email from remote mail servers. POP is one of the most used protocols for email retrieval, other one being IMAP. Virtually every email application, be it in the desktop or mobile supports the POP protocol. POP was succeeded by IMAP which has become the default protocol in many email clients.

POP is way simpler than IMAP, so it is better suited for programs which need to access mails & process them, say a notifier, or check for specific mails process & delete them. In this article we'll see how to access a mailbox via POP3 in Python.

The Module And Usage

Python comes with a module poplib for accessing POP3 servers. This module also supports the Secure Socket Layer (SSL), so you can be assured that no one is evaedropping on your message or password. In the following example we'll be looking at connecting to a remote POP3 server and fetching message summaries and a few messages for demonstration purposes, if you want to test the code yourself, please changes the server host, username & password values accordingly.

Code: Python

import poplib

pop3_host = ''
pop3_user = ''
pop3_pass = 'xxxx'

## connect to host using SSL
pop3_mail = poplib.POP3_SSL(pop3_host)

## print the response message from server
print pop3_mail.getwelcome()

## send user

## send password

## get mail box stats; returns an array
pop3_stat = pop3_mail.stat()

print "Total New Mails : %s (%s bytes)" % pop3_stat

## let's fetch one latest mail
print "\n\n===\nLatest Mail\n===\n\n"

## fetch the top mail
latest_email = pop3_mail.retr(1)

## print the message
print latest_email[1]

## in case you want to iterate and process all messages
number_of_mails = pop3_stat[0]
for i in range(number_of_mails):
    for mail in mail.retr(i+1)[1]:
        print mail

That's about it, that's all you'd need to access mails over POP3 with Python. If you need to access GMail accounts, please make sure that POP is enabled for those GMail accounts.

Scripting's Avatar, Join Date: Jun 2010
John Hoder
Perfect! I would like to see SMTP tutorail too If you don't mind, you could write it too
pradeep's Avatar, Join Date: Apr 2005
Team Leader
Originally Posted by Scripting View Post
Perfect! I would like to see SMTP tutorail too If you don't mind, you could write it too
It's already there, Sending Emails With Python