|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+import re
|
|
|
2
|
+import platform
|
|
|
3
|
+import subprocess
|
|
|
4
|
+from tempfile import TemporaryDirectory
|
|
|
5
|
+from typing import List, Union
|
|
|
6
|
+from enum import Enum
|
|
|
7
|
+from email.utils import parsedate
|
|
|
8
|
+from email.parser import BytesParser
|
|
|
9
|
+from email.message import EmailMessage
|
|
|
10
|
+from zipfile import ZipFile, ZipInfo
|
|
|
11
|
+import sys
|
|
|
12
|
+import os
|
|
|
13
|
+
|
|
|
14
|
+class BooleanOperator(Enum):
|
|
|
15
|
+ and_op = 1
|
|
|
16
|
+ or_op = 2
|
|
|
17
|
+
|
|
|
18
|
+class Filter:
|
|
|
19
|
+ """Base class for message filters."""
|
|
|
20
|
+ def matches(self, message: EmailMessage) -> bool:
|
|
|
21
|
+ raise "Not implemented"
|
|
|
22
|
+
|
|
|
23
|
+class BodyKeywordFilter(Filter):
|
|
|
24
|
+ """Simple substring search filter."""
|
|
|
25
|
+ def __init__(self, keyword: str, case_sensitive: bool = False):
|
|
|
26
|
+ self.keyword: str = keyword
|
|
|
27
|
+ self.case_sensitive: bool = case_sensitive
|
|
|
28
|
+
|
|
|
29
|
+ def matches(self, message: EmailMessage) -> bool:
|
|
|
30
|
+ for part in message.walk():
|
|
|
31
|
+ if part.get_content_maintype() == 'text':
|
|
|
32
|
+ if self.case_sensitive:
|
|
|
33
|
+ if self.keyword in part.as_string():
|
|
|
34
|
+ return True
|
|
|
35
|
+ else:
|
|
|
36
|
+ if self.keyword.lower() in part.as_string().lower():
|
|
|
37
|
+ return True
|
|
|
38
|
+ return False
|
|
|
39
|
+
|
|
|
40
|
+class HeaderFilter(Filter):
|
|
|
41
|
+ """Matches a value in an email header. Can search one filter or multiple.
|
|
|
42
|
+ Header names case-insensitive; value is case-insensitive."""
|
|
|
43
|
+ def __init__(self, headers: Union[str, List[str]], value: str):
|
|
|
44
|
+ self.headers: List[str] = [headers] if isinstance(headers, str) else headers
|
|
|
45
|
+ self.value = value
|
|
|
46
|
+
|
|
|
47
|
+ def matches(self, message: EmailMessage) -> bool:
|
|
|
48
|
+ for header in self.headers:
|
|
|
49
|
+ val = message.get(header, None)
|
|
|
50
|
+ if val is None:
|
|
|
51
|
+ continue
|
|
|
52
|
+ if self.value.lower() in val.lower():
|
|
|
53
|
+ return True
|
|
|
54
|
+ return False
|
|
|
55
|
+
|
|
|
56
|
+class BooleanFilter(Filter):
|
|
|
57
|
+ """Combines other filters with OR/AND logic."""
|
|
|
58
|
+ def __init__(self, operator: BooleanOperator, subfilters: list):
|
|
|
59
|
+ self.operator = operator
|
|
|
60
|
+ self.subfilters: List[Filter] = subfilters
|
|
|
61
|
+
|
|
|
62
|
+ def matches(self, message: EmailMessage) -> bool:
|
|
|
63
|
+ for subfilter in self.subfilters:
|
|
|
64
|
+ result = subfilter.matches(message)
|
|
|
65
|
+ if self.operator == BooleanOperator.and_op and not result:
|
|
|
66
|
+ return False
|
|
|
67
|
+ if self.operator == BooleanOperator.or_op and result:
|
|
|
68
|
+ return True
|
|
|
69
|
+ if self.operator == BooleanOperator.and_op:
|
|
|
70
|
+ return True
|
|
|
71
|
+ return False
|
|
|
72
|
+
|
|
|
73
|
+start_path = '.'
|
|
|
74
|
+output_path = TemporaryDirectory(prefix='Email search results (id ', suffix=')').name
|
|
|
75
|
+filter = None
|
|
|
76
|
+case_sensitive = False
|
|
|
77
|
+result_count = 0
|
|
|
78
|
+zip_result_count = 0
|
|
|
79
|
+zip_count = 0
|
|
|
80
|
+
|
|
|
81
|
+def clean_filename(original: str) -> str:
|
|
|
82
|
+ """Returns a scrubbed string with safe filename characters."""
|
|
|
83
|
+ return re.sub(r'[^a-zA-Z0-9 \.!,\(\)\[\]_-]+', '', original)
|
|
|
84
|
+
|
|
|
85
|
+def filename_from_email(email: EmailMessage) -> str:
|
|
|
86
|
+ """Creates a safe filename to save the given email to."""
|
|
|
87
|
+ filename = ''
|
|
|
88
|
+ date_str = email.get('Date', None)
|
|
|
89
|
+ if date_str is not None:
|
|
|
90
|
+ parsed_date = parsedate(date_str)
|
|
|
91
|
+ if parsed_date is not None:
|
|
|
92
|
+ filename += f'{parsed_date[0]:04}-{parsed_date[1]:02}-{parsed_date[2]:02}' + \
|
|
|
93
|
+ f'T{parsed_date[3]:02}.{parsed_date[4]:02}.{parsed_date[5]:02}' + \
|
|
|
94
|
+ ' - '
|
|
|
95
|
+ else:
|
|
|
96
|
+ filename += '0000-00-00T00.00.00 - '
|
|
|
97
|
+ else:
|
|
|
98
|
+ filename += '0000-00-00T00.00.00 - '
|
|
|
99
|
+ subject = email.get('Subject')
|
|
|
100
|
+ if subject is not None:
|
|
|
101
|
+ filename += clean_filename(subject)[0:50].strip()
|
|
|
102
|
+ else:
|
|
|
103
|
+ filename += '(no subject)'
|
|
|
104
|
+ filename += '.eml'
|
|
|
105
|
+ return filename
|
|
|
106
|
+
|
|
|
107
|
+def walk_directory(dir: str) -> None:
|
|
|
108
|
+ """Spiders a directory looking for subdirectories and email zip archives."""
|
|
|
109
|
+ global zip_count
|
|
|
110
|
+ for f in os.listdir(dir):
|
|
|
111
|
+ full_path = dir + os.sep + f
|
|
|
112
|
+ if f.lower().endswith('.zip'):
|
|
|
113
|
+ zip_count += 1
|
|
|
114
|
+ process_zip_file(full_path)
|
|
|
115
|
+ if os.path.isdir(f):
|
|
|
116
|
+ walk_directory(full_path)
|
|
|
117
|
+
|
|
|
118
|
+def process_zip_file(zip_path: str) -> None:
|
|
|
119
|
+ """Processes a zip file of email messages."""
|
|
|
120
|
+ global zip_result_count
|
|
|
121
|
+ print('Searching ' + zip_path + '...')
|
|
|
122
|
+ zip_result_count = 0
|
|
|
123
|
+ with ZipFile(zip_path, mode='r') as zip:
|
|
|
124
|
+ for entry in zip.filelist:
|
|
|
125
|
+ if entry.is_dir():
|
|
|
126
|
+ continue
|
|
|
127
|
+ data = zip.read(entry)
|
|
|
128
|
+ parser = BytesParser()
|
|
|
129
|
+ try:
|
|
|
130
|
+ email = parser.parsebytes(data)
|
|
|
131
|
+ search_content(email, zip_path, entry)
|
|
|
132
|
+ except UnicodeError:
|
|
|
133
|
+ print('Unicode error in message. Skipping.')
|
|
|
134
|
+ except:
|
|
|
135
|
+ print('Error reading message')
|
|
|
136
|
+ if zip_result_count > 0:
|
|
|
137
|
+ print(f"\t{zip_result_count} results in zip")
|
|
|
138
|
+
|
|
|
139
|
+def search_content(email: EmailMessage, zip_path: str, entry: ZipInfo) -> None:
|
|
|
140
|
+ """Processes an email message in a zip file."""
|
|
|
141
|
+ global result_count, zip_result_count
|
|
|
142
|
+ if filter.matches(email):
|
|
|
143
|
+ if not os.path.exists(output_path):
|
|
|
144
|
+ os.makedirs(output_path)
|
|
|
145
|
+ with open(output_path + os.sep + filename_from_email(email), 'wb') as f:
|
|
|
146
|
+ result_count += 1
|
|
|
147
|
+ zip_result_count += 1
|
|
|
148
|
+ f.write(email.as_bytes())
|
|
|
149
|
+
|
|
|
150
|
+def parse_arguments():
|
|
|
151
|
+ """Parses the command-line arguments."""
|
|
|
152
|
+ global filter
|
|
|
153
|
+ global start_path
|
|
|
154
|
+ global output_path
|
|
|
155
|
+ global case_sensitive
|
|
|
156
|
+ expect = 'script_name'
|
|
|
157
|
+ for arg in sys.argv:
|
|
|
158
|
+ if arg.startswith('-'):
|
|
|
159
|
+ if arg == '-d':
|
|
|
160
|
+ expect = 'start_path'
|
|
|
161
|
+ elif arg == '-o':
|
|
|
162
|
+ expect = 'output_path'
|
|
|
163
|
+ elif arg == '-c':
|
|
|
164
|
+ case_sensitive = True
|
|
|
165
|
+ else:
|
|
|
166
|
+ raise f'Unknown argument {arg}'
|
|
|
167
|
+ elif expect is not None:
|
|
|
168
|
+ if expect == 'script_name':
|
|
|
169
|
+ expect = None
|
|
|
170
|
+ continue
|
|
|
171
|
+ elif expect == 'start_path':
|
|
|
172
|
+ start_path = arg
|
|
|
173
|
+ expect = None
|
|
|
174
|
+ elif expect == 'output_path':
|
|
|
175
|
+ output_path = arg
|
|
|
176
|
+ expect = None
|
|
|
177
|
+ else:
|
|
|
178
|
+ raise f'Expected other argument {expect}'
|
|
|
179
|
+ else:
|
|
|
180
|
+ if filter is None:
|
|
|
181
|
+ words = arg.split(' ')
|
|
|
182
|
+ word_filters = []
|
|
|
183
|
+ for word in words:
|
|
|
184
|
+ word = word.strip()
|
|
|
185
|
+ if len(word) == 0:
|
|
|
186
|
+ continue
|
|
|
187
|
+ word_filters.append(BodyKeywordFilter(word, case_sensitive))
|
|
|
188
|
+ if len(word_filters) == 0:
|
|
|
189
|
+ continue
|
|
|
190
|
+ filter = BooleanFilter(BooleanOperator.and_op, word_filters)
|
|
|
191
|
+ else:
|
|
|
192
|
+ print('Too many arguments')
|
|
|
193
|
+ sys.exit(4)
|
|
|
194
|
+
|
|
|
195
|
+def validate_arguments():
|
|
|
196
|
+ if filter is None:
|
|
|
197
|
+ print('No filter specified')
|
|
|
198
|
+ sys.exit(3)
|
|
|
199
|
+ pass
|
|
|
200
|
+
|
|
|
201
|
+def handle_results():
|
|
|
202
|
+ """Final logic after all searching is completed."""
|
|
|
203
|
+ if result_count > 0:
|
|
|
204
|
+ if platform.system() == 'Darwin':
|
|
|
205
|
+ subprocess.call(['open', output_path])
|
|
|
206
|
+ elif platform.system() == 'Windows':
|
|
|
207
|
+ subprocess.call(['explorer.exe', output_path])
|
|
|
208
|
+ print(f'Found {result_count} result(s) total')
|
|
|
209
|
+ elif zip_count == 0:
|
|
|
210
|
+ print('No zip files found')
|
|
|
211
|
+ sys.exit(2)
|
|
|
212
|
+ else:
|
|
|
213
|
+ print('No results')
|
|
|
214
|
+ sys.exit(1)
|
|
|
215
|
+
|
|
|
216
|
+# Main logic
|
|
|
217
|
+parse_arguments()
|
|
|
218
|
+validate_arguments()
|
|
|
219
|
+walk_directory(start_path)
|
|
|
220
|
+handle_results()
|