1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Accessing EMail Using IMAP In Python

Discussion in 'Python' started by pradeep, Aug 6, 2012.

  1. pradeep

    pradeep Team Leader

    Apr 4, 2005
    Likes Received:
    Trophy Points:
    Kolkata, India
    Home Page:
    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:

    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.

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



Share This Page