-
Notifications
You must be signed in to change notification settings - Fork 22
/
shuffle_by_year.py
74 lines (53 loc) · 1.84 KB
/
shuffle_by_year.py
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
#!/usr/bin/env python
# Q&D script to sort mail into subfolders by year.
# Reduces the burden upon the filesystem gnomes.
DIRPATH = "/stor0/backups/imapbak/rtucker/Fastmail-rey_fmgirl_com"
import email
import mailbox
import imap2maildir
import sys
import time
import os
def main():
db = imap2maildir.open_sql_session(DIRPATH + "/.imap2maildir.sqlite")
mbox = mailbox.Maildir(DIRPATH, False)
try:
counter = 0
c = db.cursor()
for result in db.execute("select mailfile,folder from seenmessages where folder is null or folder = ''"):
key = result[0]
msg = mbox.get_message(key)
year = None
if 'Date' in msg:
ttup = email.utils.parsedate(msg['Date'])
if ttup:
year = ttup[0]
if year is None:
tstamp = msg.get_date()
year = time.gmtime(tstamp).tm_year
print(key + " has no valid Date header; going with " + str(year))
ybox = mbox.add_folder(str(year))
ybox.lock()
newkey = ybox.add(msg)
ybox.flush()
ybox.unlock()
c.execute("update seenmessages set mailfile = ?, folder = ? where mailfile = ?", (newkey, year, key))
mbox.lock()
mbox.discard(key)
mbox.flush()
mbox.unlock()
print("moved " + key + " to " + str(year) + "/" + newkey)
counter += 1
if counter % 25 == 0:
print("committing db")
db.commit()
sys.stdout.flush()
if os.path.exists(".STOP"):
print("stop requested")
os.unlink(".STOP")
break
finally:
mbox.unlock()
db.commit()
if __name__ == "__main__":
main()