summaryrefslogtreecommitdiff
path: root/imap-tool
blob: dab6ff8dc2468378c0a32cca051d891b1403fcd6 (plain)
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
#!/usr/bin/python

import os
import sys
import yaml
import getopt
import imaplib2

from enum import Enum

class imap_action(Enum):
	MAILBOX_LIST		= 1
	MAILBOX_LIST_SUB	= 2
	MAILBOX_STATS		= 3
	MAILBOX_CREATE		= 4
	MAILBOX_DELETE		= 5
	MAILBOX_SUBSCRIBE	= 6
	MAILBOX_UNSUBSCRIBE	= 7
	MAILBOX_RENAME		= 8
	MAILBOX_ARCHIVE		= 9

class imap_tool():
	host = "localhost"
	port = 143
	user = "user"
	password = "password"
	archive_batch = 50
	ssl = False
	action = imap_action.MAILBOX_LIST

	usage = "Usage: " + os.path.basename(sys.argv[0]) + " [options] [actions]\n" \
		"\n" \
		"Options:\n" \
		" -h [host]\n" \
		" -u [user]\n" \
		" -p [password]\n" \
		" -i [port]\n" \
		" -s\n" \
		"\n" \
		"Actions:\n" \
		" mailbox-list\n" \
		" mailbox-list-sub\n" \
		" mailbox-stats [mailbox]" \
		" mailbox-create [mailbox]\n" \
		" mailbox-delete [mailbox]\n" \
		" mailbox-subscribe [mailbox]\n" \
		" mailbox-unsubscribe [mailbox]\n" \
		" mailbox-rename [mailbox] [mailbox]\n" \
		" mailbox-archive [mailbox] [year]\n"

	def error_decode(self, data):
		return data[0].decode()

	def act(self):
		print("Connecting to " + self.host)

		if self.ssl:
			imap = imaplib2.IMAP4_SSL(host = self.host, port = self.port)
		else:
			imap = imaplib2.IMAP4(host = self.host, port = self.port)

			if "STARTTLS" not in imap.capabilities:
				print("Unable to create a secure TLS connection")
				return 1

			imap.starttls()

		print("Authenticating with user " + self.user)

		imap.login(self.user, self.password)

		print("")

		try:
			if self.action == imap_action.MAILBOX_LIST:
				ret, data = imap.list()

				print("Mailbox list:")

				for entry in data:
					name = entry.decode().split(" ")[-1]
					print("- " + name)
			elif self.action == imap_action.MAILBOX_LIST_SUB:
				ret, data = imap.lsub()

				print("Subscribed mailbox list:")

				for entry in data:
					name = entry.decode().split(" ")[-1]
					print("- " + name)
			elif self.action == imap_action.MAILBOX_STATS:
				ret, data = imap.examine(self.mailbox)
				if ret != "OK":
					print("Error getting stats for mailbox " + self.mailbox)
					raise Exception()

				count = int(data[0])
				print("Mailbox " + self.mailbox + " has " + str(count) + " entries")
			elif self.action == imap_action.MAILBOX_CREATE:
				ret, data = imap.create(self.mailbox)
				if ret != "OK":
					print("Error creating mailbox " + self.mailbox + ": " + self.error_decode(data))
					raise Exception()

				print("Created mailbox " + self.mailbox)
			elif self.action == imap_action.MAILBOX_DELETE:
				ret, data = imap.delete(self.mailbox)
				if ret != "OK":
					print("Error deleting mailbox " + self.mailbox + ": " + self.error_decode(data))
					raise Exception()

				print("Deleted mailbox " + self.mailbox)
			elif self.action == imap_action.MAILBOX_SUBSCRIBE:
				ret, data = imap.subscribe(self.mailbox)
				if ret != "OK":
					print("Error subscribing to mailbox " + self.mailbox + ": " + self.error_decode(data))
					raise Exception()

				print("Subscribed to mailbox " + self.mailbox)
			elif self.action == imap_action.MAILBOX_UNSUBSCRIBE:
				ret, data = imap.unsubscribe(self.mailbox)
				if ret != "OK":
					print("Error unsubscribing from mailbox " + self.mailbox + ": " + self.error_decode(data))
					raise Exception()

				print("Unsubscribed from mailbox " + self.mailbox)
			elif self.action == imap_action.MAILBOX_RENAME:
				ret, data = imap.rename(self.mailbox[0], self.mailbox[1])
				if ret != "OK":
					print("Error renaming mailbox " + self.mailbox[0] + " to " + self.mailbox[1] + ": " + self.error_decode(data))
					raise Exception()

				print("Renamed mailbox " + self.mailbox[0] + " to " + self.mailbox[1])
			elif self.action == imap_action.MAILBOX_ARCHIVE:
				mailbox_archive = "archives/" + self.mailbox + "/" + str(self.archive_year)
				year_start = self.archive_year
				year_stop = self.archive_year + 1

				ret, data = imap.select(self.mailbox)
				if ret != "OK":
					print("Error selecting mailbox " + self.mailbox + ": " + self.error_decode(data))
					raise Exception()

				# Two ways to search:
				# - SINCE/BEFORE that use native dating (often fs-backed), a bit faster
				# - SENTSINCE/SENTBEFORE that use message dating, a bit slower
				ret, data = imap.uid("SEARCH", None, "(SENTSINCE \"01-Jan-" + str(year_start) + "\" SENTBEFORE \"01-Jan-" + str(year_stop) + "\")")
				if ret != "OK":
					print("Error searching mailbox " + self.mailbox + ": " + self.error_decode(data))
					raise Exception()

				uids_search = data[0].decode("ascii").split()
				uids_search_count = len(uids_search)

				print("Found " + str(uids_search_count) + " messages from mailbox " + self.mailbox + " for year " + str(self.archive_year))

				if uids_search_count == 0:
					raise Exception()

				ret, data = imap.create(mailbox_archive)
				if ret != "OK":
					if not self.error_decode(data).startswith("[ALREADYEXISTS]"):
						print("Error creating mailbox " + mailbox_archive + ": " + self.error_decode(data))
						raise Exception()
				else:
					print("Created mailbox " + mailbox_archive)

				index = 0
				uids = []

				while index < uids_search_count:
					uid = uids_search[index]
					index += 1

					uids.append(uid)

					if len(uids) == self.archive_batch or index == uids_search_count:
						ret, data = imap.uid("COPY", ",".join(uids), mailbox_archive)
						if ret != "OK":
							print("Error copying " + str(len(uids)) + " messages to mailbox " + mailbox_archive)
							raise Exception()

						ret, data = imap.uid("STORE", ",".join(uids), "+FLAGS", "\\Deleted")
						if ret != "OK":
							print("Error deleting " + str(len(uids)) + " messages from mailbox " + self.mailbox)
							raise Exception()

						imap.expunge()

						print("Archived " + str(len(uids)) + " messages to mailbox " + mailbox_archive)

						uids = []
		except Exception:
			imap.logout()
			return 1

		imap.logout()
		return 0

	def main(self):
		options, arguments = getopt.getopt(sys.argv[1:], "h:u:p:i:s")

		for key, value in options:
			if key == "-h":
				self.host = value
			elif key == "-u":
				self.user = value
			elif key == "-p":
				self.password = value
			elif key == "-i":
				self.port = int(value)
			elif key == "-s":
				self.ssl = True

		if len(arguments) == 0:
			print(self.usage)
			return 1

		action_option = arguments[0]

		if action_option == "mailbox-list":
			self.action = imap_action.MAILBOX_LIST
		elif action_option == "mailbox-list-sub":
			self.action = imap_action.MAILBOX_LIST_SUB
		elif action_option == "mailbox-create":
			self.action = imap_action.MAILBOX_CREATE
			self.mailbox = arguments[1]
		elif action_option == "mailbox-delete":
			self.action = imap_action.MAILBOX_DELETE
			self.mailbox = arguments[1]
		elif action_option == "mailbox-subscribe":
			self.action = imap_action.MAILBOX_SUBSCRIBE
			self.mailbox = arguments[1]
		elif action_option == "mailbox-unsubscribe":
			self.action = imap_action.MAILBOX_UNSUBSCRIBE
			self.mailbox = arguments[1]
		elif action_option == "mailbox-stats":
			self.action = imap_action.MAILBOX_STATS
			self.mailbox = arguments[1]
		elif action_option == "mailbox-rename":
			self.action = imap_action.MAILBOX_RENAME
			self.mailbox = [ arguments[1], arguments[2] ]
		elif action_option == "mailbox-archive":
			self.action = imap_action.MAILBOX_ARCHIVE
			self.mailbox = arguments[1]
			self.archive_year = int(arguments[2])
		else:
			print("Invalid action specified")
			return 1

		return self.act()

if __name__ == "__main__":
	sys.exit(imap_tool().main())