[Tutor] Working with Email question [StringIO module]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sat, 23 Feb 2002 13:38:45 -0800 (PST)

On Sat, 23 Feb 2002, Joel Ricker wrote:

> > Python 2.2 has a new email module included, which looks to be very nice,
> > but I've been working with it, and:
> > (1) It is not well documented (at least, not from a beginner's point of
> > view)
> >  -AND-
> > (2) It is somewhat buggy IMO. For solid performance at this point, I'd
> > recommend rfc822 and if needed, multifile and mimetools.
> What I'll need to do is parse the headers for from and to address  and also
> subjects then look at the body for matching keywords -- like PORN ;)  I'm
> not that worried about attachements yet -- but in the future it would be
> nice to check for those Outlook Transmitted Diseases.
> So if I'm following the documentation correctly, I'll need to save each
> message to a local file since all of those mentioned use a file pointer.

And to avoid writing to a local file, we can use the StringIO module to
make strings look like files:


Here's an example:

>>> from StringIO import StringIO
>>> s = "Hello world, this is a test."
>>> f  = StringIO(s)
>>> f.read(1)
>>> f.read(1)
>>> f.read(1)
>>> f.read(1)
>>> f.read(1)
>>> f.seek(0)
>>> f.read()
'Hello world, this is a test.'