[Tutor] Using poplib and rfc822
Michael P. Reilly
arcege@speakeasy.net
Wed, 16 May 2001 07:43:29 -0400 (EDT)
anu gupta wrote
> I'm trying to write a python pop3 client (seems like a good way for me to
> learn python), and just wanted a quick piece of advice...
>
> I can use poplib to communicate with a pop3 server, and I can use rfc822 to
> parse message headers. So it would seem natural to use them together...
>
> But, poplib brings back mesgs as (I guess) lists, and rfc822 expects file
> objects (or something that has a readline method).
>
> So, do I need to convert my messages into files, and then create rfc822
> objects with these files ? I can see this would work, but it just seems a
> bit clunky and inefficient - I would rather parse the message headers myself
> in that case, but it seems a shame to reinvent this !
>
> Or am I missing out on some kind of "memory based" file object that I can
> use, which would eliminate the need to read/write to disk in this
> intermediate step ?
Yup, you can use the StringIO module (or cStringIO, a faster C module).
# get the StringIO class, preferably the C implementation
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
popsvr = poplib.POP(...)
rspc, lines, octets = popsvr.retr(msgn)
file = StringIO()
for line in lines:
file.write(line + '\n') # popsvr strips off the EOLN character
file.seek(0)
msg = rfc822.Message(file)
The StringIO uses memory for the storage. But be careful of large
messages, a megabyte e-mail will be stored in memory with the rest of
your program data.
Good luck,
-Arcege
--
+----------------------------------+-----------------------------------+
| Michael P. Reilly | arcege@speakeasy.net |