Sorting Unix mailboxes

sfeil at io.com sfeil at io.com
Tue Sep 13 12:23:35 EDT 2005


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. 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". 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. I could create I temp box of non-deleted then copy to
the source box, but that seams messy.

Here is my example program..


def CopyToBox(Source,Address,Destination):
    AddressRE=re.compile(
           "([a-zA-Z0-9._-]+)@([a-zA-Z0-9._-]+)\.([a-zA-Z0-9]+)")
    InFile = open("/home/stevef/mail/%s" % Source)
    OutFile = open("/home/stevef/mail/%s" % Destination,"a")
    Box = mailbox.PortableUnixMailbox(InFile)
    Envelope=Box.next()
    while 1:
        Envelope=Box.next()
        if Envelope  == None:
            break
        print Envelope.getallmatchingheaders("from")[0]
        Match=AddressRE.search(
                     Envelope.getallmatchingheaders("from")[0])
        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)
                #OutFile.write(Message.get_unixfrom()) ##error
                OutFile.write("\n")
                OutFile.write(Message.as_string())
    InFile.close()
    OutFile.close()
    return




More information about the Python-list mailing list