# Name: find-email.py # By: Jim Cameron # Created: 2015-09-12 # Last Modified: 2015-09-12 # Version: 0.1 # URL: http://support.moonpoint.com/downloads/computer_languages/python/find-email.py # # Purpose: # Search a mailbox file in mbox format for lines that start with "From" that # contain the specified string, which can be a full email address, a name, a # domain name, e.g. "hotmail.com". etc. For the messages with a matching # "From" address, if "brief" mode is chosen, print the sender email address # and after the entire file has been processed, print the total count of # matches. Otherwise, print the full message for each message found from # any matching sender. import sys from_address = "example.com" mbox_file = "/var/spool/mail/jdoe" # If brief is "True", print just "from", "subject", and "date lines # If it is "False" print the entire message to the file specified by outfile brief = False fh = open(mbox_file) def brief_message(): count = 0 for line in fh: if line.startswith('From '): if from_address in line: count += 1 ln = line.split() # Print just the email address found on the "From" line print "From: ", ln[1] for line in fh: if "Subject: " in line: print line.rstrip('\n') # Find the date the message was sent for line in fh: if "Date: " in line: print line break break print count, "matches found" def full_message(): for line in fh: if line.startswith('From '): if from_address in line: sys.stdout.write(line) for line in fh: if not line.startswith('From '): sys.stdout.write(line) else: break if brief: brief_message() else: full_message()