Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Python (http://www.go4expert.com/articles/python-tutorials/)
-   -   Access Mails Through POP3 in Python (http://www.go4expert.com/articles/access-mails-pop3-python-t28827/)

pradeep 3Aug2012 18:54

Access Mails Through POP3 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

#!/usr/bin/python26

import poplib

pop3_host = 'pop.gmail.com'
pop3_user = 'pradeep@gmail.com'
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
pop3_mail.user(pop3_user)

## send password
pop3_mail.pass_(pop3_pass)

## 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.

References



http://docs.python.org/library/poplib.html

Scripting 3Aug2012 22:07

Re: Access Mails Through POP3 in Python
 
Perfect! I would like to see SMTP tutorail too :D If you don't mind, you could write it too :)

pradeep 6Aug2012 12:49

Re: Access Mails Through POP3 in Python
 
Quote:

Originally Posted by Scripting (Post 96809)
Perfect! I would like to see SMTP tutorail too :D If you don't mind, you could write it too :)

It's already there, Sending Emails With Python


All times are GMT +5.5. The time now is 03:16.