python, mbox files and forwarding messages

Josiah Carlson jcarlson at uci.edu
Tue Oct 26 16:20:26 EDT 2004


> Can Python parse a mbox file and forward each individual message within 
> that file to someone else?

Yes.

> For example, let's say I have a 10MB mbox file that has 678 messages. 
> I'd like to send each of the messages to santa.claus at northpole.com... 
> how might I do that? Also, how might I handle messages that have an 
> attachment associated with them during the forward process?

import smtplib

def find_all_at_linestart(data, st):
    start = 0
    if data[:len(st)] == st:
        start += len(st)
        yield 0
    end = len(data)
    st = \n'+st
    while start < end:
        nstart = data.find(st, start, end)
        if nstart == -1:
            return
        start = nstart+len(st)
        yield nstart

def forward_email(mboxfname, email_from, email_to, host, port):
    mail = open('mboxfname', 'rb').read()
    lst = list(find_all_at_linestart(mail, 'From '))
    smtpc = smtplib.SMTP(host, port)
    for i in xrange(len(lst)-1):
        start = lst[i]
        end = lst[i+1]
        #strip off the mbox From ... line
        r = mail.find('\n', start, end)
        email = mail[r+1:end]
        if email:
            smtpc.sendmail(email_from, [email_to], email)
    start = lst[-1]
    end = len(mail)
    r = mail.find('\n', start, end)
    email = mail[r+1:end]
    if email:
        smtpc.sendmail(email_from, [email_to], email)
    smtpc.close()


Pardon if it doesn't quite work, this was done in my email client, and
has not been tested.

 - Josiah




More information about the Python-list mailing list