#!/usr/bin/env python
# timestamp.py
# Author: Zachary Cutlip
# twitter: @zcutlip
# Purpose: A program to fix sorting of mail messages that have been POPed or
# IMAPed in the wrong order. Compares time stamp sent and timestamp
# received on an RFC822-formatted email message, and renames the
# message file using the most recent timestamp that is no more than
# 24 hours after the date sent. Updates the file\'s atime/mtime with
# the timestamp, as well. Does not modify the headers or contents of
# the message.
import sys
import os
import email
import email.utils
import re
regex=re.compile("([0-9]+)(\\..*$)")
msg_filename=sys.argv[1]
print msg_filename
msg=email.message_from_file(open(msg_filename,"r"))
datesent=email.utils.mktime_tz(email.utils.parsedate_tz(msg.get("Date")))
#print datesent
date_rx=0
for rx_hdr in msg.get_all("Received"):
rx_date_str=rx_hdr.split(";")[-1]
#print rx_date_str
tmp_rx=email.utils.mktime_tz(email.utils.parsedate_tz(rx_date_str))
if(tmp_rx - datesent) > (24*60*60):
continue
date_rx=tmp_rx
break
#print date_rx
#received header missing?
if(date_rx < 1):
date_rx = datesent
m=regex.match(msg_filename)
if len(m.groups()) == 2:
newfilename=str(int(date_rx))+m.groups()[1]
print newfilename
if os.path.isfile(newfilename):
print "File exists!: "+newfilename
else:
os.rename(msg_filename,newfilename)
os.utime(newfilename,(date_rx,date_rx))