#! /usr/bin/env python

# Wikemail.py - import your emails into dokuwiki to create
# a searchable, wiki-able archive of you mail - Duncan Gough 23/10/04

import getpass, imaplib, re, rfc822, commands, email, os
from TaskThread import TaskThread

class ImapWiki(TaskThread):
	def __init__(self):
		TaskThread.__init__(self)

	def task(self):
		from_pattern = re.compile('From: (.*)')
		subject_pattern = re.compile('Subject: (.*)')
		to_pattern = re.compile('To: (.*)')
		date_pattern = re.compile('Date: (.*)')
		body_pattern = re.compile('^\n\s*?',re.MULTILINE)
		newline_pattern = re.compile('\n', re.MULTILINE)
		star_pattern = re.compile('\*', re.MULTILINE)
		
		M = imaplib.IMAP4()
		M.login('duncan@suttree.com','password')
		M.select()
		typ, data = M.search(None, '(UNSEEN UNDELETED)' or '(UNDELETED)')
		for num in data[0].split():
			typ, data = M.fetch(num, '(RFC822)')
			M.store(num, 'FLAGS', '(UNSEEN)')
			email_headers, email_body = re.split(r'\n\r?\n', data[0][1], 1)
		
			# Munge the email into a usable, wiki friendly format
			email_from = from_pattern.findall( data[0][1] )[0]
			email_from = rfc822.parseaddr( email_from )[1]
			email_to = to_pattern.findall( data[0][1] )[0]
			email_to = rfc822.parseaddr( email_to )[1]
			email_subject = subject_pattern.findall( data[0][1] )[0]
			rfc822_date = date_pattern.findall( data[0][1] )[0]
			email_date = rfc822.parsedate( rfc822_date.strip() )
		
			email_from = email_from.strip().lower()
			email_to = email_to.strip().lower()
			email_subject = email_subject.strip()

			wiki_date = str(email_date[0]) + ' ' + str(email_date[1]) + ' ' + str(email_date[2])
			wiki_from = email_from.replace( '@', '_at_' )
			wiki_to = email_to
		
			wiki_filename = email_subject.lower()
			wiki_filename = wiki_filename.replace( 're: ', '' )
			wiki_filename = wiki_filename.replace( 'fwd: ', '' )
			wiki_filename = wiki_filename.replace( ' ', '_' )
		
			email_body = email_body.strip()
			email_body = body_pattern.sub('', email_body)
			email_body = star_pattern.sub('-', email_body)
			
			message = ''
			message += '===== ' + email_subject.upper() + '=====\n\n'
			message += 'From: [[email:' + wiki_date + ':from:' + wiki_from + ']] (' + email_from + ')\n\n'
			message += 'To: ' + email_to + '\n\n'
			message += 'Date: [[email:' + wiki_date + ':combined|' + wiki_date + ']]\n\n'
			message += '==Message body==\n\n' + email_body + "\n\n"
		
			# Store it under the subject, from email and date
			try:
				os.stat('/home/duncan/suttree/dokuwiki/data/email/' + wiki_date.replace( ' ', '_' ) + '/subject/')
			except:
				os.makedirs('/home/duncan/suttree/dokuwiki/data/email/' + wiki_date.replace( ' ', '_' ) + '/subject/')

			try:
				os.stat('/home/duncan/suttree/dokuwiki/data/email/' + wiki_date.replace( ' ', '_' ) + '/from/')
			except:
				os.makedirs('/home/duncan/suttree/dokuwiki/data/email/' + wiki_date.replace( ' ', '_' ) + '/from/')

			f = open('/home/duncan/suttree/dokuwiki/data/email/' + wiki_date.replace( ' ', '_' ) + '/subject/' + wiki_filename + '.txt', 'a' )
			f.write(message)
			f.close
		
			f = open('/home/duncan/suttree/dokuwiki/data/email/' + wiki_date.replace( ' ', '_' ) + '/from/' + wiki_from + '.txt', 'a' )
			f.write(message)
			f.close
			
			f = open('/home/duncan/suttree/dokuwiki/data/email/' + wiki_date.replace( ' ', '_' ) + '/combined.txt', 'a' )
			f.write(message)
			f.close
		
		M.logout()

if __name__ == '__main__':
	wiki = ImapWiki()
	wiki.run()

