Handling emails

Fulvio fulvio at tm.net.my
Tue Oct 24 17:29:36 CEST 2006

Your mail has been scanned by InterScan MSS.

On Tuesday 24 October 2006 01:12, Dennis Lee Bieber wrote:
> Message-id:
> <96D4BF841562DA44A7935AAC90A29D6405E5611B at emss01m12.us.lmco.com>
> as the ID is generally created when the message is submitted to the
> delivery system

Well, that's what I'm dealing with, since a couple of weeks :-) indeed.
Some might not have one, but Kmail should had fixed.
The second will be the way to get the whole email from the mbox file. My 
problem still remain, partially. I'm not sure if the below procedure will 
give me the emails off including multipart ones.

#! /usr/bin/env python

from __future__ import generators

import email, re
import mailbox
import email.Message

def getmbox(name):
    """Return an mbox iterator given a file/directory/folder name."""
    fp = open(name, "rb")
    mbox = mailbox.PortableUnixMailbox(fp, get_message)
    return iter(mbox)

def get_message(obj):
    """Return an email Message object."""

    if isinstance(obj, email.Message.Message):
        return obj
    # Create an email Message object.
    if hasattr(obj, "read"):
        obj = obj.read()
        msg = email.message_from_string(obj)
    except email.Errors.MessageParseError:

        obj = obj[len(headers):]
        msg = email.Message.Message()
    return msg

header_break_re = re.compile(r"\r?\n(\r?\n)")

def extract_headers(text):
    """Very simple-minded header extraction"""

    m = header_break_re.search(text)
    if m:
        eol = m.start(1)
        text = text[:eol]
    if ':' not in text:
        text = ""
    return text

if __name__ == '__main__':
    #simple trial with local mbox file
    import sys
        file =sys.argv[1]
    except IOError:
        print 'Must give a mbox file program /path/to_mbox'
    k = getmbox(file)
    while 1:
        full_email = get_message(k.next())
        print '%78s' %full_email
        answer= raw_input('More? Y/N')
        if answer.lower() == 'n': break

I admit that not all code is my genuine design, ;-) some other programs 
extrapolating have been done.


More information about the Python-list mailing list