aboutsummaryrefslogtreecommitdiff
path: root/philter.py
blob: 38229aa54ebe9ea133a445d41d3b327fb0055d11 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#! /usr/bin/python
#
# Email filter
#
# This is a slighted channged version of Philter available at
# http://philter.sourceforge.net written by Prabhakar V. Chaganti and
# distributed under GPLv2.
#
# Minor changes by rhatto at riseup.net.
#

import ConfigParser, os,  rfc822, re, string, posixpath


class Philter:
	def __init__(self,match,header,destination,maildir):
		self.re = re.compile(match)
		self.header = header
		self.destination = destination
		self.maildir = maildir

		
	def __str__(self):
		return ("philter : \n \t match: %s \n\t header: %s \n\t destination: %s \n\t maildir: %s"  %
			(self.re,self.header,self.destination,self.maildir))


	
class PhilterDriver:
	__propFile = open(string.join((posixpath.expanduser('~'),'/.config/scripts/philterrc'),''))
	__newDir = '/new'
	
	def createPhilters(self):
		sections = PhilterDriver.__config.sections()
		sections.sort()
		philters=[]
		maildir = PhilterDriver.__config.get('DEFAULT','maildir')
		for section in sections:
			philters.append(Philter((PhilterDriver.__config.get(section,'match')),
						string.split(PhilterDriver.__config.get(section,'header'),','),
						PhilterDriver.__config.get(section,'destination'),
						string.join((maildir,'/',PhilterDriver.__config.get(section,'destination'),'/new'),'')))
		return philters


	def parseConfig(self):
		PhilterDriver.__config = ConfigParser.ConfigParser()
		PhilterDriver.__config.readfp(PhilterDriver.__propFile)


	def philterMaildir(self, philters):
		inbox = string.join([PhilterDriver.__config.get('DEFAULT','maildir'),
				     "/",PhilterDriver.__config.get('DEFAULT','inbox'),
				     PhilterDriver.__newDir],"")
		newMessages = os.listdir(inbox)
		maildir = PhilterDriver.__config.get('DEFAULT','maildir')
		found = 0
		for newMessage in newMessages:
			msg =  rfc822.Message(open(string.join([inbox,"/",newMessage],"")))
			for philter in philters:
				for hdr in philter.header:
					if msg.getheader(hdr):
						if philter.re.search(string.lower(msg.getheader(hdr))):
							os.rename(string.join((maildir,'INBOX/new/',newMessage),''),
								  string.join((philter.maildir,'/',newMessage),''))
							found = 1	
							break

				if found:
					found = 0
					break

		
	def  main(self):
		driver = PhilterDriver()
		driver.parseConfig()
		philters = driver.createPhilters()
		driver.philterMaildir(philters)


		
if __name__ == '__main__':
	PhilterDriver().main()