imaplib/email - parsing problem

Tim Howarth tim at worthy.demon.co.uk
Fri May 10 05:06:12 EDT 2002


I've been trying to use imaplib to fetch email from a server then use
the email module to decode the messages. (Python 2.2.1)

But I've hit a problem with email.message_from_string

Either I've misunderstood, it's a bug, it's a server feature, it's an
email module "feature" or just, I haven't found it in the docs  -
can anyone explain.


I've made a small test which fetches the first email from the server
using code taken from the examples in the docs.

The message has plain text and attachment.

However it isn't parsed properly and I get just one part which is
the whole message (without headers).


(
Using Python 2.2 produces

Traceback (most recent call last):
  File "D:\Peeps\Tim\IMAP\eg.py", line 21, in ?
    fp.write(part.get_payload(decode=1))
TypeError: argument 1 must be string or read-only buffer, not instance
)


I can get it parsed properly by replacing CR's in the raw message -
dd=dd.replace('\r','')
which then produces 2 files - text and decoded attachment.

The message as fetched has CRLF pairs, if saved ('w' not 'wb') it
produces CRCRLF line endings which I assume is a related problem.



Anyway back to the question, should it work without this fiddling ?



import imaplib, email, os

M =imaplib.IMAP4('192.168.0.1')
M.login('timbo', '12345')
M.select()
typ, data = M.fetch(1, '(RFC822)')
dd=data[0][1]

#dd=dd.replace('\r','')

msg=email.message_from_string(dd)

counter = 1
dir=r'd:\mess'

for part in msg.walk():
    if part.is_multipart():
        continue
    counter += 1
    fp = open(os.path.join(dir,'Part%s'%counter), 'wb')
    fp.write(part.get_payload(decode=1))
    fp.close()

M.logout() 



-- 
___
 |im    ---- ARM Powered ----



More information about the Python-list mailing list