#!/usr/bin/env python
#This script is a barebones way to see what is in my inbox
#and to read individual messages.
#Sort of a poor man's mail reader (but no sending emails).
#It makes no changes to INBOX.
#Mostly to work around issues reading mail on my Moto Q
#I added something to only show a certain number of characters
#at a time on screen, sort of a poor man's more.
#v1.1
#8/22/2007
#v1.0
#7/20/2007

#Copyright 2007 John C. Vernaleo
#Unfortunately, I am not comfortable putting unobscured email addresses
#on the web, but these shouldn't be too hard to figure out.
#
#		(my_first_name)@netpurgatory.com
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import os
import re
import sys
import email

path="/var/mail/"+os.getlogin()
#This path is for testing purposes.
#path="/home/"+os.getlogin()+"/tmp/"+os.getlogin()

if os.path.exists(path):
    print "Reading mail at ",path
else:
    print path," Not found"
    sys.exit()

nmail=0
i=0
fromindex=[]
fromlines=[]
maxcharacters=500

mailfile=open(path,'r')
mail=mailfile.readlines()
mailfile.close()

for line in mail:
    if re.search("^From ",line):
        if not re.search("^From MAILER-DAEMON",line):
            fromindex.append(i)
            nmail+=1
            fromlines.append(line.rstrip("\n"))
    i+=1
fromindex.append(i-1)

def get_message(index,indexlist,mail):
    cmail=""
    for i in range(indexlist[index-1],indexlist[index]):
        if not re.search("^X-",mail[i]):
            cmail=cmail+mail[i]
        msg = email.message_from_string(cmail)
    return msg

if __name__ == "__main__":
    if(len(sys.argv) > 1):
        messageindex=int(sys.argv[1])
        if messageindex > nmail:
            print "You only have",nmail,"messages in your INBOX."
            sys.exit()
        msg=get_message(messageindex,fromindex,mail)
        print "Message Number",messageindex
        print fromlines[messageindex-1],"\n"
        message=msg.get_payload()
        j=0
        for i in range(0,len(message)):
            j+=1
            sys.stdout.write(message[i])
            if j >= maxcharacters:
                raw_input()
                j=0
    else:
        for i in range(1,len(fromlines)+1):
            print i,fromlines[i-1]
        print nmail," total messages in INBOX"
