imapdedup 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. #! /usr/bin/env python3
  2. #
  3. # imapdedup.py
  4. #
  5. # Looks for duplicate messages in a set of IMAP mailboxes and removes all but the first.
  6. # Comparison is normally based on the Message-ID header.
  7. #
  8. # Default behaviour is purely to mark the duplicates as deleted. Some mail clients
  9. # will allow you to view these and undelete them if you change your mind.
  10. #
  11. # Copyright (c) 2013-2020 Quentin Stafford-Fraser.
  12. # All rights reserved, subject to the following:
  13. #
  14. #
  15. # This is free software; you can redistribute it and/or modify
  16. # it under the terms of the GNU General Public License as published by
  17. # the Free Software Foundation; either version 2 of the License, or
  18. # (at your option) any later version.
  19. #
  20. # This software is distributed in the hope that it will be useful,
  21. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. # GNU General Public License for more details.
  24. #
  25. # You should have received a copy of the GNU General Public License
  26. # along with this software; if not, write to the Free Software
  27. # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  28. # USA.
  29. #
  30. import getpass
  31. import hashlib
  32. import imaplib
  33. import os
  34. import optparse
  35. import re
  36. import socket
  37. import sys
  38. from typing import List, Dict, Tuple, Optional, Union, Type, Any
  39. from email.parser import BytesParser
  40. from email.message import Message
  41. from email.errors import HeaderParseError
  42. from email.header import decode_header
  43. # Increase the rather small limit on result line-length
  44. # imposed in certain imaplib versions.
  45. # imaplib._MAXLINE = max(2000000, imaplib._MAXLINE)
  46. class ImapDedupException(Exception):
  47. pass
  48. # IMAP responses should normally begin 'OK' - we strip that off
  49. def check_response(resp: Tuple[str, List[bytes]]):
  50. status, value = resp
  51. if status != "OK":
  52. raise ImapDedupException("Got response: %s from server" % str(value))
  53. return value
  54. def get_arguments(args: List[str]) -> Tuple[optparse.Values, List[str]]:
  55. # Get arguments and create link to server
  56. parser = optparse.OptionParser(usage="%prog [options] <mailboxname> [<mailboxname> ...]")
  57. parser.add_option(
  58. "-P", "--process", dest="process", help="IMAP process to access mailboxes"
  59. )
  60. parser.add_option("-s", "--server", dest="server", help="IMAP server")
  61. parser.add_option("-p", "--port", dest="port", help="IMAP server port", type="int")
  62. parser.add_option("-x", "--ssl", dest="ssl", action="store_true", help="Use SSL")
  63. parser.add_option("-X", "--starttls", dest="starttls", action="store_true", help="Require STARTTLS")
  64. parser.add_option("-u", "--user", dest="user", help="IMAP user name")
  65. parser.add_option(
  66. "-w",
  67. "--password",
  68. dest="password",
  69. help="IMAP password (Will prompt if not specified)",
  70. )
  71. parser.add_option(
  72. "-v", "--verbose", dest="verbose", action="store_true", help="Verbose mode"
  73. )
  74. parser.add_option(
  75. "-n",
  76. "--dry-run",
  77. dest="dry_run",
  78. action="store_true",
  79. help="Don't actually do anything, just report what would be done",
  80. )
  81. parser.add_option(
  82. "-c",
  83. "--checksum",
  84. dest="use_checksum",
  85. action="store_true",
  86. help="Use a checksum of several mail headers, instead of the Message-ID",
  87. )
  88. parser.add_option(
  89. "-m",
  90. "--checksum-with-id",
  91. dest="use_id_in_checksum",
  92. action="store_true",
  93. help="Include the Message-ID (if any) in the -c checksum.",
  94. )
  95. parser.add_option(
  96. "",
  97. "--no-close",
  98. dest="no_close",
  99. action="store_true",
  100. help='Do not "close" mailbox when done. Some servers will purge deleted messages on a close command.',
  101. )
  102. parser.add_option(
  103. "-l",
  104. "--list",
  105. dest="just_list",
  106. action="store_true",
  107. help="Just list mailboxes",
  108. )
  109. parser.set_defaults(
  110. verbose=False, ssl=False, dry_run=False, no_close=False, just_list=False
  111. )
  112. (options, mboxes) = parser.parse_args(args)
  113. if ((not options.server) or (not options.user)) and not options.process:
  114. sys.stderr.write(
  115. "\nError: Must specify server, user, and at least one mailbox.\n\n"
  116. )
  117. parser.print_help()
  118. sys.exit(1)
  119. if not options.password and not options.process:
  120. # Read from IMAPDEDUP_PASSWORD env variable, or prompt for one.
  121. options.password = os.getenv("IMAPDEDUP_PASSWORD") or getpass.getpass()
  122. if options.use_id_in_checksum and not options.use_checksum:
  123. sys.stderr.write("\nError: If you use -m you must also use -c.\n")
  124. sys.exit(1)
  125. return (options, mboxes)
  126. # Thanks to http://www.doughellmann.com/PyMOTW/imaplib/
  127. list_response_pattern = re.compile(
  128. rb'\((?P<flags>.*?)\) "(?P<delimiter>.*)" (?P<name>.*)'
  129. )
  130. def parse_list_response(line: bytes):
  131. m = list_response_pattern.match(line)
  132. if m is None:
  133. sys.stderr.write("\nError: parsing list response '{}'".format(str(line)))
  134. sys.exit(1)
  135. flags, delimiter, mailbox_name = m.groups()
  136. mailbox_name = mailbox_name.strip(b'"')
  137. return (flags, delimiter, mailbox_name)
  138. def str_header(parsed_message: Message, name: str) -> str:
  139. """"
  140. Return the value (of the first instance, if more than one) of
  141. the given header, as a unicode string.
  142. """
  143. hdrlist = decode_header(parsed_message.get(name, ""))
  144. btext, charset = hdrlist[0]
  145. if isinstance(btext, str):
  146. text = btext
  147. else:
  148. text = btext.decode("utf-8", "ignore")
  149. return text
  150. def get_message_id(
  151. parsed_message: Message, options_use_checksum=False, options_use_id_in_checksum=False
  152. ) -> Optional[str]:
  153. """
  154. Normally, return the Message-ID header (or print a warning if it doesn't
  155. exist and return None).
  156. If options_use_checksum is specified, use md5 hash of several headers
  157. instead.
  158. For more safety, user should first do a dry run, reviewing them before
  159. deletion. Problems are extremely unlikely, but md5 is not collision-free.
  160. If options_use_id_in_checksum is specified, then the Message-ID will be
  161. included in the header checksum, otherwise it is excluded.
  162. """
  163. try:
  164. if options_use_checksum:
  165. md5 = hashlib.md5()
  166. md5.update(("From:" + str_header(parsed_message, "From")).encode())
  167. md5.update(("To:" + str_header(parsed_message, "To")).encode())
  168. md5.update(("Subject:" + str_header(parsed_message, "Subject")).encode())
  169. md5.update(("Date:" + str_header(parsed_message, "Date")).encode())
  170. md5.update(("Cc:" + str_header(parsed_message, "Cc")).encode())
  171. md5.update(("Bcc:" + str_header(parsed_message, "Bcc")).encode())
  172. if options_use_id_in_checksum:
  173. md5.update(("Message-ID:" + str_header(parsed_message, "Message-ID")).encode())
  174. msg_id = md5.hexdigest()
  175. # print(msg_id)
  176. else:
  177. msg_id = str_header(parsed_message, "Message-ID")
  178. if not msg_id:
  179. print(
  180. (
  181. "Message '%s' dated '%s' has no Message-ID header."
  182. % (
  183. str_header(parsed_message, "Subject"),
  184. str_header(parsed_message, "Date"),
  185. )
  186. )
  187. )
  188. print("You might want to use the -c option.")
  189. return None
  190. return msg_id
  191. except (ValueError, HeaderParseError):
  192. print(
  193. "WARNING: There was an exception trying to parse the headers of this message."
  194. )
  195. print("It may be corrupt, and you might consider deleting it.")
  196. print(
  197. (
  198. "Subject: %s\nFrom: %s\nDate: %s\n"
  199. % (
  200. parsed_message["Subject"],
  201. parsed_message["From"],
  202. parsed_message["Date"],
  203. )
  204. )
  205. )
  206. print("Message skipped.")
  207. return None
  208. def get_mailbox_list(server: imaplib.IMAP4) -> List[str]:
  209. """
  210. Return a list of usable mailbox names
  211. """
  212. resp = []
  213. for mb in check_response(server.list()):
  214. bits = parse_list_response(mb)
  215. if rb"\\Noselect" not in bits[0]:
  216. resp.append(bits[2].decode())
  217. return resp
  218. def get_deleted_msgnums(server: imaplib.IMAP4) -> List[int]:
  219. """
  220. Return a list of ids of deleted messages in the folder.
  221. """
  222. resp = []
  223. deleted_info = check_response(server.search(None, "DELETED"))
  224. if deleted_info:
  225. # If neither None nor empty, then
  226. # the first item should be a list of msg ids
  227. resp = [int(n) for n in deleted_info[0].split()]
  228. return resp
  229. def get_undeleted_msgnums(server: imaplib.IMAP4) -> List[int]:
  230. """
  231. Return a list of ids of non-deleted messages in the folder.
  232. """
  233. resp = []
  234. undeleted_info = check_response(server.search(None, "UNDELETED"))
  235. if undeleted_info:
  236. # If neither None nor empty, then
  237. # the first item should be a list of msg ids
  238. resp = [int(n) for n in undeleted_info[0].split()]
  239. return resp
  240. def mark_messages_deleted(server: imaplib.IMAP4, msgs_to_delete: List[int]):
  241. message_ids = ",".join(map(str, msgs_to_delete))
  242. check_response(
  243. server.store(message_ids, "+FLAGS", r"(\Deleted)")
  244. )
  245. def get_msg_headers(server: imaplib.IMAP4, msg_ids: List[int]) -> List[Tuple[int, bytes]]:
  246. """
  247. Get the dict of headers for each message in the list of provided IDs.
  248. Return a list of tuples: [ (msgid, header_bytes), (msgid, header_bytes)... ]
  249. The returned header_bytes can be parsed by
  250. """
  251. # Get the header info for each message
  252. message_ids_str = ",".join(map(str, msg_ids))
  253. ms = check_response(server.fetch(message_ids_str, "(RFC822.HEADER)"))
  254. # There are two lines per message in the response
  255. resp: List[Tuple[int, bytes]] = []
  256. for ci in range(0, len(ms) // 2):
  257. mnum = int(msg_ids[ci])
  258. _, hinfo = ms[ci * 2]
  259. resp.append((mnum, hinfo))
  260. return resp
  261. def print_message_info(parsed_message: Message):
  262. print("From: " + str_header(parsed_message, "From"))
  263. print("To: " + str_header(parsed_message, "To"))
  264. print("Cc: " + str_header(parsed_message, "Cc"))
  265. print("Bcc: " + str_header(parsed_message, "Bcc"))
  266. print("Subject: " + str_header(parsed_message, "Subject"))
  267. print("Date: " + str_header(parsed_message, "Date"))
  268. print("")
  269. # This actually does the work
  270. def process(options, mboxes: List[str]):
  271. serverclass: Type[Any]
  272. if options.process:
  273. serverclass = imaplib.IMAP4_stream
  274. elif options.ssl:
  275. serverclass = imaplib.IMAP4_SSL
  276. else:
  277. serverclass = imaplib.IMAP4
  278. try:
  279. if options.process:
  280. server = serverclass(options.process)
  281. elif options.port:
  282. server = serverclass(options.server, options.port)
  283. else:
  284. # Use the default, which will be different depending on SSL choice
  285. server = serverclass(options.server)
  286. except socket.error as e:
  287. sys.stderr.write(
  288. "\nFailed to connect to server. Might be host, port or SSL settings?\n"
  289. )
  290. sys.stderr.write("%s\n\n" % e)
  291. sys.exit(1)
  292. if ("STARTTLS" in server.capabilities) and hasattr(server, "starttls"):
  293. server.starttls()
  294. elif options.starttls:
  295. sys.stderr.write("\nError: Server did not offer TLS\n")
  296. sys.exit(1)
  297. elif not options.ssl:
  298. sys.stderr.write("\nWarning: Unencrypted connection\n")
  299. try:
  300. if not options.process:
  301. server.login(options.user, options.password)
  302. except:
  303. sys.stderr.write("\nError: Login failed\n")
  304. sys.exit(1)
  305. # List mailboxes option
  306. # Just do that and then exit
  307. if options.just_list:
  308. for mb in get_mailbox_list(server):
  309. print(mb)
  310. return
  311. if len(mboxes) == 0:
  312. sys.stderr.write("\nError: Must specify mailbox\n")
  313. sys.exit(1)
  314. # OK - let's get started.
  315. # Iterate through a set of named mailboxes and delete the later messages discovered.
  316. try:
  317. parser = BytesParser() # can be the same for all mailboxes
  318. # Create a list of previously seen message IDs, in any mailbox
  319. msg_ids: Dict[str, str] = {}
  320. for mbox in mboxes:
  321. msgs_to_delete = [] # should be reset for each mbox
  322. msg_map = {} # should be reset for each mbox
  323. # Make sure mailbox name is surrounded by quotes if it contains a space
  324. if " " in mbox and (mbox[0] != '"' or mbox[-1] != '"'):
  325. mbox = '"' + mbox + '"'
  326. # Select the mailbox
  327. msgs = check_response(server.select(mailbox=mbox, readonly=options.dry_run))[0]
  328. print("There are %d messages in %s." % (int(msgs), mbox))
  329. # Check how many messages are already marked 'deleted'...
  330. numdeleted = len(get_deleted_msgnums(server))
  331. print(
  332. "%s message(s) currently marked as deleted in %s"
  333. % (numdeleted or "No", mbox)
  334. )
  335. # Now get a list of the ones that aren't deleted.
  336. # That's what we'll actually use.
  337. msgnums = get_undeleted_msgnums(server)
  338. print("%s others in %s" % (len(msgnums), mbox))
  339. chunkSize = 100
  340. if options.verbose:
  341. print("Reading the others... (in batches of %d)" % chunkSize)
  342. for i in range(0, len(msgnums), chunkSize):
  343. if options.verbose:
  344. print("Batch starting at item %d" % i)
  345. # and parse them.
  346. for mnum, hinfo in get_msg_headers(server, msgnums[i: i + chunkSize]):
  347. # Parse the header info into a Message object
  348. mp = parser.parsebytes(hinfo)
  349. if options.verbose:
  350. print("Checking %s message %s" % (mbox, mnum))
  351. # Store message only when verbose is enabled (to print it later on)
  352. msg_map[mnum] = mp
  353. # Record the message-ID header (or generate one from other headers)
  354. msg_id = get_message_id(
  355. mp, options.use_checksum, options.use_id_in_checksum
  356. )
  357. if msg_id:
  358. # If we've seen this message before, record it as one to be
  359. # deleted in this mailbox.
  360. if msg_id in msg_ids:
  361. print(
  362. "Message %s_%s is a duplicate of %s and %s be marked as deleted"
  363. % (
  364. mbox, mnum, msg_ids[msg_id],
  365. options.dry_run and "would" or "will",
  366. )
  367. )
  368. if options.verbose:
  369. print(
  370. "Subject: %s\nFrom: %s\nDate: %s\n"
  371. % (mp["Subject"], mp["From"], mp["Date"])
  372. )
  373. msgs_to_delete.append(mnum)
  374. # Otherwise just record the fact that we've seen it
  375. else:
  376. msg_ids[msg_id] = f"{mbox}_{mnum}"
  377. print(
  378. (
  379. "%s message(s) in %s processed"
  380. % (min(len(msgnums), i + chunkSize), mbox)
  381. )
  382. )
  383. # OK - we've been through this mailbox, and msgs_to_delete holds
  384. # a list of the duplicates we've found.
  385. if len(msgs_to_delete) == 0:
  386. print("No duplicates were found in %s" % mbox)
  387. else:
  388. if options.verbose:
  389. print("These are the duplicate messages: ")
  390. for mnum in msgs_to_delete:
  391. print_message_info(msg_map[mnum])
  392. if options.dry_run:
  393. print(
  394. "If you had NOT selected the 'dry-run' option,\n"
  395. " %i messages would now be marked as 'deleted'."
  396. % (len(msgs_to_delete))
  397. )
  398. else:
  399. print("Marking %i messages as deleted..." % (len(msgs_to_delete)))
  400. # Deleting messages one at a time can be slow if there are many,
  401. # so we batch them up.
  402. chunkSize = 30
  403. if options.verbose:
  404. print("(in batches of %d)" % chunkSize)
  405. for i in range(0, len(msgs_to_delete), chunkSize):
  406. mark_messages_deleted(server, msgs_to_delete[i: i + chunkSize])
  407. if options.verbose:
  408. print("Batch starting at item %d marked." % i)
  409. print("Confirming new numbers...")
  410. numdeleted = len(get_deleted_msgnums(server))
  411. numundel = len(get_undeleted_msgnums(server))
  412. print(
  413. "There are now %s messages marked as deleted and %s others in %s."
  414. % (numdeleted, numundel, mbox)
  415. )
  416. if not options.no_close:
  417. server.close()
  418. except ImapDedupException as e:
  419. print("Error:", e, file=sys.stderr)
  420. finally:
  421. server.logout()
  422. def main(args: List[str]):
  423. options, mboxes = get_arguments(args)
  424. process(options, mboxes)
  425. if __name__ == "__main__":
  426. main(sys.argv[1:])