CSC220 parseEmail.py
--D. Thiebaut 22:34, 5 October 2010 (UTC)
#! /bin/env python
# parseEmamil.py
# D. Thiebaut
# Oct. 2010
#
# An example script that intercepts email messages
# and processes them in some fashion.
#
# Setup:
# in 220a account, create .forward file with this single line
#
# "|/usr/bin/python /Users/classes/220a/bin/parseMail.py", \220a
#
# First part indicates that message body should be 'piped' to the
# python program parseMail.py in ~220a/bin. Second part says that
# a copy of the message should be kept in mailbox of User 220a.
#
# This script appends the date, subject, sender, and body of the
# message to a file in ~220a/uploads called filtered.mail.txt
#
import sys
try:
#--- get the whole message in data ---
data = sys.stdin.readlines()
#--- prepare fields of interest ---
date = sender = subject = None
body = False
message = []
#--- scan all the lines ---
for line in data:
line = line.strip()
if line.find( "Date:" )== 0:
date = line.split( 'Date:' )[1]
continue
if line.find( "From:" )== 0:
sender = line.split( 'm:' )[1]
continue
if line.find( "Subject:" )== 0:
subject = line.split( 'Subject:' )[1]
continue
#--- first blank line is beginning of message (usually) ---
if len( line )<=1:
body = True
if body:
message.append( line )
continue
#--- write captured information to file ---
file = open( "/Users/classes/220a/uploads/filtered.mail.txt", "a" )
file.write( 'sender = %s\ndate = %s\nsubject = %s\n%s\n\n' %
( sender, date, subject, '\n'.join( message ) ) )
file.close()
except:
pass