[Tutor] Getting mail out of the box and into the email module

Scot Stevenson scot@possum.in-berlin.de
Sat Feb 1 00:21:02 2003


Hi there, 

Progress strikes again: 

I'm rewriting an older program of mine that takes mail out of my mailbox, 
plays around with it and then saves it. Up until now, I've done it with the 
UnixMailbox part of the "mailbox" module, which you can hit with a "next()" 
method to get the individual mails as a rfc822.Message object. That was fun 
and worked, but it was one of my first larger efforts and the program, uh, 
sucks. Hence the rewrite.

Now, Python 2.2 has a new module called "email" which seems to be a lot easier 
to use and also seems set to superseed the rfc822 module. There is one small 
problem, though: I can't get the mailbox module to hand me an email.Message 
object. In theory, you can pass the mailbox object a "factory", but that only 
seems to work with rfc822: 

Python 2.2.1 (#1, Sep 10 2002, 17:49:17) 
[GCC 3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mailbox
>>> import email
>>> thebox = file("test.mbox", "r")
>>> rawbox = mailbox.UnixMailbox(thebox, email.Message)
>>> rawbox.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/lib/python2.2/mailbox.py", line 34, in next
    return self.factory(_Subfile(self.fp, start, stop))
TypeError: 'module' object is not callable

The difference seems to be that the email.Message constructor doesn't take 
arguments, in constrast to rfc822.Message, which takes anything that has a 
readline() method. Bummer. 

Of course, what I could do is take the rfc822.Message object, save it as a 
file (or rather a file-like object in memory), and reload it with some of the 
tricks of the email module -- but then I could just as well use the rfc822 
module directly. 

Now, am I missing something here, or has the mailbox module failed to go with 
the times? And just how do you get a message out of a Unix mailbox and into a 
email.Message object?

Thanks, 
Y, Scot

-- 
  Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany