a2ccabb9e813069b8776edbf2b98ccee6e1772a1
bn8 Initial commit

bn8 authored 11 years ago

1) #! /usr/bin/env python
2) # -*- coding: utf-8 -*-
3) 
4) # imapt -- Simple command-line tool to test IMAP server
5) # By: Benjamin RENARD <brenard@easter-eggs.com>
6) #
7) # Copyright (C) 2013 Easter-eggs
Benjamin Renard Fixed project URL

Benjamin Renard authored 11 years ago

8) # http://git.zionetrix.net/mailt
bn8 Initial commit

bn8 authored 11 years ago

9) #
10) # This file is part of MailT.
11) #
12) # MailT is free software; you can redistribute it and/or modify
13) # it under the terms of the GNU General Public License as published
14) # by the Free Software Foundation, either version 3 of the License,
15) # or (at your option) any later version.
16) #
17) # MailT is distributed in the hope that it will be useful,
18) # but WITHOUT ANY WARRANTY; without even the implied warranty of
19) # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20) # GNU Affero General Public License for more details.
21) #
22) # You should have received a copy of the GNU General Public License
23) # along with this program.  If not, see <http://www.gnu.org/licenses/>.
24) 
25) from optparse import OptionParser
26) 
27) import os
28) import imaplib
29) 
30) import logging
31) import sys
32) 
Benjamin Renard Add display IMAP quota feature

Benjamin Renard authored 8 years ago

33) import re
Benjamin Renard Add interactive authenticat...

Benjamin Renard authored 8 years ago

34) import getpass
Benjamin Renard Add display IMAP quota feature

Benjamin Renard authored 8 years ago

35) 
bn8 Initial commit

bn8 authored 11 years ago

36) parser = OptionParser()
37) 
38) 
39) parser.add_option('-H',
Benjamin Renard Fix ident

Benjamin Renard authored 8 years ago

40) 		  '--host',
41) 		  action="store",
42) 		  type="string",
43) 		  dest="host",
44) 		  help="The IMAP host",
45) 		  default="127.0.0.1")
bn8 Initial commit

bn8 authored 11 years ago

46) 
47) parser.add_option('-p',
Benjamin Renard Fix ident

Benjamin Renard authored 8 years ago

48) 		  '--port',
49) 		  action="store",
50) 		  type="string",
51) 		  dest="port",
52) 		  help="The IMAP port",
53) 		  default=None)
bn8 Initial commit

bn8 authored 11 years ago

54) 
55) parser.add_option('-S',
Benjamin Renard Fix ident

Benjamin Renard authored 8 years ago

56) 		  '--ssl',
57) 		  action="store_true",
58) 		  dest="ssl",
59) 		  help="IMAP Over SSL (IMAPS)",
60) 		  default=False)
bn8 Initial commit

bn8 authored 11 years ago

61) 
62) parser.add_option('-U',
Benjamin Renard Fix ident

Benjamin Renard authored 8 years ago

63) 		  '--user',
64) 		  action="store",
65) 		  type="string",
66) 		  dest="user",
67) 		  help="User login",
68) 		  default=None)
bn8 Initial commit

bn8 authored 11 years ago

69) 
70) parser.add_option('-P',
Benjamin Renard Fix ident

Benjamin Renard authored 8 years ago

71) 		  '--password',
72) 		  action="store",
73) 		  type="string",
74) 		  dest="password",
75) 		  help="User password",
76) 		  default=None)
bn8 Initial commit

bn8 authored 11 years ago

77) 
78) parser.add_option('--md5',
Benjamin Renard Fix ident

Benjamin Renard authored 8 years ago

79) 		  action="store_true",
80) 		  dest="md5",
81) 		  help="Use CRAM-MD5 password for authentication",
82) 		  default=False)
bn8 Initial commit

bn8 authored 11 years ago

83) 
84) parser.add_option('-m',
Benjamin Renard Fix ident

Benjamin Renard authored 8 years ago

85) 		  '--mailbox',
86) 		  action="store",
87) 		  type="string",
88) 		  dest="mailbox",
89) 		  help="The mailbox directory to select",
90) 		  default='INBOX')
bn8 Initial commit

bn8 authored 11 years ago

91) 
92) parser.add_option('-v',
Benjamin Renard Fix ident

Benjamin Renard authored 8 years ago

93) 		  '--verbose',
94) 		  action="store_true",
95) 		  dest="verbose")
bn8 Initial commit

bn8 authored 11 years ago

96) 
Benjamin Renard imapt : add -l/--list param...

Benjamin Renard authored 10 years ago

97) parser.add_option('-l',
Benjamin Renard Fix ident

Benjamin Renard authored 8 years ago

98) 		  '--list',
99) 		  action="store_true",
100) 		  dest="list",
101) 		  help="List mailboxes",
102) 		  default=False)
Benjamin Renard imapt : add -l/--list param...

Benjamin Renard authored 10 years ago

103) 
Benjamin Renard Add display IMAP quota feature

Benjamin Renard authored 8 years ago

104) parser.add_option('-q',
105) 		  '--quota',
106) 		  action="store_true",
107) 		  dest="quota",
108) 		  help="Display quota informations",
109) 		  default=False)
110) 
Benjamin Renard imapt : Add --expunge param...

Benjamin Renard authored 10 years ago

111) parser.add_option('--expunge',
Benjamin Renard Fix ident

Benjamin Renard authored 8 years ago

112) 		  action="store",
113) 		  type="string",
114) 		  dest="expunge",
115) 		  help="Expunge mailbox specify (ALL to expunge all mailboxes)",
116) 		  default=None)
Benjamin Renard imapt : Add --expunge param...

Benjamin Renard authored 10 years ago

117) 
bn8 Initial commit

bn8 authored 11 years ago

118) (options, args) = parser.parse_args()
119) 
120) if options.verbose:
121) 	loglevel=logging.DEBUG
122) else:
123) 	loglevel=logging.INFO
124) 
125) logging.basicConfig(level=loglevel,format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
126) 
Benjamin Renard Add interactive authenticat...

Benjamin Renard authored 8 years ago

127) if not options.user:
128) 	logging.fatal('You must provide the user login')
bn8 Initial commit

bn8 authored 11 years ago

129) 	sys.exit(1)
130) 
Benjamin Renard Add interactive authenticat...

Benjamin Renard authored 8 years ago

131) if not options.password:
132) 	options.password=getpass.getpass()
133) 
bn8 Initial commit

bn8 authored 11 years ago

134) if options.port is None:
135) 	if options.ssl:
136) 		options.port=993
137) 	else:
138) 		options.port=143
139) 
140) if options.ssl:
141) 	logging.debug('Establish SSL connexion to server')
142) 	try:
143) 		server = imaplib.IMAP4_SSL(options.host,options.port)
144) 		logging.debug('Connected')
145) 	except Exception, e:
146) 		logging.critical("IMAP connection error : %s" % e)
147) 		sys.exit(2)
148) else:
149) 	logging.debug("Establish connexion to server")
150) 	try:
151) 		server = imaplib.IMAP4(options.host,options.port)
152) 		logging.debug('Connected')
153) 	except Exception, e:
154) 		logging.critical("IMAP connection error : %s" % e)
155) 		sys.exit(2)
156) 
157) if options.user:
158) 	try:
159) 		if options.md5:
160) 			logging.debug('Login into server as %s (with CRAM-MD5 password)' % options.user)
161) 			server.login_cram_md5(options.user,options.password)
162) 		else:
163) 			logging.debug('Login into server as %s' % options.user)
164) 			server.login(options.user,options.password)
165) 		logging.debug('Logged')
166) 	except Exception as e:
167) 		logging.critical("IMAP Auth error : %s" % e)
168) 		sys.exit(3)
Benjamin Renard imapt : Add --expunge param...

Benjamin Renard authored 10 years ago

169) 
170) def expunge(server,mailbox):
171) 	logging.info('Expunge %s mailbox' % mailbox)
172) 	try:
173) 		(st,c) = server.select(mailbox)
174) 		if st!='OK':
175) 			logging.error('Error selecting %s mailbox : %s' % (mailbox,st))
176) 			return
177) 		(st,ex) = server.expunge()
178) 		if st=='OK':
179) 			if len(ex)==1 and ex[0] is None:
180) 				logging.info('Mailbox %s expunged, no mail removed' % mailbox)
181) 			else:
182) 				logging.info('Mailbox %s expunged : %s mail(s) removed' % (mailbox,len(ex)))
183) 		else:
184) 			logging.info('Error expunging %s mailbox, return "%s"' % (mailbox,st))
185) 	except Exception as e:
186) 		logging.error('Error expunging %s mailbox : %s' % (mailbox,e))
187) 
Benjamin Renard Add display IMAP quota feature

Benjamin Renard authored 8 years ago

188) def format_quota(num):
189) 	num=int(num)
190) 	for x in ['KB', 'MB', 'GB', 'TB']:
191) 		if num < 1024.0:
192) 			return "%3.1f %s" % (num, x)
193) 		num /= 1024.0
Benjamin Renard imapt : Add --expunge param...

Benjamin Renard authored 10 years ago

194) 
bn8 Initial commit

bn8 authored 11 years ago

195) try:
Benjamin Renard imapt : add -l/--list param...

Benjamin Renard authored 10 years ago

196) 	if options.list:
197) 		logging.info('List mailbox')
198) 		(status,l) = server.list()
199) 		for d in l:
Benjamin Renard imapt : Add --expunge param...

Benjamin Renard authored 10 years ago

200) 			logging.info('   "%s"' % d.split('"')[3])
201) 	elif options.expunge:
202) 		if options.expunge=='ALL':
203) 			logging.debug("Listing mailboxes")
204) 			(status,l) = server.list()
205) 			for d in l:
206) 				dirname=d.split('"')[3]
207) 				expunge(server,dirname)
208) 		else:
209) 			expunge(server,options.expunge)
Benjamin Renard Add display IMAP quota feature

Benjamin Renard authored 8 years ago

210) 	elif options.quota:
211) 		logging.debug("Get quota usage")
212) 		ret=server.getquotaroot(options.mailbox)
213) 		logging.debug("IMAP server return : %s" % str(ret))
214) 		# Return example on Dovecot
215) 		# ('OK', [['"INBOX" "User quota"'], ['"User quota" (STORAGE 0 1024)']])
216) 		if isinstance(ret, (list, tuple)):
217) 			for quota in ret[1][1]:
218) 				if quota is None:
219) 					logging.info('No quota defined')
220) 					continue
221) 				parsequota=re.match('^"([^"]*)" \(STORAGE ([0-9]*) ([0-9]*)\)$',quota)
222) 				if parsequota:
223) 					logging.info("Quota %s : %s / %s" % (parsequota.group(1),format_quota(parsequota.group(2)),format_quota(parsequota.group(3))))
224) 				else:
225) 					logging.error("Error parsing quota string from IMAP server : '%s'" % quota)
226) 		else:
227) 			logging.error("Invalid result getting quotas: %s" % ret)
bn8 Initial commit

bn8 authored 11 years ago

228) 	else:
Benjamin Renard imapt : add -l/--list param...

Benjamin Renard authored 10 years ago

229) 		logging.debug("Select mailbox")
230) 		ret = server.select(options.mailbox)
231) 		if len(ret)>0 and ret[0]=='OK':
232) 			logging.info("Mailbox %s content %s message(s)" % (options.mailbox,ret[1][0]))
233) 		else:
234) 			logging.error("Selecting return incorrected : %s" % ret)
235) 		server.close()
bn8 Initial commit

bn8 authored 11 years ago

236) except Exception as e:
Benjamin Renard imapt : fixed typo bug

Benjamin Renard authored 10 years ago

237) 	logging.critical('Error selecting mailbox %s : %s' % (options.mailbox,e))