+

Add display IMAP quota feature

Benjamin Renard [2015-11-16 17:44:16]
Add display IMAP quota feature
Filename
imapt
diff --git a/imapt b/imapt
index c1b7c64..efef1bc 100755
--- a/imapt
+++ b/imapt
@@ -30,6 +30,8 @@ import imaplib
 import logging
 import sys

+import re
+
 parser = OptionParser()


@@ -98,6 +100,13 @@ parser.add_option('-l',
 		  help="List mailboxes",
 		  default=False)

+parser.add_option('-q',
+		  '--quota',
+		  action="store_true",
+		  dest="quota",
+		  help="Display quota informations",
+		  default=False)
+
 parser.add_option('--expunge',
 		  action="store",
 		  type="string",
@@ -172,6 +181,12 @@ def expunge(server,mailbox):
 	except Exception as e:
 		logging.error('Error expunging %s mailbox : %s' % (mailbox,e))

+def format_quota(num):
+	num=int(num)
+	for x in ['KB', 'MB', 'GB', 'TB']:
+		if num < 1024.0:
+			return "%3.1f %s" % (num, x)
+		num /= 1024.0

 try:
 	if options.list:
@@ -188,6 +203,24 @@ try:
 				expunge(server,dirname)
 		else:
 			expunge(server,options.expunge)
+	elif options.quota:
+		logging.debug("Get quota usage")
+		ret=server.getquotaroot(options.mailbox)
+		logging.debug("IMAP server return : %s" % str(ret))
+		# Return example on Dovecot
+		# ('OK', [['"INBOX" "User quota"'], ['"User quota" (STORAGE 0 1024)']])
+		if isinstance(ret, (list, tuple)):
+			for quota in ret[1][1]:
+				if quota is None:
+					logging.info('No quota defined')
+					continue
+				parsequota=re.match('^"([^"]*)" \(STORAGE ([0-9]*) ([0-9]*)\)$',quota)
+				if parsequota:
+					logging.info("Quota %s : %s / %s" % (parsequota.group(1),format_quota(parsequota.group(2)),format_quota(parsequota.group(3))))
+				else:
+					logging.error("Error parsing quota string from IMAP server : '%s'" % quota)
+		else:
+			logging.error("Invalid result getting quotas: %s" % ret)
 	else:
 		logging.debug("Select mailbox")
 		ret = server.select(options.mailbox)
ViewGit