HomePython Page 3 - Python Email Libraries, part 1: POP3
Getting Message Info - Python
Some very useful business software connects with and interacts with email in various ways. If you are building or working with such software, you might want to know how Python accomplishes these tasks. This article series discusses how to use the email libraries built into Python. In this first part, POP3 is covered.
Once you’re connected to the server, the natural thing you’ll want to do is download a list of messages available on the server for download. This is done using the list operation. This method returns a Python list data structure, where the first element is the server’s response, and the second element is another list of strings, each of which contains a message number and message size. An example of how you might do this follows:
One important thing to note is that the list method can alternatively take an argument that specifies a subset of messages whose information to return. How to actually do this is described in the POP RFC.
Protocol Definition Concerns
One thing to note regarding the POP3 library concerns the list operation in the first line of the above code. As you can see, it pulls the second element off of the list to work with and ignores the first. This is because almost all methods in the POP3 library return a list, and the first element of that list is almost always the server’s response to the command, usually a string of something like “OK” or “BAD” telling you whether or not the server was able to process the request.
Throughout this article, I will generally assume that the commands we send to the server will work correctly in order to focus more on the actual workings of the POP library. However, when you work with this library in any sort of production level software, this first element of the response list is invaluable for error detection and recovery. You can check this response in the case that you get no data back from a request to find out if there really is no data, or if your request was in some way flawed. If you want to know the exact possibilities for this server response field, they are defined in RFC 1725.