Go4Expert (http://www.go4expert.com/)
-   Python (http://www.go4expert.com/articles/python-tutorials/)
-   -   Accessing EMail Using IMAP In Python (http://www.go4expert.com/articles/accessing-email-using-imap-python-t28838/)

pradeep 6Aug2012 18:19

Accessing EMail Using IMAP In Python
Internet Message Access Protocol better known as IMAP is one of the most popular & widely used protocols for accessing emails from remote servers, the other one being POP (Post Office Protocol), and almost all modern email clients support both these protocols.

IMAP works on TCP/IP stack, and the server generally runs on port 143 and IMAPS (IMAP over SSL) on 993. IMAP is much more advanced than POP, you can use IMAP to fetch messages in part or full, create folder/sub-folders, move & copy messages from/to folders, upload new messages to the server, search for messages using various parameters, and more. The current version of IMAP is IMAP4 (version 4 revision 1).

In this article, we'll be looking into a few basic IMAP operations with some demo code.


The built-in Python module imaplib, the module makes it pretty simple to connect to IMAP & IMAPS severs, follow the sample code below:

Code: Python


import imaplib

imap_host = 'imap.gmail.com'
imap_user = 'pradeep@gmail.com'
imap_pass = 'xXxxXxx'

## connect to host using SSL
imap = imaplib.IMAP4_SSL(imap_host)

## login to server
imap.login(imap_user, imap_pass)

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

print status

unreadcount = int(response[0].split()[2].strip(').,]'))
print unreadcount

Advanced Operations

Now, let's look at some more operations like list the folders and sub-folders, creating new folder/sub-folder, searching for messages, please follow the demo code, bit you have to try running it, tweaking it to get to understand it better.

Code: Python

## create a new sub-folder inside a folder
status, create_response = imap.create('Archives.July')

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

## list sub-folders
status, sub_folder_list = imap.list(directory='Social NW Mails')

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

## search a folder, returns the matched message-ids in CSV
status, msg_ids = imap.search(None, '(SUBJECT "Your Monthly Statement")')

## fetching a message, first we'll see how to fetch just headers
## first arg is the message id, next are flags
status, msg_header = imap.fetch('1', '(BODY.PEEK[HEADER])')

## fecthing full message
status, msg_full = imap.fetch('1', '(RFC822)')

## moving/copying messages around folders
status, msg_ids = imap.copy(msg_ids, 'Archives.July')
status, msg_ids = imap.move(msg_ids, 'Unimportant')

## last but not the least, closing & logging out



All times are GMT +5.5. The time now is 02:13.