Using poplib to parse headers

Tim Roberts timr at probo.com
Wed May 28 03:44:45 EDT 2008


Jean-Claude Neveu <jcn-france1972 at pobox.com> wrote:
>
>I am writing a Python program to check email using POP3. I've tried 
>the sample code from python.org, and it works great. In other words, 
>the code below successfully prints out my emails.
>
>import getpass, poplib, email
>M = poplib.POP3('mail.blah.com')
>M.user('username')
>M.pass_('password')
>numMessages = len(M.list()[1])
>for i in range(numMessages):
>     for j in M.retr(i+1)[1]:
>         print j
>M.quit()
>
>However, if I understand right, the Python poplib library will also 
>parse the email for me so that I can iterate through the headers, 
>body, etc, of each message, and use them in my program. I think the 
>method I need to use is email.message_from_file, but I'm having 
>difficulty getting it to work. Can anyone explain me how I would 
>extend the above example to do this?
>
>I tried to do this by using in the i loop the line:
>
>	message = email.message_from_file(j)
>
>but I get the error: "AttributeError: 'str' object has no attribute 'readline'"

You've received some very confusing advice in this thread.  Alex had the
right answer, but I want to expand it a bit.

You said "the Python poplib library will also parse the email for me". This
is incorrect.  poplib, like many of the modules of the Python standard
library, focuses on exactly one purpose: handling the POP3 protocol.  It
will allow you to count your messages, and fetch your messages, but that's
it, because that's all that POP3 does.  It's a very simple protocol.

Now, the standard library DOES include modules for parsing email, as you
seem to realize.  The "email" module is a very sophisticated tool for that
purpose.  However, the email module doesn't have any way to fech the mail.
So, you need to stitch them together.

poplib.retr gives you a string.  You need to hand that string to the email
module, and you do that using "email.message_from_string".
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the Python-list mailing list