Two email module questions

Andrew Dalke adalke at
Thu Jan 9 11:32:52 CET 2003

Paul Mackinney wrote:
> 1. There are two obvious ways to use email.message_from_file. Am I
> correct in assuming that method a. is prefered, because method b. leaves
> an open file with no convenient way to close it?
>    a. fn  = file('foo','r')
>       msg = email.message_from_file(fn)
>    		fn.close()
>    b. msg = email.message_from_file(file('foo','r'))

There was a thread about this a week or two back.  It comes down to,
do you trust garbage collection or not?  If not, you'll probably want
to do

fn = file('foo', 'r')
   msg = email.message_from_file(fn)

I personally don't worry about it and go for b.

> 2. After importing a message, I get a bogus extra line at the top when I
>    print it:
>    >>> msg = message_from_file('foo')
>    >>> print msg
>    From nobody Thu Jan  9 01:16:54 2003
> What's going on here? The 'From nobody...' line doesn't show in
> msg.keys(), I couldn't find this behavior in the docs.

That's the "unixfrom" option.  Look at email.Message.__str__ and
you'll see

def __str__(self):
     """Return the entire formatted message as a string.
     This includes the headers, body, and envelope header.
     return self.as_string(unixfrom=True)

def as_string(self, unixfrom=False):
     """Return the entire formatted message as a string.
     Optional `unixfrom' when True, means include the Unix From_ envelope
     from email.Generator import Generator
     fp = StringIO()
     g = Generator(fp)
     g.flatten(self, unixfrom=unixfrom)
     return fp.getvalue()

So try 'print msg.tostring()'

(Erm, this is Python 2.3. Python 2.2's 'email' uses 0 and 1 instead
of False and True.)

					dalke at

More information about the Python-list mailing list