Switch to full style
Python Technology Tutorials Written By Members.
Post a reply

Reading email in Python

Sat Aug 04, 2012 4:03 pm

In this article we read an email using POP protocol, Python includes a poplib package for connecting POP servers. In the following code snippet we fetch email content :

Code:

import poplib
mailServer 
= 'pop.gmail.com'
emailID = '[email protected]'
emailPass = 'xxxx'

## open connection to mail server (Secured using SSL)
myEmailConnection = poplib.POP3_SSL(mailServer)
## print the response message from server
print myEmailConnection.getwelcome()
## set email address
myEmailConnection.user(emailID)
## set password 
myEmailConnection.pass_(emailPass)
## get information about the email address
EmailInformation = myEmailConnection.stat()
print "Number of new emails: %s (%s bytes)" % EmailInformation
## Reading an email
print "\n\n===\nRead messages\n===\n\n"
 
## Read all emails
numberofmails = EmailInformation[0]
for i in range(numberOfMails):
    for email in myEmailConnection.retr(i+1)[1]:
        print email

You may noticed that we first opened a connection to POP3 (Post Office Protocol version 3) server then we using the user email ID/Password to retrieve email information and content. You have to notice that we sent the password using secured channel(SSL). The gmail service allow you to change the date that you want to start reading your message from, just go to your email options. There are other functions that we didn't use in this code snippet for example :

myEmailConnection.retr(index) ( used in the snippet)
Retrieve whole message number index
myEmailConnection.dele(index)
Flag message number index for deletion.
myEmailConnection.quit()
Sign-off: unlock mailbox after committing changes, close connection.

You can also read email using IMAP, IMAP has more features than POP, for example using IMAP you can create folders, move/delete/send messages. Following snippet present an example for using a built in package "imaplib".
Code:

import imaplib

imap_host 
= 'imap.gmail.com'
imap_user = '[email protected]'
imap_pass = 'password'

## open a connection 
imap = imaplib.IMAP4_SSL(imap_host)

## login
imap.login(imap_user, imap_pass)

## get status for the mailbox (folder) INBOX
folderStatus, UnseenInfo = imap.status('INBOX', "(UNSEEN)")

print folderStatus

NotReadCounter 
= int(UnseenInfo[0].split()[2].strip(').,]'))
print NotReadCounter


## create a new folder
status, createFolder_response = imap.create('myFolders.xyz')

## folders list
status, folder_list = imap.list()

## list sub-folders
status, sub_folder_list = imap.list(directory='insd')

## select a specific folder
status, data = imap.select('INBOX')

## searching current folder using title keywords 
status, messages = imap.search(None, '(SUBJECT "Work Report")')
 
## fetching message header by  using message( ID)
status, msg_header = imap.fetch('1', '(BODY.PEEK[HEADER])')

## fetching the full message ( ID=1)
status, AllTheMessage= imap.fetch('1', '(RFC822)')

## moving/copying messages around folders
status, messages  = imap.copy(msg_ids, 'myFolders.xyz')
status, messages  = imap.move(msg_ids, 'otherFolder')


 




Re: Reading email in Python

Tue Aug 07, 2012 9:09 am

updated

Post a reply
  Related Posts  to : Reading email in Python
 hashing in python     -  
 how to use GeoIP with Python     -  
 Python Module for MySQL     -  
 How to read and write to CSV file from python     -  
 exception handling try and catch in Python     -  
 usage of SQLite database from Python     -  
 Python Training from Certified Experts (ap2v.com)     -  
 Build Linear Regression in Python - Supervised Learning     -  
 Reading the all file in php     -  
 Reading file with integers     -  

Topic Tags

Python Email