Add display IMAP quota feature
Benjamin Renard

Benjamin Renard commited on 2015-11-16 17:44:16
Showing 1 changed files, with 33 additions and 0 deletions.

... ...
@@ -30,6 +30,8 @@ import imaplib
30 30
 import logging
31 31
 import sys
32 32
 
33
+import re
34
+
33 35
 parser = OptionParser()
34 36
 
35 37
 
... ...
@@ -98,6 +100,13 @@ parser.add_option('-l',
98 100
 		  help="List mailboxes",
99 101
 		  default=False)
100 102
 
103
+parser.add_option('-q',
104
+		  '--quota',
105
+		  action="store_true",
106
+		  dest="quota",
107
+		  help="Display quota informations",
108
+		  default=False)
109
+
101 110
 parser.add_option('--expunge',
102 111
 		  action="store",
103 112
 		  type="string",
... ...
@@ -172,6 +181,12 @@ def expunge(server,mailbox):
172 181
 	except Exception as e:
173 182
 		logging.error('Error expunging %s mailbox : %s' % (mailbox,e))
174 183
 
184
+def format_quota(num):
185
+	num=int(num)
186
+	for x in ['KB', 'MB', 'GB', 'TB']:
187
+		if num < 1024.0:
188
+			return "%3.1f %s" % (num, x)
189
+		num /= 1024.0
175 190
 
176 191
 try:
177 192
 	if options.list:
... ...
@@ -188,6 +203,24 @@ try:
188 203
 				expunge(server,dirname)
189 204
 		else:
190 205
 			expunge(server,options.expunge)
206
+	elif options.quota:
207
+		logging.debug("Get quota usage")
208
+		ret=server.getquotaroot(options.mailbox)
209
+		logging.debug("IMAP server return : %s" % str(ret))
210
+		# Return example on Dovecot
211
+		# ('OK', [['"INBOX" "User quota"'], ['"User quota" (STORAGE 0 1024)']])
212
+		if isinstance(ret, (list, tuple)):
213
+			for quota in ret[1][1]:
214
+				if quota is None:
215
+					logging.info('No quota defined')
216
+					continue
217
+				parsequota=re.match('^"([^"]*)" \(STORAGE ([0-9]*) ([0-9]*)\)$',quota)
218
+				if parsequota:
219
+					logging.info("Quota %s : %s / %s" % (parsequota.group(1),format_quota(parsequota.group(2)),format_quota(parsequota.group(3))))
220
+				else:
221
+					logging.error("Error parsing quota string from IMAP server : '%s'" % quota)
222
+		else:
223
+			logging.error("Invalid result getting quotas: %s" % ret)
191 224
 	else:
192 225
 		logging.debug("Select mailbox")
193 226
 		ret = server.select(options.mailbox)
194 227