Using poplib to parse headers

Jean-Claude Neveu jcn-france1972 at pobox.com
Mon May 26 18:39:51 EDT 2008


Hello,

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'"

Please forgive this very basic question. I do most of my programming 
in PHP and I'm just getting started with Python.

Many thanks,

J-C




More information about the Python-list mailing list