Search utility for my zipped email archives
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. """Script for searching email messages in a collection of zip files of raw email message files."""
  2. import argparse
  3. import os
  4. import platform
  5. import re
  6. import subprocess
  7. import sys
  8. from email.message import EmailMessage
  9. from email.parser import BytesParser
  10. from email.utils import parsedate
  11. from enum import Enum
  12. from tempfile import TemporaryDirectory
  13. from typing import List, Optional, Union
  14. from zipfile import ZipFile
  15. class BooleanOperator(Enum):
  16. """Boolean combinatory operator enum."""
  17. and_op = 1
  18. or_op = 2
  19. class Filter:
  20. """Base class for message filters."""
  21. def matches(self, message: EmailMessage) -> bool:
  22. """Returns true if the given email message matches this filter's criteria."""
  23. raise AssertionError("Not implemented")
  24. def matches_raw(self, raw_content: str) -> bool:
  25. """Returns true if the given raw, unparsed email content matches this filter's criteria."""
  26. raise AssertionError("Not implemented")
  27. def supports_raw(self) -> bool:
  28. """Whether this filter supports raw messages at least partially."""
  29. return False
  30. class BodyKeywordFilter(Filter):
  31. """Simple substring search filter."""
  32. def __init__(self, keyword: str, case_sensitive: bool = False):
  33. self.keyword: str = keyword
  34. self.case_sensitive: bool = case_sensitive
  35. def matches(self, message: EmailMessage) -> bool:
  36. for part in message.walk():
  37. if part.get_content_maintype() == 'text':
  38. if self.case_sensitive:
  39. if self.keyword in part.as_string():
  40. return True
  41. else:
  42. if self.keyword.lower() in part.as_string().lower():
  43. return True
  44. return False
  45. def matches_raw(self, raw_content: str) -> bool:
  46. if self.case_sensitive:
  47. if self.keyword in raw_content:
  48. return True
  49. else:
  50. if self.keyword.lower() in raw_content.lower():
  51. return True
  52. return False
  53. def supports_raw(self) -> bool:
  54. return True
  55. class HeaderFilter(Filter):
  56. """Matches a value in an email header. Can search one filter or multiple.
  57. Header names case-insensitive; value is case-insensitive."""
  58. def __init__(self, headers: Union[str, List[str]], value: str):
  59. self.headers: List[str] = [headers] if isinstance(headers, str) else headers
  60. self.value = value
  61. def matches(self, message: EmailMessage) -> bool:
  62. for header in self.headers:
  63. val = message.get(header, None)
  64. if val is None:
  65. continue
  66. if self.value.lower() in val.lower():
  67. return True
  68. return False
  69. class BooleanFilter(Filter):
  70. """Combines other filters with OR/AND logic."""
  71. def __init__(self, operator: BooleanOperator, subfilters: list):
  72. self.operator = operator
  73. self.subfilters: List[Filter] = subfilters
  74. def matches(self, message: EmailMessage) -> bool:
  75. for subfilter in self.subfilters:
  76. result = subfilter.matches(message)
  77. if self.operator == BooleanOperator.and_op and not result:
  78. return False
  79. if self.operator == BooleanOperator.or_op and result:
  80. return True
  81. if self.operator == BooleanOperator.and_op:
  82. return True
  83. return False
  84. def matches_raw(self, raw_content: str) -> bool:
  85. for subfilter in self.subfilters:
  86. result = subfilter.matches_raw(raw_content)
  87. if self.operator == BooleanOperator.and_op and not result:
  88. return False
  89. if self.operator == BooleanOperator.or_op and result:
  90. return True
  91. if self.operator == BooleanOperator.and_op:
  92. return True
  93. return False
  94. def supports_raw(self) -> bool:
  95. for subfilter in self.subfilters:
  96. if subfilter.supports_raw():
  97. return True
  98. return False
  99. class DateFilter(Filter):
  100. """Filters messages based on the date field. For each message with a parseable
  101. date field, the given comparator is called with a `maketime` list representation
  102. of the date and time. The comparator must return a bool of whether to match
  103. the given date or not."""
  104. def __init__(self, comparator):
  105. self.comparator = comparator
  106. def matches(self, message: EmailMessage) -> bool:
  107. date_str = message.get('date', None)
  108. if date_str is None:
  109. return False
  110. date_elems = parsedate(date_str)
  111. if date_elems is None:
  112. return False
  113. return self.comparator(date_elems)
  114. class Options:
  115. """Parsed command-line options."""
  116. def __init__(self):
  117. self.keywords: List[str] = []
  118. self.any: bool = False
  119. self.dir: List[str] = []
  120. self.output: Optional[str] = None
  121. self.casesensitive: bool = False
  122. setattr(self, 'from', None)
  123. setattr(self, 'to', None)
  124. self.subject: Optional[str] = None
  125. self.before: Optional[List[int]] = None
  126. self.after: Optional[List[int]] = None
  127. args: Options = Options()
  128. message_filter: Filter = None
  129. result_count = 0
  130. zip_result_count = 0
  131. zip_count = 0
  132. parser: argparse.ArgumentParser = None
  133. def compare_dates(a: List[int], b: List[int]) -> int:
  134. """Compares two list representations of `maketime` date-times. Returns -1 if a < b,
  135. 1 if a > b, and 0 if they are equal."""
  136. for i in range(6):
  137. a_elem = a[i] if i < len(a) else -1
  138. b_elem = b[i] if i < len(b) else -1
  139. if a_elem < b_elem:
  140. return -1
  141. if a_elem > b_elem:
  142. return 1
  143. return 0
  144. def clean_filename(original: str) -> str:
  145. """Returns a scrubbed string with safe filename characters."""
  146. return re.sub(r'[^a-zA-Z0-9 \.!,\(\)\[\]_-]+', '', original)
  147. def filename_from_email(email: EmailMessage) -> str:
  148. """Creates a safe filename to save the given email to."""
  149. filename = ''
  150. date_str = email.get('date', None)
  151. if date_str is not None:
  152. parsed_date = parsedate(date_str)
  153. if parsed_date is not None:
  154. filename += f'{parsed_date[0]:04}-{parsed_date[1]:02}-{parsed_date[2]:02}' + \
  155. f'T{parsed_date[3]:02}.{parsed_date[4]:02}.{parsed_date[5]:02}' + \
  156. ' - '
  157. else:
  158. filename += '0000-00-00T00.00.00 - '
  159. else:
  160. filename += '0000-00-00T00.00.00 - '
  161. filename += f'{result_count:04} - '
  162. subject = email.get('subject')
  163. if subject is not None:
  164. filename += clean_filename(subject)[0:50].strip()
  165. else:
  166. filename += '(no subject)'
  167. filename += '.eml'
  168. return filename
  169. def walk_directory(directory: str) -> None:
  170. """Spiders a directory looking for subdirectories and email zip archives."""
  171. global zip_count
  172. for f in os.listdir(directory):
  173. full_path = directory + os.sep + f
  174. if f.lower().endswith('.zip'):
  175. zip_count += 1
  176. process_zip_file(full_path)
  177. if os.path.isdir(full_path):
  178. walk_directory(full_path)
  179. def process_zip_file(zip_path: str) -> None:
  180. """Processes a zip file of email messages."""
  181. global parser, zip_result_count
  182. print('Searching ' + zip_path + '...')
  183. zip_result_count = 0
  184. with ZipFile(zip_path, mode='r') as z:
  185. for entry in z.filelist:
  186. if entry.is_dir():
  187. continue
  188. data = z.read(entry)
  189. parser = BytesParser()
  190. try:
  191. email = parser.parsebytes(data)
  192. search_content(email)
  193. except:
  194. if message_filter.supports_raw():
  195. search_raw_content(data)
  196. else:
  197. print('Message cannot be parsed. Skipping.')
  198. if zip_result_count > 0:
  199. print(f"\t{zip_result_count} results in zip")
  200. def search_content(email: EmailMessage) -> None:
  201. """Processes an email message in a zip file."""
  202. if message_filter.matches(email):
  203. save_message(email)
  204. def search_raw_content(raw_bytes: bytes) -> None:
  205. """Searches an unparsed email message."""
  206. encodings = [ 'ascii', 'iso-8859-1', 'utf-8' ]
  207. content = None
  208. for encoding in encodings:
  209. try:
  210. content = raw_bytes.decode(encoding)
  211. break
  212. except:
  213. pass
  214. if content is None:
  215. print('Cannot decode email bytes. Skipping message.', file=sys.stderr)
  216. return
  217. print('Could not parse message. Searching raw content.', file=sys.stderr)
  218. if message_filter.matches_raw(content):
  219. save_raw_message(raw_bytes)
  220. def save_message(email: EmailMessage) -> None:
  221. """Saves a matching message to the results directory."""
  222. global result_count, zip_result_count
  223. if not os.path.exists(args.output):
  224. os.makedirs(args.output)
  225. with open(args.output + os.sep + filename_from_email(email), 'wb') as f:
  226. result_count += 1
  227. zip_result_count += 1
  228. f.write(email.as_bytes())
  229. def save_raw_message(content: bytes) -> None:
  230. """Saves an unparseable matching message to the results directory."""
  231. global result_count, zip_result_count
  232. if not os.path.exists(args.output):
  233. os.makedirs(args.output)
  234. filename = f'unparseable-match-{result_count:04}.eml'
  235. with open(args.output + os.sep + filename, 'wb') as f:
  236. result_count += 1
  237. zip_result_count += 1
  238. f.write(content)
  239. def parse_arguments():
  240. """Parses command-line arguments to `args`."""
  241. global args, parser
  242. parser = argparse.ArgumentParser(
  243. prog='search.py',
  244. description='Searches a directory of zipped email messages. ' + \
  245. 'Messages are assumed to be stored one per file within the zip files (Maildir format). ' + \
  246. 'Input directories are searched recursively for any zip files contained within.'
  247. )
  248. parser.add_argument(
  249. 'keywords',
  250. action='append',
  251. nargs='*',
  252. help='one or more phrases to search for in the message body'
  253. )
  254. parser.add_argument(
  255. '--any',
  256. default=False,
  257. action='store_true',
  258. help='matches messages containing any of the given search phrases (default requires ' + \
  259. 'all phrases appear in a message)'
  260. )
  261. parser.add_argument(
  262. '-d', '--dir',
  263. action='append',
  264. help='directory(s) to search for email zip archives (default is working directory)'
  265. )
  266. parser.add_argument(
  267. '-o', '--output',
  268. help='directory to copy matching messages to (default is a temp directory)'
  269. )
  270. parser.add_argument(
  271. '-c', '--casesensitive',
  272. default=False,
  273. action='store_true',
  274. help='search case-sensitively (default is case-insensitive)'
  275. )
  276. parser.add_argument(
  277. '-f', '--from',
  278. metavar='sender-email',
  279. help='email address of sender'
  280. )
  281. parser.add_argument(
  282. '-t', '--to',
  283. metavar='recipient-email',
  284. help='email address of recipient (searches to:, cc:, bcc: fields)'
  285. )
  286. parser.add_argument(
  287. '-s', '--subject',
  288. help='searches subject field'
  289. )
  290. parser.add_argument(
  291. '-a', '--after',
  292. metavar='YYYY-MM-DD',
  293. help='date to search on or after'
  294. )
  295. parser.add_argument(
  296. '-b', '--before',
  297. metavar='YYYY-MM-DD',
  298. help='date to search on or before'
  299. )
  300. args = parser.parse_args()
  301. def validate_arguments():
  302. """Validate and parse special field types"""
  303. args.keywords = args.keywords[0] # no idea why it nests it 2D
  304. if args.before is not None:
  305. m = re.match('^([0-9]{4})-([0-9]{2})-([0-9]{2})$', args.before)
  306. if m is None:
  307. parser.error('before date must be in YYYY-MM-DD format (e.g. 2015-03-28)')
  308. args.before = [ int(m.group(1)), int(m.group(2)), int(m.group(3)) ]
  309. if args.after is not None:
  310. m = re.match('^([0-9]{4})-([0-9]{2})-([0-9]{2})$', args.after)
  311. if m is None:
  312. parser.error('after date must be in YYYY-MM-DD format (e.g. 2015-03-28)')
  313. args.after = [ int(m.group(1)), int(m.group(2)), int(m.group(3)) ]
  314. if args.dir is None:
  315. args.dir = [ '.' ]
  316. else:
  317. for d in args.dir:
  318. if not os.path.exists(d) or not os.path.isdir(d):
  319. parser.error(f'search path \'{d}\' does not exist or is not a directory')
  320. if args.output is None:
  321. args.output = TemporaryDirectory(prefix='Email search results (id ', suffix=')').name
  322. else:
  323. if not os.path.exists(args.output) or not os.path.isdir(args.output):
  324. parser.error(f'output path \'{args.output}\' does not exist or is not a directory')
  325. def construct_filter():
  326. """Sets `filter` from parsed command line arguments."""
  327. global message_filter
  328. criteria: List[Filter] = []
  329. keyword_filters = []
  330. for k in args.keywords:
  331. k = k.strip()
  332. if len(k) > 0:
  333. keyword_filters.append(BodyKeywordFilter(k, case_sensitive=args.casesensitive))
  334. if len(keyword_filters) > 0:
  335. op = BooleanOperator.or_op if args.any else BooleanOperator.and_op
  336. criteria.append(BooleanFilter(op, keyword_filters))
  337. if getattr(args, 'from') is not None:
  338. criteria.append(HeaderFilter('from', getattr(args, 'from')))
  339. if getattr(args, 'to') is not None:
  340. criteria.append(HeaderFilter(['to', 'cc', 'bcc'], getattr(args, 'to')))
  341. if args.subject is not None:
  342. criteria.append(HeaderFilter('subject', args.subject))
  343. if args.before is not None:
  344. criteria.append(DateFilter(lambda d: compare_dates(d, args.before) <= 0))
  345. if args.after is not None:
  346. criteria.append(DateFilter(lambda d: compare_dates(d, args.after) >= 0))
  347. if len(criteria) == 0:
  348. parser.error('No filters specified')
  349. message_filter = BooleanFilter(BooleanOperator.and_op, criteria)
  350. def handle_results():
  351. """Final logic after all searching is completed."""
  352. if result_count > 0:
  353. if platform.system() == 'Darwin':
  354. subprocess.call(['open', args.output])
  355. elif platform.system() == 'Windows':
  356. subprocess.call(['explorer.exe', args.output])
  357. print(f'Found {result_count} result(s) total')
  358. elif zip_count == 0:
  359. print('No zip files found')
  360. sys.exit(2)
  361. else:
  362. print('No results')
  363. sys.exit(1)
  364. # Main logic
  365. parse_arguments()
  366. validate_arguments()
  367. construct_filter()
  368. for path in args.dir:
  369. walk_directory(path)
  370. handle_results()