-
Notifications
You must be signed in to change notification settings - Fork 1
/
imap-snooze.py
executable file
·168 lines (141 loc) · 5.81 KB
/
imap-snooze.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#!/usr/bin/env python3
from imaplib import IMAP4_SSL
class SnoozeBox:
"""
A snooze box is an imap folder that contains the string "snooze" and a
number that defines the number of days a message in this folder should be
snoozed.
"""
def __init__(self, string):
self.bstring = string
self.name = string.decode("utf-8")[7:]
import re
self.time = re.findall(r'\d+', self.name) [0]
def __str__(self):
return "SnoozeBox(\"" + self.name + "\", "+ self.time + ")"
def __repr__(self):
return str(self)
class IMAPSnoozeDaemon:
"""
A snooze daemon which watches a set of IMAP folders for snooze emails to
appear. If a snooze email appears, it is marked with the time it was moved
to the snooze folder and is moved back to the main folder when the defined
snooze delay was reached.
"""
def __init__(self, server, user, password):
self.server = server
self.user = user
self.password = password
def connect(self):
self.imap = IMAP4_SSL(self.server)
self.imap.login(self.user, self.password)
def findSnoozeBoxes(self):
status , mailboxes = self.imap.lsub()
assert(status == "OK")
snoozeboxes = filter(lambda x : str(x).find("snooze") != -1, mailboxes)
self.boxes = list(map(SnoozeBox, snoozeboxes))
print(self.boxes)
def loop(self):
while True:
print("Checking mailbox again")
for box in self.boxes:
self.process(box)
import time
time.sleep(60)
def process(self, box):
self.markNew(box)
self.moveBack(box)
def markNew(self, box):
self.imap.select(box.name)
status, data = self.imap.uid('search', None, 'NOT HEADER X-SNOOZE ""')
assert(status == "OK")
mails = data[0].decode("utf-8").split(" ")
toDelete = []
if mails == ['']:
return;
for mail in mails:
status, body = self.imap.uid('fetch', mail, '(RFC822)')
assert(status == "OK")
keepmail = True
try:
body = body[0][1].decode("utf-8")
except UnicodeDecodeError:
print("Problem found")
keepmail = False
result = self.imap.uid('COPY', mail, 'INBOX')
res = self.imap.uid('STORE', mail, '+FLAGS', '(\Deleted)')
continue
if body.find("X-SNOOZE:") == -1 or True:
if body.find("X-SNOOZE:") != -1:
body = body[body.find('\n')+1:body.rfind('\n')]
import time
t = int(time.time())
t += int(box.time) * 3600 * 24
print("Newtime %d" % t)
body = "X-SNOOZE: " + str(t) + "\n" + body
toDelete.append(mail)
self.imap.append(box.name, None, None, body.encode("utf-8"))
res = self.imap.uid('STORE', mail, '+FLAGS', '(\Deleted)')
a = self.imap.expunge()
return
def moveBack(self, box):
self.imap.select(box.name)
status, data = self.imap.uid('search', None, 'HEADER X-SNOOZE ""')
assert(status == "OK")
mails = data[0].decode("utf-8").split(" ")
toDelete = []
if mails == ['']:
return;
for mail in mails:
status, body = self.imap.uid('fetch', mail, '(RFC822)')
assert(status == "OK")
keepmail = True
try:
body = body[0][1].decode("utf-8")
except UnicodeDecodeError:
print("Problem found")
keepmail = False
continue
import email.feedparser as parser
p = parser.FeedParser()
p.feed(body)
email = p.close()
if body.find("X-SNOOZE:") != -1:
import re
moveTime = int(re.findall(r'\d+', body) [0])
import time
currentTime = time.time()
if moveTime > currentTime and keepmail:
remainingTime = int(moveTime - currentTime)
print(remainingTime)
remainingSeconds = remainingTime % 60
remainingMinutes = remainingTime % (60 * 60)
remainingHours = remainingTime % (60 * 60 * 60)
remainingDays = remainingTime
remainingSeconds = remainingSeconds
remainingMinutes = remainingMinutes / 60
remainingHours = remainingHours / (60 * 60)
remainingDays = remainingDays / (60 * 60 * 24)
print("# Igoring\n\"%s\" from %s" %
(email["Subject"], email["From"]))
print("Time left: %d d, %d h, %d m, %d s" % (remainingDays, remainingHours, remainingMinutes, remainingSeconds))
continue
body = body[body.find('\n')+1:body.rfind('\n')]
self.imap.append("INBOX", None, None, body.encode("utf-8"))
res = self.imap.uid('STORE', mail, '+FLAGS', '(\Deleted)')
self.imap.expunge()
return
import argparse
parser = argparse.ArgumentParser(description='IMAP snooze daemon.')
parser.add_argument('--server', dest='server',
help='The URL of the imap server to connect to',
default='imaps-proxy.messagingengine.com')
parser.add_argument('--user', dest='user', required=True,
help='The username to use')
parser.add_argument('--password', dest='password', required=True,
help='the password to use')
args = parser.parse_args()
snoozed = IMAPSnoozeDaemon(args.server, args.user, args.password)
snoozed.connect()
snoozed.findSnoozeBoxes()
snoozed.loop()