HomePython Page 2 - Python Email Libraries, part 2: IMAP
Authentication - Python
The first article in this series discussed how to access a POP3 server with a Python script. While that protocol is useful for learning the basics of how email works, IMAP is the protocol most used today. This article covers this more complicated protocol.
Once you have successfully connected to the server, you need to log in to do anything useful. The function to do this is called “login,” and it takes two arguments, the username and password. Once you have logged in, you have several choices as to what you want to do. Since IMAP organizes mail into various “mailboxes” (which are basically folders), you can move to another mailbox, create or delete a mailbox, and fetch various parts of messages.
mboxes = server.list()
r = server.select(“Old Mail”)
The above code logs in to the mail server and then does some work with mailboxes. The second line gets a list of mailboxes from the server. This response gives you a Python list data structure of the server’s responses to the “list” request. As with the POP3 library, the first element of these returned results is the server’s “response,” which lets you know if the command completed successfully; since we are interested primarily in the data from this function, we strip the first element away.
The “list” function returns a list of strings. Each of these strings has three elements. The first part of the string contains the mailbox attributes flag. This gives you some basic information about the mailbox, such as whether the server thinks it’s interesting or not. The next element is where this mailbox lives, basically its parent directory. This is useful when setting up a nested folder system on the email server, as you must supply the full path to a new mailbox in order to create it within another mailbox.
Finally, the last element is the folder name itself. If you want to find out how many messages there are in a mailbox, you must then select that mailbox. The server will return the result of the operation as well as the number of messages in the mailbox. It is important to know that you must select some mailbox before you can do any actual searching or fetching of messages. By default, the “select” function selects the “Inbox,” but it must be called before anything else can be done with individual messages.