Sorting Unix mailboxes

Tom Anderson twic at
Thu Sep 15 14:39:29 CEST 2005

[posted and mailed, in case the OP has given up on reading the group!]

On Tue, 13 Sep 2005, sfeil at wrote:

> I'm writing a program in python to sort the mail in standard Unix
> email boxes. In my "prof of concept" example I am coping a letter to a
> second mailbox if the letter was send from a particular email
> address. When I read the destination mailbox with cat, I can see that
> something is getting copied to it, but the mail program does not
> recognize any new letters in the destination mailbox. It would seam
> that the "OutFile.write(Message.get_unixfrom())" line is
> essential.

Absolutely! The From line is the key element in mailbox structure.

> However if I run with this line uncommented then I get an the following 
> error. "TypeError: argument 1 must be string or read-only character 
> buffer, not None".

This is happening because Message.get_unixfrom is returning None, rather 
than a proper From line. According to its documentation, thus method 
"defaults to None if the envelope header was never set". Since you've 
never set the envelope header, this behaviour is therefore not surprising. 
But didn't the envelope header get set when you created the message? 
Actually, no - you created it with "email.message_from_file(Envelope.fp)", 
which reads the contents of the email from the file Envelope.fp. 
Envelope.fp, however, isn't the complete text of the mailbox entry, it's 
just (AFAICT) the payload of the message. Therefore, the message you 
create has no headers or envelope, just the body.

> I created this program by following an example posted somewhere on the 
> Internet, that I can't seam to find anymore. At one time I was able to 
> get Python to put new letters in a mailbox.
> Also, I was wondering is there were a way to use Python to delete items 
> from a mailbox.

Not really. This is a universal problem which affects all programs, 
regardless of language, with work with file formats consisting of 
variable-sized records - there's no wasy way to delete them.

> I could create I temp box of non-deleted then copy to the source box, 
> but that seams messy.

A cleaner way would be to copy the non-deleted messages to a new file, 
then to throw away the old file and rename the new one to replace it. This 
would avoid the second copy. Alternatively, you could read and write 
simultaneously with one file, then truncate at the end; this takes a bit 
more care, though.

> Here is my example program..

Right. Some of this makes sense to me, but there's quite a lot here that i 
don't get. Perhaps some of this is a result of the code being excised from 
its natural context, though.

> def CopyToBox(Source,Address,Destination):
>    AddressRE=re.compile(
>           "([a-zA-Z0-9._-]+)@([a-zA-Z0-9._-]+)\.([a-zA-Z0-9]+)")

Why did you write the regexp to capture the address as three groups? It 
seems like the only thing you ever do with the groups is put them back 
together again!

Also, it's better to define the regexp once, at global scope, to avoid 
having to compile it every time the function runs.

>    InFile = open("/home/stevef/mail/%s" % Source)
>    OutFile = open("/home/stevef/mail/%s" % Destination,"a")
>    Box = mailbox.PortableUnixMailbox(InFile)

Why 'Envelope'? That object is a Message, not an Envelope!

And did you really mean to throw away the first message in the box like 

>    while 1:
>        if Envelope  == None:
>            break

Why an infinite loop with a break and an explicit next call? Why not a for 
loop over the mailbox?

>        print Envelope.getallmatchingheaders("from")[0]
>                     Envelope.getallmatchingheaders("from")[0])

Why getallmatchingheaders("from")[0] rather than 

>        if Match:
>            Set=Match.groups()
>            if "%s@%s.%s" % Set == Address:
>                print "Copy letter from  %s@%s.%s" % Set
>                Message = email.message_from_file(Envelope.fp)

Message now contains the email's payload, but not its headers or envelope 
details, so ...

>                #OutFile.write(Message.get_unixfrom()) ##error

That doesn't work.

>                OutFile.write("\n")
>                OutFile.write(Message.as_string())
>    InFile.close()
>    OutFile.close()
>    return

There's no need for an explicit return here.

I have to sympathise with you over python's mail-handling libraries, 
though; having both the rfc822 and email modules around at the same time 
is quite a headache. Luckily, there's a way to make things simpler and 
much easier to work with, using a trick described in the docs for the 
mailbox module: rather than letting the mailbox module make the message 
objects (using the rfc822 module to do it), we can supply our own message 
factory function, with which we can create email-module messages right 
from the start. You need a function like this:

def msgfactory(f):
 	while True:
 			return email.message_from_file(f)

Then you can make a mailbox like this:

mbox = mailbox.PortableUnixMailbox(f, msgfactory)

The messages in it will then be email.Message instances.

I'd then write the main function like this (you'll need to import 

MBOX_DIR = "/home/stevef/mail"

def CopyToBox(src, addr, dst):
 	in_ = file(os.path.join(MBOX_DIR, src))
 	out = file(os.path.join(MBOX_DIR, dst), "a")
 	for mail in mailbox.PortableUnixMailbox(in_, msgfactory):
 		if (addr in mail["from"]):

Simple, eh?


Also, a 'dark future where there is only war!' ... have you seen the news lately? -- applez

More information about the Python-list mailing list