blob: 9c38e1c823db14c1d22d69b1bd03ffde2998c31d [file] [log] [blame]
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001"""IMAP4 client.
2
3Based on RFC 2060.
4
Tim Peters07e99cb2001-01-14 23:47:14 +00005Public class: IMAP4
6Public variable: Debug
7Public functions: Internaldate2tuple
8 Int2AP
9 ParseFlags
10 Time2Internaldate
Guido van Rossumc2c07fa1998-04-09 13:51:46 +000011"""
Guido van Rossumb1f08121998-06-25 02:22:16 +000012
Guido van Rossum98d9fd32000-02-28 15:12:25 +000013# Author: Piers Lauder <piers@cs.su.oz.au> December 1997.
Tim Peters07e99cb2001-01-14 23:47:14 +000014#
Guido van Rossum98d9fd32000-02-28 15:12:25 +000015# Authentication code contributed by Donn Cave <donn@u.washington.edu> June 1998.
Eric S. Raymond25a0cbc2001-02-09 06:50:21 +000016# String method conversion by ESR, February 2001.
Piers Lauder15e5d532001-07-20 10:52:06 +000017# GET/SETACL contributed by Anthony Baxter <anthony@interlink.com.au> April 2001.
Piers Laudera4f83132002-03-08 01:53:24 +000018# IMAP4_SSL contributed by Tino Lange <Tino.Lange@isg.de> March 2002.
Piers Lauder3fca2912002-06-17 07:07:20 +000019# GET/SETQUOTA contributed by Andreas Zeidler <az@kreativkombinat.de> June 2002.
Piers Laudere0273de2002-11-22 05:53:04 +000020# PROXYAUTH contributed by Rick Holbert <holbert.13@osu.edu> November 2002.
Piers Lauderd80ef022005-06-01 23:50:52 +000021# GET/SETANNOTATION contributed by Tomas Lindroos <skitta@abo.fi> June 2005.
Guido van Rossum98d9fd32000-02-28 15:12:25 +000022
Piers Lauderbe5615e2005-08-31 10:50:03 +000023__version__ = "2.58"
Guido van Rossumc2c07fa1998-04-09 13:51:46 +000024
Antoine Pitrou81c87c52010-11-10 08:59:25 +000025import binascii, errno, random, re, socket, subprocess, sys, time
Guido van Rossumc2c07fa1998-04-09 13:51:46 +000026
Antoine Pitrouf3b001f2010-11-12 18:49:16 +000027try:
28 import ssl
29 HAVE_SSL = True
30except ImportError:
31 HAVE_SSL = False
32
Thomas Wouters47b49bf2007-08-30 22:15:33 +000033__all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple",
Barry Warsawf4493912001-01-24 04:16:09 +000034 "Int2AP", "ParseFlags", "Time2Internaldate"]
Skip Montanaro2dd42762001-01-23 15:35:05 +000035
Tim Peters07e99cb2001-01-14 23:47:14 +000036# Globals
Guido van Rossumc2c07fa1998-04-09 13:51:46 +000037
Christian Heimesfb5faf02008-11-05 19:39:50 +000038CRLF = b'\r\n'
Guido van Rossumc2c07fa1998-04-09 13:51:46 +000039Debug = 0
40IMAP4_PORT = 143
Piers Lauder95f84952002-03-08 09:05:12 +000041IMAP4_SSL_PORT = 993
Tim Peters07e99cb2001-01-14 23:47:14 +000042AllowedVersions = ('IMAP4REV1', 'IMAP4') # Most recent first
Guido van Rossumc2c07fa1998-04-09 13:51:46 +000043
Tim Peters07e99cb2001-01-14 23:47:14 +000044# Commands
Guido van Rossumc2c07fa1998-04-09 13:51:46 +000045
46Commands = {
Tim Peters07e99cb2001-01-14 23:47:14 +000047 # name valid states
48 'APPEND': ('AUTH', 'SELECTED'),
49 'AUTHENTICATE': ('NONAUTH',),
50 'CAPABILITY': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
51 'CHECK': ('SELECTED',),
52 'CLOSE': ('SELECTED',),
53 'COPY': ('SELECTED',),
54 'CREATE': ('AUTH', 'SELECTED'),
55 'DELETE': ('AUTH', 'SELECTED'),
Martin v. Löwis7b9190b2004-07-27 05:07:19 +000056 'DELETEACL': ('AUTH', 'SELECTED'),
Tim Peters07e99cb2001-01-14 23:47:14 +000057 'EXAMINE': ('AUTH', 'SELECTED'),
58 'EXPUNGE': ('SELECTED',),
59 'FETCH': ('SELECTED',),
Piers Lauder15e5d532001-07-20 10:52:06 +000060 'GETACL': ('AUTH', 'SELECTED'),
Piers Lauderd80ef022005-06-01 23:50:52 +000061 'GETANNOTATION':('AUTH', 'SELECTED'),
Piers Lauder3fca2912002-06-17 07:07:20 +000062 'GETQUOTA': ('AUTH', 'SELECTED'),
63 'GETQUOTAROOT': ('AUTH', 'SELECTED'),
Martin v. Löwis7b9190b2004-07-27 05:07:19 +000064 'MYRIGHTS': ('AUTH', 'SELECTED'),
Tim Peters07e99cb2001-01-14 23:47:14 +000065 'LIST': ('AUTH', 'SELECTED'),
66 'LOGIN': ('NONAUTH',),
67 'LOGOUT': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
68 'LSUB': ('AUTH', 'SELECTED'),
Piers Lauder15e5d532001-07-20 10:52:06 +000069 'NAMESPACE': ('AUTH', 'SELECTED'),
Tim Peters07e99cb2001-01-14 23:47:14 +000070 'NOOP': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
Piers Lauderf2d7d152002-02-22 01:15:17 +000071 'PARTIAL': ('SELECTED',), # NB: obsolete
Piers Laudere0273de2002-11-22 05:53:04 +000072 'PROXYAUTH': ('AUTH',),
Tim Peters07e99cb2001-01-14 23:47:14 +000073 'RENAME': ('AUTH', 'SELECTED'),
74 'SEARCH': ('SELECTED',),
75 'SELECT': ('AUTH', 'SELECTED'),
Piers Lauder15e5d532001-07-20 10:52:06 +000076 'SETACL': ('AUTH', 'SELECTED'),
Piers Lauderd80ef022005-06-01 23:50:52 +000077 'SETANNOTATION':('AUTH', 'SELECTED'),
Piers Lauder3fca2912002-06-17 07:07:20 +000078 'SETQUOTA': ('AUTH', 'SELECTED'),
Piers Lauder15e5d532001-07-20 10:52:06 +000079 'SORT': ('SELECTED',),
Antoine Pitrouf3b001f2010-11-12 18:49:16 +000080 'STARTTLS': ('NONAUTH',),
Tim Peters07e99cb2001-01-14 23:47:14 +000081 'STATUS': ('AUTH', 'SELECTED'),
82 'STORE': ('SELECTED',),
83 'SUBSCRIBE': ('AUTH', 'SELECTED'),
Martin v. Löwisd8921372003-11-10 06:44:44 +000084 'THREAD': ('SELECTED',),
Tim Peters07e99cb2001-01-14 23:47:14 +000085 'UID': ('SELECTED',),
86 'UNSUBSCRIBE': ('AUTH', 'SELECTED'),
87 }
Guido van Rossumc2c07fa1998-04-09 13:51:46 +000088
Tim Peters07e99cb2001-01-14 23:47:14 +000089# Patterns to match server responses
Guido van Rossumc2c07fa1998-04-09 13:51:46 +000090
Christian Heimesfb5faf02008-11-05 19:39:50 +000091Continuation = re.compile(br'\+( (?P<data>.*))?')
92Flags = re.compile(br'.*FLAGS \((?P<flags>[^\)]*)\)')
93InternalDate = re.compile(br'.*INTERNALDATE "'
94 br'(?P<day>[ 0123][0-9])-(?P<mon>[A-Z][a-z][a-z])-(?P<year>[0-9][0-9][0-9][0-9])'
95 br' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
96 br' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
97 br'"')
98Literal = re.compile(br'.*{(?P<size>\d+)}$', re.ASCII)
99MapCRLF = re.compile(br'\r\n|\r|\n')
100Response_code = re.compile(br'\[(?P<type>[A-Z-]+)( (?P<data>[^\]]*))?\]')
101Untagged_response = re.compile(br'\* (?P<type>[A-Z-]+)( (?P<data>.*))?')
Antoine Pitroufd036452008-08-19 17:56:33 +0000102Untagged_status = re.compile(
Christian Heimesfb5faf02008-11-05 19:39:50 +0000103 br'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?', re.ASCII)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000104
105
106
107class IMAP4:
108
Tim Peters07e99cb2001-01-14 23:47:14 +0000109 """IMAP4 client class.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000110
Tim Peters07e99cb2001-01-14 23:47:14 +0000111 Instantiate with: IMAP4([host[, port]])
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000112
Tim Peters07e99cb2001-01-14 23:47:14 +0000113 host - host's name (default: localhost);
114 port - port number (default: standard IMAP4 port).
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000115
Tim Peters07e99cb2001-01-14 23:47:14 +0000116 All IMAP4rev1 commands are supported by methods of the same
117 name (in lower-case).
Guido van Rossum6884af71998-05-29 13:34:03 +0000118
Tim Peters07e99cb2001-01-14 23:47:14 +0000119 All arguments to commands are converted to strings, except for
120 AUTHENTICATE, and the last argument to APPEND which is passed as
121 an IMAP4 literal. If necessary (the string contains any
122 non-printing characters or white-space and isn't enclosed with
123 either parentheses or double quotes) each string is quoted.
124 However, the 'password' argument to the LOGIN command is always
125 quoted. If you want to avoid having an argument string quoted
126 (eg: the 'flags' argument to STORE) then enclose the string in
127 parentheses (eg: "(\Deleted)").
Guido van Rossum6884af71998-05-29 13:34:03 +0000128
Tim Peters07e99cb2001-01-14 23:47:14 +0000129 Each command returns a tuple: (type, [data, ...]) where 'type'
130 is usually 'OK' or 'NO', and 'data' is either the text from the
Piers Laudere0273de2002-11-22 05:53:04 +0000131 tagged response, or untagged results from command. Each 'data'
132 is either a string, or a tuple. If a tuple, then the first part
133 is the header of the response, and the second part contains
134 the data (ie: 'literal' value).
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000135
Tim Peters07e99cb2001-01-14 23:47:14 +0000136 Errors raise the exception class <instance>.error("<reason>").
137 IMAP4 server errors raise <instance>.abort("<reason>"),
138 which is a sub-class of 'error'. Mailbox status changes
139 from READ-WRITE to READ-ONLY raise the exception class
140 <instance>.readonly("<reason>"), which is a sub-class of 'abort'.
Guido van Rossumeda960a1998-06-18 14:24:28 +0000141
Tim Peters07e99cb2001-01-14 23:47:14 +0000142 "error" exceptions imply a program error.
143 "abort" exceptions imply the connection should be reset, and
144 the command re-tried.
145 "readonly" exceptions imply the command should be re-tried.
Guido van Rossum8c062211999-12-13 23:27:45 +0000146
Piers Lauderd80ef022005-06-01 23:50:52 +0000147 Note: to use this module, you must read the RFCs pertaining to the
148 IMAP4 protocol, as the semantics of the arguments to each IMAP4
149 command are left to the invoker, not to mention the results. Also,
150 most IMAP servers implement a sub-set of the commands available here.
Tim Peters07e99cb2001-01-14 23:47:14 +0000151 """
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000152
Tim Peters07e99cb2001-01-14 23:47:14 +0000153 class error(Exception): pass # Logical errors - debug required
154 class abort(error): pass # Service errors - close and retry
155 class readonly(abort): pass # Mailbox status changed to READ-ONLY
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000156
Tim Peters07e99cb2001-01-14 23:47:14 +0000157 def __init__(self, host = '', port = IMAP4_PORT):
Tim Peters07e99cb2001-01-14 23:47:14 +0000158 self.debug = Debug
159 self.state = 'LOGOUT'
160 self.literal = None # A literal argument to a command
161 self.tagged_commands = {} # Tagged commands awaiting response
162 self.untagged_responses = {} # {typ: [data, ...], ...}
163 self.continuation_response = '' # Last continuation response
Piers Lauder14f39402005-08-31 10:46:29 +0000164 self.is_readonly = False # READ-ONLY desired state
Tim Peters07e99cb2001-01-14 23:47:14 +0000165 self.tagnum = 0
Antoine Pitrouf3b001f2010-11-12 18:49:16 +0000166 self._tls_established = False
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000167
Tim Peters07e99cb2001-01-14 23:47:14 +0000168 # Open socket to server.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000169
Tim Peters07e99cb2001-01-14 23:47:14 +0000170 self.open(host, port)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000171
Tim Peters07e99cb2001-01-14 23:47:14 +0000172 # Create unique tag for this session,
173 # and compile tagged response matcher.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000174
Piers Lauder2dfc1682005-07-05 04:20:07 +0000175 self.tagpre = Int2AP(random.randint(4096, 65535))
Christian Heimesfb5faf02008-11-05 19:39:50 +0000176 self.tagre = re.compile(br'(?P<tag>'
Tim Peters07e99cb2001-01-14 23:47:14 +0000177 + self.tagpre
Christian Heimesfb5faf02008-11-05 19:39:50 +0000178 + br'\d+) (?P<type>[A-Z]+) (?P<data>.*)', re.ASCII)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000179
Tim Peters07e99cb2001-01-14 23:47:14 +0000180 # Get server welcome message,
181 # request and store CAPABILITY response.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000182
Tim Peters07e99cb2001-01-14 23:47:14 +0000183 if __debug__:
Piers Lauderf2d7d152002-02-22 01:15:17 +0000184 self._cmd_log_len = 10
185 self._cmd_log_idx = 0
186 self._cmd_log = {} # Last `_cmd_log_len' interactions
Tim Peters07e99cb2001-01-14 23:47:14 +0000187 if self.debug >= 1:
Piers Lauderf2d7d152002-02-22 01:15:17 +0000188 self._mesg('imaplib version %s' % __version__)
189 self._mesg('new IMAP4 connection, tag=%s' % self.tagpre)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000190
Tim Peters07e99cb2001-01-14 23:47:14 +0000191 self.welcome = self._get_response()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000192 if 'PREAUTH' in self.untagged_responses:
Tim Peters07e99cb2001-01-14 23:47:14 +0000193 self.state = 'AUTH'
Raymond Hettinger54f02222002-06-01 14:18:47 +0000194 elif 'OK' in self.untagged_responses:
Tim Peters07e99cb2001-01-14 23:47:14 +0000195 self.state = 'NONAUTH'
196 else:
197 raise self.error(self.welcome)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000198
Antoine Pitroudbe75192010-11-16 17:55:26 +0000199 self._get_capabilities()
Tim Peters07e99cb2001-01-14 23:47:14 +0000200 if __debug__:
201 if self.debug >= 3:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000202 self._mesg('CAPABILITIES: %r' % (self.capabilities,))
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000203
Tim Peters07e99cb2001-01-14 23:47:14 +0000204 for version in AllowedVersions:
205 if not version in self.capabilities:
206 continue
207 self.PROTOCOL_VERSION = version
208 return
Guido van Rossumb1f08121998-06-25 02:22:16 +0000209
Tim Peters07e99cb2001-01-14 23:47:14 +0000210 raise self.error('server not IMAP4 compliant')
Guido van Rossum38d8f4e1998-04-11 01:22:34 +0000211
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000212
Tim Peters07e99cb2001-01-14 23:47:14 +0000213 def __getattr__(self, attr):
214 # Allow UPPERCASE variants of IMAP4 command methods.
Raymond Hettinger54f02222002-06-01 14:18:47 +0000215 if attr in Commands:
Piers Lauder15e5d532001-07-20 10:52:06 +0000216 return getattr(self, attr.lower())
Tim Peters07e99cb2001-01-14 23:47:14 +0000217 raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
Guido van Rossum26367a01998-09-28 15:34:46 +0000218
219
220
Piers Lauder15e5d532001-07-20 10:52:06 +0000221 # Overridable methods
Guido van Rossum26367a01998-09-28 15:34:46 +0000222
223
Christian Heimesfb5faf02008-11-05 19:39:50 +0000224 def _create_socket(self):
Antoine Pitrouc1d09362009-05-15 12:15:51 +0000225 return socket.create_connection((self.host, self.port))
Christian Heimesfb5faf02008-11-05 19:39:50 +0000226
Piers Lauderf97b2d72002-06-05 22:31:57 +0000227 def open(self, host = '', port = IMAP4_PORT):
228 """Setup connection to remote server on "host:port"
229 (default: localhost:standard IMAP4 port).
Piers Lauder15e5d532001-07-20 10:52:06 +0000230 This connection will be used by the routines:
231 read, readline, send, shutdown.
232 """
Piers Lauderf97b2d72002-06-05 22:31:57 +0000233 self.host = host
234 self.port = port
Christian Heimesfb5faf02008-11-05 19:39:50 +0000235 self.sock = self._create_socket()
Guido van Rossumc0f1bfe2001-10-15 13:47:08 +0000236 self.file = self.sock.makefile('rb')
Guido van Rossumeda960a1998-06-18 14:24:28 +0000237
238
Piers Lauder15e5d532001-07-20 10:52:06 +0000239 def read(self, size):
240 """Read 'size' bytes from remote."""
Christian Heimesfb5faf02008-11-05 19:39:50 +0000241 chunks = []
242 read = 0
243 while read < size:
244 data = self.file.read(min(size-read, 4096))
245 if not data:
246 break
247 read += len(data)
248 chunks.append(data)
249 return b''.join(chunks)
Piers Lauder15e5d532001-07-20 10:52:06 +0000250
251
252 def readline(self):
253 """Read line from remote."""
254 return self.file.readline()
255
256
257 def send(self, data):
258 """Send data to remote."""
Martin v. Löwise12454f2002-02-16 23:06:19 +0000259 self.sock.sendall(data)
Piers Lauder15e5d532001-07-20 10:52:06 +0000260
Piers Lauderf2d7d152002-02-22 01:15:17 +0000261
Piers Lauder15e5d532001-07-20 10:52:06 +0000262 def shutdown(self):
263 """Close I/O established in "open"."""
264 self.file.close()
Antoine Pitrou81c87c52010-11-10 08:59:25 +0000265 try:
266 self.sock.shutdown(socket.SHUT_RDWR)
267 except socket.error as e:
268 # The server might already have closed the connection
269 if e.errno != errno.ENOTCONN:
270 raise
271 finally:
272 self.sock.close()
Piers Lauder15e5d532001-07-20 10:52:06 +0000273
274
275 def socket(self):
276 """Return socket instance used to connect to IMAP4 server.
277
278 socket = <instance>.socket()
279 """
280 return self.sock
281
282
283
284 # Utility methods
285
286
Tim Peters07e99cb2001-01-14 23:47:14 +0000287 def recent(self):
288 """Return most recent 'RECENT' responses if any exist,
289 else prompt server for an update using the 'NOOP' command.
Guido van Rossum26367a01998-09-28 15:34:46 +0000290
Tim Peters07e99cb2001-01-14 23:47:14 +0000291 (typ, [data]) = <instance>.recent()
Guido van Rossum26367a01998-09-28 15:34:46 +0000292
Tim Peters07e99cb2001-01-14 23:47:14 +0000293 'data' is None if no new messages,
294 else list of RECENT responses, most recent last.
295 """
296 name = 'RECENT'
297 typ, dat = self._untagged_response('OK', [None], name)
298 if dat[-1]:
299 return typ, dat
300 typ, dat = self.noop() # Prod server for response
301 return self._untagged_response(typ, dat, name)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000302
303
Tim Peters07e99cb2001-01-14 23:47:14 +0000304 def response(self, code):
305 """Return data for response 'code' if received, or None.
Guido van Rossum26367a01998-09-28 15:34:46 +0000306
Tim Peters07e99cb2001-01-14 23:47:14 +0000307 Old value for response 'code' is cleared.
Guido van Rossum26367a01998-09-28 15:34:46 +0000308
Tim Peters07e99cb2001-01-14 23:47:14 +0000309 (code, [data]) = <instance>.response(code)
310 """
Eric S. Raymond25a0cbc2001-02-09 06:50:21 +0000311 return self._untagged_response(code, [None], code.upper())
Guido van Rossum26367a01998-09-28 15:34:46 +0000312
313
Guido van Rossum26367a01998-09-28 15:34:46 +0000314
Tim Peters07e99cb2001-01-14 23:47:14 +0000315 # IMAP4 commands
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000316
317
Tim Peters07e99cb2001-01-14 23:47:14 +0000318 def append(self, mailbox, flags, date_time, message):
319 """Append message to named mailbox.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000320
Tim Peters07e99cb2001-01-14 23:47:14 +0000321 (typ, [data]) = <instance>.append(mailbox, flags, date_time, message)
Guido van Rossum8c062211999-12-13 23:27:45 +0000322
Tim Peters07e99cb2001-01-14 23:47:14 +0000323 All args except `message' can be None.
324 """
325 name = 'APPEND'
326 if not mailbox:
327 mailbox = 'INBOX'
328 if flags:
329 if (flags[0],flags[-1]) != ('(',')'):
330 flags = '(%s)' % flags
331 else:
332 flags = None
333 if date_time:
334 date_time = Time2Internaldate(date_time)
335 else:
336 date_time = None
Piers Lauder47404ff2003-04-29 23:40:59 +0000337 self.literal = MapCRLF.sub(CRLF, message)
Tim Peters07e99cb2001-01-14 23:47:14 +0000338 return self._simple_command(name, mailbox, flags, date_time)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000339
340
Tim Peters07e99cb2001-01-14 23:47:14 +0000341 def authenticate(self, mechanism, authobject):
342 """Authenticate command - requires response processing.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000343
Tim Peters07e99cb2001-01-14 23:47:14 +0000344 'mechanism' specifies which authentication mechanism is to
345 be used - it must appear in <instance>.capabilities in the
346 form AUTH=<mechanism>.
Guido van Rossumeda960a1998-06-18 14:24:28 +0000347
Tim Peters07e99cb2001-01-14 23:47:14 +0000348 'authobject' must be a callable object:
Guido van Rossumeda960a1998-06-18 14:24:28 +0000349
Tim Peters07e99cb2001-01-14 23:47:14 +0000350 data = authobject(response)
Guido van Rossumeda960a1998-06-18 14:24:28 +0000351
Tim Peters07e99cb2001-01-14 23:47:14 +0000352 It will be called to process server continuation responses.
353 It should return data that will be encoded and sent to server.
354 It should return None if the client abort response '*' should
355 be sent instead.
356 """
Eric S. Raymond25a0cbc2001-02-09 06:50:21 +0000357 mech = mechanism.upper()
Neal Norwitzb2071702003-06-29 04:21:43 +0000358 # XXX: shouldn't this code be removed, not commented out?
359 #cap = 'AUTH=%s' % mech
Tim Peters77c06fb2002-11-24 02:35:35 +0000360 #if not cap in self.capabilities: # Let the server decide!
Piers Laudere0273de2002-11-22 05:53:04 +0000361 # raise self.error("Server doesn't allow %s authentication." % mech)
Tim Peters07e99cb2001-01-14 23:47:14 +0000362 self.literal = _Authenticator(authobject).process
363 typ, dat = self._simple_command('AUTHENTICATE', mech)
364 if typ != 'OK':
365 raise self.error(dat[-1])
366 self.state = 'AUTH'
367 return typ, dat
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000368
369
Piers Lauderd80ef022005-06-01 23:50:52 +0000370 def capability(self):
371 """(typ, [data]) = <instance>.capability()
372 Fetch capabilities list from server."""
373
374 name = 'CAPABILITY'
375 typ, dat = self._simple_command(name)
376 return self._untagged_response(typ, dat, name)
377
378
Tim Peters07e99cb2001-01-14 23:47:14 +0000379 def check(self):
380 """Checkpoint mailbox on server.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000381
Tim Peters07e99cb2001-01-14 23:47:14 +0000382 (typ, [data]) = <instance>.check()
383 """
384 return self._simple_command('CHECK')
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000385
386
Tim Peters07e99cb2001-01-14 23:47:14 +0000387 def close(self):
388 """Close currently selected mailbox.
Guido van Rossumeeec0af1998-04-09 14:20:31 +0000389
Tim Peters07e99cb2001-01-14 23:47:14 +0000390 Deleted messages are removed from writable mailbox.
391 This is the recommended command before 'LOGOUT'.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000392
Tim Peters07e99cb2001-01-14 23:47:14 +0000393 (typ, [data]) = <instance>.close()
394 """
395 try:
396 typ, dat = self._simple_command('CLOSE')
397 finally:
398 self.state = 'AUTH'
399 return typ, dat
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000400
401
Tim Peters07e99cb2001-01-14 23:47:14 +0000402 def copy(self, message_set, new_mailbox):
403 """Copy 'message_set' messages onto end of 'new_mailbox'.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000404
Tim Peters07e99cb2001-01-14 23:47:14 +0000405 (typ, [data]) = <instance>.copy(message_set, new_mailbox)
406 """
407 return self._simple_command('COPY', message_set, new_mailbox)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000408
409
Tim Peters07e99cb2001-01-14 23:47:14 +0000410 def create(self, mailbox):
411 """Create new mailbox.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000412
Tim Peters07e99cb2001-01-14 23:47:14 +0000413 (typ, [data]) = <instance>.create(mailbox)
414 """
415 return self._simple_command('CREATE', mailbox)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000416
417
Tim Peters07e99cb2001-01-14 23:47:14 +0000418 def delete(self, mailbox):
419 """Delete old mailbox.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000420
Tim Peters07e99cb2001-01-14 23:47:14 +0000421 (typ, [data]) = <instance>.delete(mailbox)
422 """
423 return self._simple_command('DELETE', mailbox)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000424
Martin v. Löwis7b9190b2004-07-27 05:07:19 +0000425 def deleteacl(self, mailbox, who):
426 """Delete the ACLs (remove any rights) set for who on mailbox.
427
428 (typ, [data]) = <instance>.deleteacl(mailbox, who)
429 """
430 return self._simple_command('DELETEACL', mailbox, who)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000431
Tim Peters07e99cb2001-01-14 23:47:14 +0000432 def expunge(self):
433 """Permanently remove deleted items from selected mailbox.
Guido van Rossumeeec0af1998-04-09 14:20:31 +0000434
Tim Peters07e99cb2001-01-14 23:47:14 +0000435 Generates 'EXPUNGE' response for each deleted message.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000436
Tim Peters07e99cb2001-01-14 23:47:14 +0000437 (typ, [data]) = <instance>.expunge()
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000438
Tim Peters07e99cb2001-01-14 23:47:14 +0000439 'data' is list of 'EXPUNGE'd message numbers in order received.
440 """
441 name = 'EXPUNGE'
442 typ, dat = self._simple_command(name)
443 return self._untagged_response(typ, dat, name)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000444
445
Tim Peters07e99cb2001-01-14 23:47:14 +0000446 def fetch(self, message_set, message_parts):
447 """Fetch (parts of) messages.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000448
Tim Peters07e99cb2001-01-14 23:47:14 +0000449 (typ, [data, ...]) = <instance>.fetch(message_set, message_parts)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000450
Tim Peters07e99cb2001-01-14 23:47:14 +0000451 'message_parts' should be a string of selected parts
452 enclosed in parentheses, eg: "(UID BODY[TEXT])".
Fred Drakefd267d92000-05-25 03:25:26 +0000453
Tim Peters07e99cb2001-01-14 23:47:14 +0000454 'data' are tuples of message part envelope and data.
455 """
456 name = 'FETCH'
457 typ, dat = self._simple_command(name, message_set, message_parts)
458 return self._untagged_response(typ, dat, name)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000459
460
Piers Lauder15e5d532001-07-20 10:52:06 +0000461 def getacl(self, mailbox):
462 """Get the ACLs for a mailbox.
463
464 (typ, [data]) = <instance>.getacl(mailbox)
465 """
466 typ, dat = self._simple_command('GETACL', mailbox)
467 return self._untagged_response(typ, dat, 'ACL')
468
469
Piers Lauderd80ef022005-06-01 23:50:52 +0000470 def getannotation(self, mailbox, entry, attribute):
471 """(typ, [data]) = <instance>.getannotation(mailbox, entry, attribute)
472 Retrieve ANNOTATIONs."""
473
474 typ, dat = self._simple_command('GETANNOTATION', mailbox, entry, attribute)
475 return self._untagged_response(typ, dat, 'ANNOTATION')
476
477
Piers Lauder3fca2912002-06-17 07:07:20 +0000478 def getquota(self, root):
479 """Get the quota root's resource usage and limits.
480
Neal Norwitz1ed564a2002-06-17 12:43:20 +0000481 Part of the IMAP4 QUOTA extension defined in rfc2087.
Piers Lauder3fca2912002-06-17 07:07:20 +0000482
483 (typ, [data]) = <instance>.getquota(root)
Neal Norwitz1ed564a2002-06-17 12:43:20 +0000484 """
Piers Lauder3fca2912002-06-17 07:07:20 +0000485 typ, dat = self._simple_command('GETQUOTA', root)
486 return self._untagged_response(typ, dat, 'QUOTA')
487
488
489 def getquotaroot(self, mailbox):
490 """Get the list of quota roots for the named mailbox.
491
492 (typ, [[QUOTAROOT responses...], [QUOTA responses]]) = <instance>.getquotaroot(mailbox)
Neal Norwitz1ed564a2002-06-17 12:43:20 +0000493 """
Piers Lauder6a4e6352004-08-10 01:24:54 +0000494 typ, dat = self._simple_command('GETQUOTAROOT', mailbox)
Piers Lauder3fca2912002-06-17 07:07:20 +0000495 typ, quota = self._untagged_response(typ, dat, 'QUOTA')
496 typ, quotaroot = self._untagged_response(typ, dat, 'QUOTAROOT')
Neal Norwitz1ed564a2002-06-17 12:43:20 +0000497 return typ, [quotaroot, quota]
Piers Lauder3fca2912002-06-17 07:07:20 +0000498
499
Tim Peters07e99cb2001-01-14 23:47:14 +0000500 def list(self, directory='""', pattern='*'):
501 """List mailbox names in directory matching pattern.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000502
Tim Peters07e99cb2001-01-14 23:47:14 +0000503 (typ, [data]) = <instance>.list(directory='""', pattern='*')
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000504
Tim Peters07e99cb2001-01-14 23:47:14 +0000505 'data' is list of LIST responses.
506 """
507 name = 'LIST'
508 typ, dat = self._simple_command(name, directory, pattern)
509 return self._untagged_response(typ, dat, name)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000510
511
Tim Peters07e99cb2001-01-14 23:47:14 +0000512 def login(self, user, password):
513 """Identify client using plaintext password.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000514
Tim Peters07e99cb2001-01-14 23:47:14 +0000515 (typ, [data]) = <instance>.login(user, password)
Guido van Rossum8c062211999-12-13 23:27:45 +0000516
Tim Peters07e99cb2001-01-14 23:47:14 +0000517 NB: 'password' will be quoted.
518 """
Tim Peters07e99cb2001-01-14 23:47:14 +0000519 typ, dat = self._simple_command('LOGIN', user, self._quote(password))
520 if typ != 'OK':
521 raise self.error(dat[-1])
522 self.state = 'AUTH'
523 return typ, dat
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000524
525
Piers Laudere0273de2002-11-22 05:53:04 +0000526 def login_cram_md5(self, user, password):
527 """ Force use of CRAM-MD5 authentication.
528
529 (typ, [data]) = <instance>.login_cram_md5(user, password)
530 """
531 self.user, self.password = user, password
532 return self.authenticate('CRAM-MD5', self._CRAM_MD5_AUTH)
533
534
535 def _CRAM_MD5_AUTH(self, challenge):
536 """ Authobject to use with CRAM-MD5 authentication. """
537 import hmac
538 return self.user + " " + hmac.HMAC(self.password, challenge).hexdigest()
539
540
Tim Peters07e99cb2001-01-14 23:47:14 +0000541 def logout(self):
542 """Shutdown connection to server.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000543
Tim Peters07e99cb2001-01-14 23:47:14 +0000544 (typ, [data]) = <instance>.logout()
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000545
Tim Peters07e99cb2001-01-14 23:47:14 +0000546 Returns server 'BYE' response.
547 """
548 self.state = 'LOGOUT'
549 try: typ, dat = self._simple_command('LOGOUT')
550 except: typ, dat = 'NO', ['%s: %s' % sys.exc_info()[:2]]
Piers Lauder15e5d532001-07-20 10:52:06 +0000551 self.shutdown()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000552 if 'BYE' in self.untagged_responses:
Tim Peters07e99cb2001-01-14 23:47:14 +0000553 return 'BYE', self.untagged_responses['BYE']
554 return typ, dat
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000555
556
Tim Peters07e99cb2001-01-14 23:47:14 +0000557 def lsub(self, directory='""', pattern='*'):
558 """List 'subscribed' mailbox names in directory matching pattern.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000559
Tim Peters07e99cb2001-01-14 23:47:14 +0000560 (typ, [data, ...]) = <instance>.lsub(directory='""', pattern='*')
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000561
Tim Peters07e99cb2001-01-14 23:47:14 +0000562 'data' are tuples of message part envelope and data.
563 """
564 name = 'LSUB'
565 typ, dat = self._simple_command(name, directory, pattern)
566 return self._untagged_response(typ, dat, name)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000567
Martin v. Löwis7b9190b2004-07-27 05:07:19 +0000568 def myrights(self, mailbox):
569 """Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
570
571 (typ, [data]) = <instance>.myrights(mailbox)
572 """
573 typ,dat = self._simple_command('MYRIGHTS', mailbox)
574 return self._untagged_response(typ, dat, 'MYRIGHTS')
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000575
Piers Lauder15e5d532001-07-20 10:52:06 +0000576 def namespace(self):
577 """ Returns IMAP namespaces ala rfc2342
578
579 (typ, [data, ...]) = <instance>.namespace()
580 """
581 name = 'NAMESPACE'
582 typ, dat = self._simple_command(name)
583 return self._untagged_response(typ, dat, name)
584
585
Tim Peters07e99cb2001-01-14 23:47:14 +0000586 def noop(self):
587 """Send NOOP command.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000588
Piers Laudere0273de2002-11-22 05:53:04 +0000589 (typ, [data]) = <instance>.noop()
Tim Peters07e99cb2001-01-14 23:47:14 +0000590 """
591 if __debug__:
592 if self.debug >= 3:
Piers Lauderf2d7d152002-02-22 01:15:17 +0000593 self._dump_ur(self.untagged_responses)
Tim Peters07e99cb2001-01-14 23:47:14 +0000594 return self._simple_command('NOOP')
Guido van Rossum6884af71998-05-29 13:34:03 +0000595
596
Tim Peters07e99cb2001-01-14 23:47:14 +0000597 def partial(self, message_num, message_part, start, length):
598 """Fetch truncated part of a message.
Guido van Rossumeda960a1998-06-18 14:24:28 +0000599
Tim Peters07e99cb2001-01-14 23:47:14 +0000600 (typ, [data, ...]) = <instance>.partial(message_num, message_part, start, length)
Guido van Rossumeda960a1998-06-18 14:24:28 +0000601
Tim Peters07e99cb2001-01-14 23:47:14 +0000602 'data' is tuple of message part envelope and data.
603 """
604 name = 'PARTIAL'
605 typ, dat = self._simple_command(name, message_num, message_part, start, length)
606 return self._untagged_response(typ, dat, 'FETCH')
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000607
608
Piers Laudere0273de2002-11-22 05:53:04 +0000609 def proxyauth(self, user):
610 """Assume authentication as "user".
611
612 Allows an authorised administrator to proxy into any user's
613 mailbox.
614
615 (typ, [data]) = <instance>.proxyauth(user)
616 """
617
618 name = 'PROXYAUTH'
619 return self._simple_command('PROXYAUTH', user)
620
621
Tim Peters07e99cb2001-01-14 23:47:14 +0000622 def rename(self, oldmailbox, newmailbox):
623 """Rename old mailbox name to new.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000624
Piers Laudere0273de2002-11-22 05:53:04 +0000625 (typ, [data]) = <instance>.rename(oldmailbox, newmailbox)
Tim Peters07e99cb2001-01-14 23:47:14 +0000626 """
627 return self._simple_command('RENAME', oldmailbox, newmailbox)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000628
629
Tim Peters07e99cb2001-01-14 23:47:14 +0000630 def search(self, charset, *criteria):
631 """Search mailbox for matching messages.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000632
Martin v. Löwis3ae0f7a2003-03-27 16:59:38 +0000633 (typ, [data]) = <instance>.search(charset, criterion, ...)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000634
Tim Peters07e99cb2001-01-14 23:47:14 +0000635 'data' is space separated list of matching message numbers.
636 """
637 name = 'SEARCH'
638 if charset:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000639 typ, dat = self._simple_command(name, 'CHARSET', charset, *criteria)
Piers Lauder15e5d532001-07-20 10:52:06 +0000640 else:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000641 typ, dat = self._simple_command(name, *criteria)
Tim Peters07e99cb2001-01-14 23:47:14 +0000642 return self._untagged_response(typ, dat, name)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000643
644
Piers Lauder14f39402005-08-31 10:46:29 +0000645 def select(self, mailbox='INBOX', readonly=False):
Tim Peters07e99cb2001-01-14 23:47:14 +0000646 """Select a mailbox.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000647
Tim Peters07e99cb2001-01-14 23:47:14 +0000648 Flush all untagged responses.
Guido van Rossum46586821998-05-18 14:39:42 +0000649
Piers Lauder14f39402005-08-31 10:46:29 +0000650 (typ, [data]) = <instance>.select(mailbox='INBOX', readonly=False)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000651
Tim Peters07e99cb2001-01-14 23:47:14 +0000652 'data' is count of messages in mailbox ('EXISTS' response).
Piers Lauder6a4e6352004-08-10 01:24:54 +0000653
654 Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so
655 other responses should be obtained via <instance>.response('FLAGS') etc.
Tim Peters07e99cb2001-01-14 23:47:14 +0000656 """
Tim Peters07e99cb2001-01-14 23:47:14 +0000657 self.untagged_responses = {} # Flush old responses.
658 self.is_readonly = readonly
Piers Lauder14f39402005-08-31 10:46:29 +0000659 if readonly:
Tim Peters07e99cb2001-01-14 23:47:14 +0000660 name = 'EXAMINE'
661 else:
662 name = 'SELECT'
663 typ, dat = self._simple_command(name, mailbox)
664 if typ != 'OK':
665 self.state = 'AUTH' # Might have been 'SELECTED'
666 return typ, dat
667 self.state = 'SELECTED'
Raymond Hettinger54f02222002-06-01 14:18:47 +0000668 if 'READ-ONLY' in self.untagged_responses \
Tim Peters07e99cb2001-01-14 23:47:14 +0000669 and not readonly:
670 if __debug__:
671 if self.debug >= 1:
Piers Lauderf2d7d152002-02-22 01:15:17 +0000672 self._dump_ur(self.untagged_responses)
Tim Peters07e99cb2001-01-14 23:47:14 +0000673 raise self.readonly('%s is not writable' % mailbox)
674 return typ, self.untagged_responses.get('EXISTS', [None])
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000675
676
Piers Lauder15e5d532001-07-20 10:52:06 +0000677 def setacl(self, mailbox, who, what):
678 """Set a mailbox acl.
679
Piers Lauderf167dc32004-03-25 00:12:21 +0000680 (typ, [data]) = <instance>.setacl(mailbox, who, what)
Piers Lauder15e5d532001-07-20 10:52:06 +0000681 """
682 return self._simple_command('SETACL', mailbox, who, what)
683
684
Piers Lauderd80ef022005-06-01 23:50:52 +0000685 def setannotation(self, *args):
686 """(typ, [data]) = <instance>.setannotation(mailbox[, entry, attribute]+)
687 Set ANNOTATIONs."""
688
689 typ, dat = self._simple_command('SETANNOTATION', *args)
690 return self._untagged_response(typ, dat, 'ANNOTATION')
691
692
Piers Lauder3fca2912002-06-17 07:07:20 +0000693 def setquota(self, root, limits):
694 """Set the quota root's resource limits.
695
696 (typ, [data]) = <instance>.setquota(root, limits)
Neal Norwitz1ed564a2002-06-17 12:43:20 +0000697 """
Piers Lauder3fca2912002-06-17 07:07:20 +0000698 typ, dat = self._simple_command('SETQUOTA', root, limits)
699 return self._untagged_response(typ, dat, 'QUOTA')
700
701
Piers Lauder15e5d532001-07-20 10:52:06 +0000702 def sort(self, sort_criteria, charset, *search_criteria):
703 """IMAP4rev1 extension SORT command.
704
705 (typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...)
706 """
707 name = 'SORT'
Tim Peters87cc0c32001-07-21 01:41:30 +0000708 #if not name in self.capabilities: # Let the server decide!
709 # raise self.error('unimplemented extension command: %s' % name)
Piers Lauder15e5d532001-07-20 10:52:06 +0000710 if (sort_criteria[0],sort_criteria[-1]) != ('(',')'):
Tim Peters87cc0c32001-07-21 01:41:30 +0000711 sort_criteria = '(%s)' % sort_criteria
Guido van Rossum68468eb2003-02-27 20:14:51 +0000712 typ, dat = self._simple_command(name, sort_criteria, charset, *search_criteria)
Piers Lauder15e5d532001-07-20 10:52:06 +0000713 return self._untagged_response(typ, dat, name)
714
715
Antoine Pitrouf3b001f2010-11-12 18:49:16 +0000716 def starttls(self, ssl_context=None):
717 name = 'STARTTLS'
718 if not HAVE_SSL:
719 raise self.error('SSL support missing')
720 if self._tls_established:
721 raise self.abort('TLS session already established')
722 if name not in self.capabilities:
723 raise self.abort('TLS not supported by server')
724 # Generate a default SSL context if none was passed.
725 if ssl_context is None:
726 ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
727 # SSLv2 considered harmful.
728 ssl_context.options |= ssl.OP_NO_SSLv2
729 typ, dat = self._simple_command(name)
730 if typ == 'OK':
731 self.sock = ssl_context.wrap_socket(self.sock)
732 self.file = self.sock.makefile('rb')
733 self._tls_established = True
Antoine Pitroudbe75192010-11-16 17:55:26 +0000734 self._get_capabilities()
Antoine Pitrouf3b001f2010-11-12 18:49:16 +0000735 else:
736 raise self.error("Couldn't establish TLS session")
737 return self._untagged_response(typ, dat, name)
738
739
Tim Peters07e99cb2001-01-14 23:47:14 +0000740 def status(self, mailbox, names):
741 """Request named status conditions for mailbox.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000742
Tim Peters07e99cb2001-01-14 23:47:14 +0000743 (typ, [data]) = <instance>.status(mailbox, names)
744 """
745 name = 'STATUS'
Tim Peters87cc0c32001-07-21 01:41:30 +0000746 #if self.PROTOCOL_VERSION == 'IMAP4': # Let the server decide!
Piers Lauder15e5d532001-07-20 10:52:06 +0000747 # raise self.error('%s unimplemented in IMAP4 (obtain IMAP4rev1 server, or re-code)' % name)
Tim Peters07e99cb2001-01-14 23:47:14 +0000748 typ, dat = self._simple_command(name, mailbox, names)
749 return self._untagged_response(typ, dat, name)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000750
751
Tim Peters07e99cb2001-01-14 23:47:14 +0000752 def store(self, message_set, command, flags):
753 """Alters flag dispositions for messages in mailbox.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000754
Tim Peters07e99cb2001-01-14 23:47:14 +0000755 (typ, [data]) = <instance>.store(message_set, command, flags)
756 """
757 if (flags[0],flags[-1]) != ('(',')'):
758 flags = '(%s)' % flags # Avoid quoting the flags
759 typ, dat = self._simple_command('STORE', message_set, command, flags)
760 return self._untagged_response(typ, dat, 'FETCH')
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000761
762
Tim Peters07e99cb2001-01-14 23:47:14 +0000763 def subscribe(self, mailbox):
764 """Subscribe to new mailbox.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000765
Tim Peters07e99cb2001-01-14 23:47:14 +0000766 (typ, [data]) = <instance>.subscribe(mailbox)
767 """
768 return self._simple_command('SUBSCRIBE', mailbox)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000769
770
Martin v. Löwisd8921372003-11-10 06:44:44 +0000771 def thread(self, threading_algorithm, charset, *search_criteria):
772 """IMAPrev1 extension THREAD command.
773
Mark Dickinson8ae535b2009-12-24 16:12:49 +0000774 (type, [data]) = <instance>.thread(threading_algorithm, charset, search_criteria, ...)
Martin v. Löwisd8921372003-11-10 06:44:44 +0000775 """
776 name = 'THREAD'
777 typ, dat = self._simple_command(name, threading_algorithm, charset, *search_criteria)
778 return self._untagged_response(typ, dat, name)
779
780
Tim Peters07e99cb2001-01-14 23:47:14 +0000781 def uid(self, command, *args):
782 """Execute "command arg ..." with messages identified by UID,
783 rather than message number.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000784
Tim Peters07e99cb2001-01-14 23:47:14 +0000785 (typ, [data]) = <instance>.uid(command, arg1, arg2, ...)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000786
Tim Peters07e99cb2001-01-14 23:47:14 +0000787 Returns response appropriate to 'command'.
788 """
Eric S. Raymond25a0cbc2001-02-09 06:50:21 +0000789 command = command.upper()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000790 if not command in Commands:
Tim Peters07e99cb2001-01-14 23:47:14 +0000791 raise self.error("Unknown IMAP4 UID command: %s" % command)
792 if self.state not in Commands[command]:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000793 raise self.error("command %s illegal in state %s, "
794 "only allowed in states %s" %
795 (command, self.state,
796 ', '.join(Commands[command])))
Tim Peters07e99cb2001-01-14 23:47:14 +0000797 name = 'UID'
Guido van Rossum68468eb2003-02-27 20:14:51 +0000798 typ, dat = self._simple_command(name, command, *args)
Georg Brandl05245f72010-07-31 22:32:52 +0000799 if command in ('SEARCH', 'SORT', 'THREAD'):
Piers Lauder15e5d532001-07-20 10:52:06 +0000800 name = command
Tim Peters07e99cb2001-01-14 23:47:14 +0000801 else:
802 name = 'FETCH'
803 return self._untagged_response(typ, dat, name)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000804
805
Tim Peters07e99cb2001-01-14 23:47:14 +0000806 def unsubscribe(self, mailbox):
807 """Unsubscribe from old mailbox.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000808
Tim Peters07e99cb2001-01-14 23:47:14 +0000809 (typ, [data]) = <instance>.unsubscribe(mailbox)
810 """
811 return self._simple_command('UNSUBSCRIBE', mailbox)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000812
813
Tim Peters07e99cb2001-01-14 23:47:14 +0000814 def xatom(self, name, *args):
815 """Allow simple extension commands
816 notified by server in CAPABILITY response.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000817
Piers Lauder15e5d532001-07-20 10:52:06 +0000818 Assumes command is legal in current state.
819
Tim Peters07e99cb2001-01-14 23:47:14 +0000820 (typ, [data]) = <instance>.xatom(name, arg, ...)
Piers Lauder15e5d532001-07-20 10:52:06 +0000821
822 Returns response appropriate to extension command `name'.
Tim Peters07e99cb2001-01-14 23:47:14 +0000823 """
Piers Lauder15e5d532001-07-20 10:52:06 +0000824 name = name.upper()
Tim Peters87cc0c32001-07-21 01:41:30 +0000825 #if not name in self.capabilities: # Let the server decide!
Piers Lauder15e5d532001-07-20 10:52:06 +0000826 # raise self.error('unknown extension command: %s' % name)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000827 if not name in Commands:
Piers Lauder15e5d532001-07-20 10:52:06 +0000828 Commands[name] = (self.state,)
Guido van Rossum68468eb2003-02-27 20:14:51 +0000829 return self._simple_command(name, *args)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000830
831
832
Tim Peters07e99cb2001-01-14 23:47:14 +0000833 # Private methods
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000834
835
Tim Peters07e99cb2001-01-14 23:47:14 +0000836 def _append_untagged(self, typ, dat):
Christian Heimesfb5faf02008-11-05 19:39:50 +0000837 if dat is None:
838 dat = b''
Tim Peters07e99cb2001-01-14 23:47:14 +0000839 ur = self.untagged_responses
840 if __debug__:
841 if self.debug >= 5:
Christian Heimesfb5faf02008-11-05 19:39:50 +0000842 self._mesg('untagged_responses[%s] %s += ["%r"]' %
Tim Peters07e99cb2001-01-14 23:47:14 +0000843 (typ, len(ur.get(typ,'')), dat))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000844 if typ in ur:
Tim Peters07e99cb2001-01-14 23:47:14 +0000845 ur[typ].append(dat)
846 else:
847 ur[typ] = [dat]
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000848
849
Tim Peters07e99cb2001-01-14 23:47:14 +0000850 def _check_bye(self):
851 bye = self.untagged_responses.get('BYE')
852 if bye:
Antoine Pitroudac47912010-11-10 00:18:40 +0000853 raise self.abort(bye[-1].decode('ascii', 'replace'))
Guido van Rossum8c062211999-12-13 23:27:45 +0000854
855
Tim Peters07e99cb2001-01-14 23:47:14 +0000856 def _command(self, name, *args):
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000857
Tim Peters07e99cb2001-01-14 23:47:14 +0000858 if self.state not in Commands[name]:
859 self.literal = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000860 raise self.error("command %s illegal in state %s, "
861 "only allowed in states %s" %
862 (name, self.state,
863 ', '.join(Commands[name])))
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000864
Tim Peters07e99cb2001-01-14 23:47:14 +0000865 for typ in ('OK', 'NO', 'BAD'):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000866 if typ in self.untagged_responses:
Tim Peters07e99cb2001-01-14 23:47:14 +0000867 del self.untagged_responses[typ]
Guido van Rossum26367a01998-09-28 15:34:46 +0000868
Raymond Hettinger54f02222002-06-01 14:18:47 +0000869 if 'READ-ONLY' in self.untagged_responses \
Tim Peters07e99cb2001-01-14 23:47:14 +0000870 and not self.is_readonly:
871 raise self.readonly('mailbox status changed to READ-ONLY')
Guido van Rossumeda960a1998-06-18 14:24:28 +0000872
Tim Peters07e99cb2001-01-14 23:47:14 +0000873 tag = self._new_tag()
Christian Heimesfb5faf02008-11-05 19:39:50 +0000874 name = bytes(name, 'ASCII')
875 data = tag + b' ' + name
Tim Peters07e99cb2001-01-14 23:47:14 +0000876 for arg in args:
877 if arg is None: continue
Christian Heimesfb5faf02008-11-05 19:39:50 +0000878 if isinstance(arg, str):
879 arg = bytes(arg, "ASCII")
Christian Heimesfb5faf02008-11-05 19:39:50 +0000880 data = data + b' ' + arg
Guido van Rossum6884af71998-05-29 13:34:03 +0000881
Tim Peters07e99cb2001-01-14 23:47:14 +0000882 literal = self.literal
883 if literal is not None:
884 self.literal = None
885 if type(literal) is type(self._command):
886 literator = literal
887 else:
888 literator = None
Christian Heimesfb5faf02008-11-05 19:39:50 +0000889 data = data + bytes(' {%s}' % len(literal), 'ASCII')
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000890
Tim Peters07e99cb2001-01-14 23:47:14 +0000891 if __debug__:
892 if self.debug >= 4:
Christian Heimesfb5faf02008-11-05 19:39:50 +0000893 self._mesg('> %r' % data)
Tim Peters07e99cb2001-01-14 23:47:14 +0000894 else:
Christian Heimesfb5faf02008-11-05 19:39:50 +0000895 self._log('> %r' % data)
Guido van Rossum8c062211999-12-13 23:27:45 +0000896
Tim Peters07e99cb2001-01-14 23:47:14 +0000897 try:
Christian Heimesfb5faf02008-11-05 19:39:50 +0000898 self.send(data + CRLF)
Guido van Rossumb940e112007-01-10 16:19:56 +0000899 except (socket.error, OSError) as val:
Tim Peters07e99cb2001-01-14 23:47:14 +0000900 raise self.abort('socket error: %s' % val)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000901
Tim Peters07e99cb2001-01-14 23:47:14 +0000902 if literal is None:
903 return tag
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000904
Tim Peters07e99cb2001-01-14 23:47:14 +0000905 while 1:
906 # Wait for continuation response
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000907
Tim Peters07e99cb2001-01-14 23:47:14 +0000908 while self._get_response():
909 if self.tagged_commands[tag]: # BAD/NO?
910 return tag
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000911
Tim Peters07e99cb2001-01-14 23:47:14 +0000912 # Send literal
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000913
Tim Peters07e99cb2001-01-14 23:47:14 +0000914 if literator:
915 literal = literator(self.continuation_response)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000916
Tim Peters07e99cb2001-01-14 23:47:14 +0000917 if __debug__:
918 if self.debug >= 4:
Piers Lauderf2d7d152002-02-22 01:15:17 +0000919 self._mesg('write literal size %s' % len(literal))
Guido van Rossumeda960a1998-06-18 14:24:28 +0000920
Tim Peters07e99cb2001-01-14 23:47:14 +0000921 try:
Piers Lauder15e5d532001-07-20 10:52:06 +0000922 self.send(literal)
923 self.send(CRLF)
Guido van Rossumb940e112007-01-10 16:19:56 +0000924 except (socket.error, OSError) as val:
Tim Peters07e99cb2001-01-14 23:47:14 +0000925 raise self.abort('socket error: %s' % val)
Guido van Rossumeda960a1998-06-18 14:24:28 +0000926
Tim Peters07e99cb2001-01-14 23:47:14 +0000927 if not literator:
928 break
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000929
Tim Peters07e99cb2001-01-14 23:47:14 +0000930 return tag
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000931
932
Tim Peters07e99cb2001-01-14 23:47:14 +0000933 def _command_complete(self, name, tag):
Antoine Pitroudac47912010-11-10 00:18:40 +0000934 # BYE is expected after LOGOUT
935 if name != 'LOGOUT':
936 self._check_bye()
Tim Peters07e99cb2001-01-14 23:47:14 +0000937 try:
938 typ, data = self._get_tagged_response(tag)
Guido van Rossumb940e112007-01-10 16:19:56 +0000939 except self.abort as val:
Tim Peters07e99cb2001-01-14 23:47:14 +0000940 raise self.abort('command: %s => %s' % (name, val))
Guido van Rossumb940e112007-01-10 16:19:56 +0000941 except self.error as val:
Tim Peters07e99cb2001-01-14 23:47:14 +0000942 raise self.error('command: %s => %s' % (name, val))
Antoine Pitroudac47912010-11-10 00:18:40 +0000943 if name != 'LOGOUT':
944 self._check_bye()
Tim Peters07e99cb2001-01-14 23:47:14 +0000945 if typ == 'BAD':
946 raise self.error('%s command error: %s %s' % (name, typ, data))
947 return typ, data
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000948
949
Antoine Pitroudbe75192010-11-16 17:55:26 +0000950 def _get_capabilities(self):
951 typ, dat = self.capability()
952 if dat == [None]:
953 raise self.error('no CAPABILITY response from server')
954 dat = str(dat[-1], "ASCII")
955 dat = dat.upper()
956 self.capabilities = tuple(dat.split())
957
958
Tim Peters07e99cb2001-01-14 23:47:14 +0000959 def _get_response(self):
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000960
Tim Peters07e99cb2001-01-14 23:47:14 +0000961 # Read response and store.
962 #
963 # Returns None for continuation responses,
964 # otherwise first response line received.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000965
Tim Peters07e99cb2001-01-14 23:47:14 +0000966 resp = self._get_line()
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000967
Tim Peters07e99cb2001-01-14 23:47:14 +0000968 # Command completion response?
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000969
Tim Peters07e99cb2001-01-14 23:47:14 +0000970 if self._match(self.tagre, resp):
971 tag = self.mo.group('tag')
Raymond Hettinger54f02222002-06-01 14:18:47 +0000972 if not tag in self.tagged_commands:
Tim Peters07e99cb2001-01-14 23:47:14 +0000973 raise self.abort('unexpected tagged response: %s' % resp)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000974
Tim Peters07e99cb2001-01-14 23:47:14 +0000975 typ = self.mo.group('type')
Christian Heimesfb5faf02008-11-05 19:39:50 +0000976 typ = str(typ, 'ASCII')
Tim Peters07e99cb2001-01-14 23:47:14 +0000977 dat = self.mo.group('data')
978 self.tagged_commands[tag] = (typ, [dat])
979 else:
980 dat2 = None
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000981
Tim Peters07e99cb2001-01-14 23:47:14 +0000982 # '*' (untagged) responses?
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000983
Tim Peters07e99cb2001-01-14 23:47:14 +0000984 if not self._match(Untagged_response, resp):
985 if self._match(Untagged_status, resp):
986 dat2 = self.mo.group('data2')
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000987
Tim Peters07e99cb2001-01-14 23:47:14 +0000988 if self.mo is None:
989 # Only other possibility is '+' (continuation) response...
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000990
Tim Peters07e99cb2001-01-14 23:47:14 +0000991 if self._match(Continuation, resp):
992 self.continuation_response = self.mo.group('data')
993 return None # NB: indicates continuation
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000994
Tim Peters07e99cb2001-01-14 23:47:14 +0000995 raise self.abort("unexpected response: '%s'" % resp)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +0000996
Tim Peters07e99cb2001-01-14 23:47:14 +0000997 typ = self.mo.group('type')
Christian Heimesfb5faf02008-11-05 19:39:50 +0000998 typ = str(typ, 'ascii')
Tim Peters07e99cb2001-01-14 23:47:14 +0000999 dat = self.mo.group('data')
Christian Heimesfb5faf02008-11-05 19:39:50 +00001000 if dat is None: dat = b'' # Null untagged response
1001 if dat2: dat = dat + b' ' + dat2
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001002
Tim Peters07e99cb2001-01-14 23:47:14 +00001003 # Is there a literal to come?
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001004
Tim Peters07e99cb2001-01-14 23:47:14 +00001005 while self._match(Literal, dat):
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001006
Tim Peters07e99cb2001-01-14 23:47:14 +00001007 # Read literal direct from connection.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001008
Eric S. Raymond25a0cbc2001-02-09 06:50:21 +00001009 size = int(self.mo.group('size'))
Tim Peters07e99cb2001-01-14 23:47:14 +00001010 if __debug__:
1011 if self.debug >= 4:
Piers Lauderf2d7d152002-02-22 01:15:17 +00001012 self._mesg('read literal size %s' % size)
Piers Lauder15e5d532001-07-20 10:52:06 +00001013 data = self.read(size)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001014
Tim Peters07e99cb2001-01-14 23:47:14 +00001015 # Store response with literal as tuple
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001016
Tim Peters07e99cb2001-01-14 23:47:14 +00001017 self._append_untagged(typ, (dat, data))
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001018
Tim Peters07e99cb2001-01-14 23:47:14 +00001019 # Read trailer - possibly containing another literal
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001020
Tim Peters07e99cb2001-01-14 23:47:14 +00001021 dat = self._get_line()
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001022
Tim Peters07e99cb2001-01-14 23:47:14 +00001023 self._append_untagged(typ, dat)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001024
Tim Peters07e99cb2001-01-14 23:47:14 +00001025 # Bracketed response information?
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001026
Tim Peters07e99cb2001-01-14 23:47:14 +00001027 if typ in ('OK', 'NO', 'BAD') and self._match(Response_code, dat):
Christian Heimesfb5faf02008-11-05 19:39:50 +00001028 typ = self.mo.group('type')
1029 typ = str(typ, "ASCII")
1030 self._append_untagged(typ, self.mo.group('data'))
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001031
Tim Peters07e99cb2001-01-14 23:47:14 +00001032 if __debug__:
1033 if self.debug >= 1 and typ in ('NO', 'BAD', 'BYE'):
Christian Heimesfb5faf02008-11-05 19:39:50 +00001034 self._mesg('%s response: %r' % (typ, dat))
Guido van Rossum26367a01998-09-28 15:34:46 +00001035
Tim Peters07e99cb2001-01-14 23:47:14 +00001036 return resp
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001037
1038
Tim Peters07e99cb2001-01-14 23:47:14 +00001039 def _get_tagged_response(self, tag):
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001040
Tim Peters07e99cb2001-01-14 23:47:14 +00001041 while 1:
1042 result = self.tagged_commands[tag]
1043 if result is not None:
1044 del self.tagged_commands[tag]
1045 return result
Guido van Rossumf36b1822000-02-17 17:12:39 +00001046
Tim Peters07e99cb2001-01-14 23:47:14 +00001047 # Some have reported "unexpected response" exceptions.
1048 # Note that ignoring them here causes loops.
1049 # Instead, send me details of the unexpected response and
1050 # I'll update the code in `_get_response()'.
Guido van Rossumf36b1822000-02-17 17:12:39 +00001051
Tim Peters07e99cb2001-01-14 23:47:14 +00001052 try:
1053 self._get_response()
Guido van Rossumb940e112007-01-10 16:19:56 +00001054 except self.abort as val:
Tim Peters07e99cb2001-01-14 23:47:14 +00001055 if __debug__:
1056 if self.debug >= 1:
Piers Lauderf2d7d152002-02-22 01:15:17 +00001057 self.print_log()
Tim Peters07e99cb2001-01-14 23:47:14 +00001058 raise
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001059
1060
Tim Peters07e99cb2001-01-14 23:47:14 +00001061 def _get_line(self):
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001062
Piers Lauder15e5d532001-07-20 10:52:06 +00001063 line = self.readline()
Tim Peters07e99cb2001-01-14 23:47:14 +00001064 if not line:
1065 raise self.abort('socket error: EOF')
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001066
Tim Peters07e99cb2001-01-14 23:47:14 +00001067 # Protocol mandates all lines terminated by CRLF
R. David Murraye8dc2582009-12-10 02:08:06 +00001068 if not line.endswith(b'\r\n'):
1069 raise self.abort('socket error: unterminated line')
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001070
Tim Peters07e99cb2001-01-14 23:47:14 +00001071 line = line[:-2]
1072 if __debug__:
1073 if self.debug >= 4:
Christian Heimesfb5faf02008-11-05 19:39:50 +00001074 self._mesg('< %r' % line)
Tim Peters07e99cb2001-01-14 23:47:14 +00001075 else:
Christian Heimesfb5faf02008-11-05 19:39:50 +00001076 self._log('< %r' % line)
Tim Peters07e99cb2001-01-14 23:47:14 +00001077 return line
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001078
1079
Tim Peters07e99cb2001-01-14 23:47:14 +00001080 def _match(self, cre, s):
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001081
Tim Peters07e99cb2001-01-14 23:47:14 +00001082 # Run compiled regular expression match method on 's'.
1083 # Save result, return success.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001084
Tim Peters07e99cb2001-01-14 23:47:14 +00001085 self.mo = cre.match(s)
1086 if __debug__:
1087 if self.mo is not None and self.debug >= 5:
Christian Heimesfb5faf02008-11-05 19:39:50 +00001088 self._mesg("\tmatched r'%r' => %r" % (cre.pattern, self.mo.groups()))
Tim Peters07e99cb2001-01-14 23:47:14 +00001089 return self.mo is not None
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001090
1091
Tim Peters07e99cb2001-01-14 23:47:14 +00001092 def _new_tag(self):
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001093
Christian Heimesfb5faf02008-11-05 19:39:50 +00001094 tag = self.tagpre + bytes(str(self.tagnum), 'ASCII')
Tim Peters07e99cb2001-01-14 23:47:14 +00001095 self.tagnum = self.tagnum + 1
1096 self.tagged_commands[tag] = None
1097 return tag
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001098
1099
Tim Peters07e99cb2001-01-14 23:47:14 +00001100 def _quote(self, arg):
Guido van Rossum8c062211999-12-13 23:27:45 +00001101
Antoine Pitroub1436f12010-11-09 22:55:55 +00001102 arg = arg.replace('\\', '\\\\')
1103 arg = arg.replace('"', '\\"')
Guido van Rossum8c062211999-12-13 23:27:45 +00001104
Antoine Pitroub1436f12010-11-09 22:55:55 +00001105 return '"' + arg + '"'
Guido van Rossum8c062211999-12-13 23:27:45 +00001106
1107
Tim Peters07e99cb2001-01-14 23:47:14 +00001108 def _simple_command(self, name, *args):
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001109
Guido van Rossum68468eb2003-02-27 20:14:51 +00001110 return self._command_complete(name, self._command(name, *args))
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001111
1112
Tim Peters07e99cb2001-01-14 23:47:14 +00001113 def _untagged_response(self, typ, dat, name):
Tim Peters07e99cb2001-01-14 23:47:14 +00001114 if typ == 'NO':
1115 return typ, dat
Raymond Hettinger54f02222002-06-01 14:18:47 +00001116 if not name in self.untagged_responses:
Tim Peters07e99cb2001-01-14 23:47:14 +00001117 return typ, [None]
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001118 data = self.untagged_responses.pop(name)
Tim Peters07e99cb2001-01-14 23:47:14 +00001119 if __debug__:
1120 if self.debug >= 5:
Piers Lauderf2d7d152002-02-22 01:15:17 +00001121 self._mesg('untagged_responses[%s] => %s' % (name, data))
Tim Peters07e99cb2001-01-14 23:47:14 +00001122 return typ, data
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001123
1124
Piers Lauderf2d7d152002-02-22 01:15:17 +00001125 if __debug__:
1126
1127 def _mesg(self, s, secs=None):
1128 if secs is None:
1129 secs = time.time()
1130 tm = time.strftime('%M:%S', time.localtime(secs))
1131 sys.stderr.write(' %s.%02d %s\n' % (tm, (secs*100)%100, s))
1132 sys.stderr.flush()
1133
1134 def _dump_ur(self, dict):
1135 # Dump untagged responses (in `dict').
1136 l = dict.items()
1137 if not l: return
1138 t = '\n\t\t'
1139 l = map(lambda x:'%s: "%s"' % (x[0], x[1][0] and '" "'.join(x[1]) or ''), l)
1140 self._mesg('untagged responses dump:%s%s' % (t, t.join(l)))
1141
1142 def _log(self, line):
1143 # Keep log of last `_cmd_log_len' interactions for debugging.
1144 self._cmd_log[self._cmd_log_idx] = (line, time.time())
1145 self._cmd_log_idx += 1
1146 if self._cmd_log_idx >= self._cmd_log_len:
1147 self._cmd_log_idx = 0
1148
1149 def print_log(self):
1150 self._mesg('last %d IMAP4 interactions:' % len(self._cmd_log))
1151 i, n = self._cmd_log_idx, self._cmd_log_len
1152 while n:
1153 try:
Guido van Rossum68468eb2003-02-27 20:14:51 +00001154 self._mesg(*self._cmd_log[i])
Piers Lauderf2d7d152002-02-22 01:15:17 +00001155 except:
1156 pass
1157 i += 1
1158 if i >= self._cmd_log_len:
1159 i = 0
1160 n -= 1
1161
1162
Antoine Pitrouf3b001f2010-11-12 18:49:16 +00001163if HAVE_SSL:
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001164
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001165 class IMAP4_SSL(IMAP4):
Piers Laudera4f83132002-03-08 01:53:24 +00001166
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001167 """IMAP4 client class over SSL connection
Piers Laudera4f83132002-03-08 01:53:24 +00001168
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001169 Instantiate with: IMAP4_SSL([host[, port[, keyfile[, certfile]]]])
Piers Laudera4f83132002-03-08 01:53:24 +00001170
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001171 host - host's name (default: localhost);
1172 port - port number (default: standard IMAP4 SSL port).
1173 keyfile - PEM formatted file that contains your private key (default: None);
1174 certfile - PEM formatted certificate chain file (default: None);
Piers Laudera4f83132002-03-08 01:53:24 +00001175
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001176 for more documentation see the docstring of the parent class IMAP4.
Piers Laudera4f83132002-03-08 01:53:24 +00001177 """
Piers Laudera4f83132002-03-08 01:53:24 +00001178
1179
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001180 def __init__(self, host = '', port = IMAP4_SSL_PORT, keyfile = None, certfile = None):
1181 self.keyfile = keyfile
1182 self.certfile = certfile
1183 IMAP4.__init__(self, host, port)
Piers Laudera4f83132002-03-08 01:53:24 +00001184
Christian Heimesfb5faf02008-11-05 19:39:50 +00001185 def _create_socket(self):
1186 sock = IMAP4._create_socket(self)
1187 return ssl.wrap_socket(sock, self.keyfile, self.certfile)
Piers Laudera4f83132002-03-08 01:53:24 +00001188
Christian Heimesfb5faf02008-11-05 19:39:50 +00001189 def open(self, host='', port=IMAP4_SSL_PORT):
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001190 """Setup connection to remote server on "host:port".
1191 (default: localhost:standard IMAP4 SSL port).
1192 This connection will be used by the routines:
1193 read, readline, send, shutdown.
1194 """
Christian Heimesfb5faf02008-11-05 19:39:50 +00001195 IMAP4.open(self, host, port)
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001196
1197 __all__.append("IMAP4_SSL")
Piers Laudera4f83132002-03-08 01:53:24 +00001198
1199
Piers Laudere0273de2002-11-22 05:53:04 +00001200class IMAP4_stream(IMAP4):
1201
1202 """IMAP4 client class over a stream
1203
1204 Instantiate with: IMAP4_stream(command)
1205
Christian Heimesfb5faf02008-11-05 19:39:50 +00001206 where "command" is a string that can be passed to subprocess.Popen()
Piers Laudere0273de2002-11-22 05:53:04 +00001207
1208 for more documentation see the docstring of the parent class IMAP4.
1209 """
1210
1211
1212 def __init__(self, command):
1213 self.command = command
1214 IMAP4.__init__(self)
1215
1216
1217 def open(self, host = None, port = None):
1218 """Setup a stream connection.
1219 This connection will be used by the routines:
1220 read, readline, send, shutdown.
1221 """
1222 self.host = None # For compatibility with parent class
1223 self.port = None
1224 self.sock = None
1225 self.file = None
Christian Heimesfb5faf02008-11-05 19:39:50 +00001226 self.process = subprocess.Popen(self.command,
1227 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1228 shell=True, close_fds=True)
1229 self.writefile = self.process.stdin
1230 self.readfile = self.process.stdout
Piers Laudere0273de2002-11-22 05:53:04 +00001231
1232 def read(self, size):
1233 """Read 'size' bytes from remote."""
1234 return self.readfile.read(size)
1235
1236
1237 def readline(self):
1238 """Read line from remote."""
1239 return self.readfile.readline()
1240
1241
1242 def send(self, data):
1243 """Send data to remote."""
1244 self.writefile.write(data)
1245 self.writefile.flush()
1246
1247
1248 def shutdown(self):
1249 """Close I/O established in "open"."""
1250 self.readfile.close()
1251 self.writefile.close()
Christian Heimesfb5faf02008-11-05 19:39:50 +00001252 self.process.wait()
Piers Laudere0273de2002-11-22 05:53:04 +00001253
1254
1255
Guido van Rossumeda960a1998-06-18 14:24:28 +00001256class _Authenticator:
1257
Tim Peters07e99cb2001-01-14 23:47:14 +00001258 """Private class to provide en/decoding
1259 for base64-based authentication conversation.
1260 """
Guido van Rossumeda960a1998-06-18 14:24:28 +00001261
Tim Peters07e99cb2001-01-14 23:47:14 +00001262 def __init__(self, mechinst):
1263 self.mech = mechinst # Callable object to provide/process data
Guido van Rossumeda960a1998-06-18 14:24:28 +00001264
Tim Peters07e99cb2001-01-14 23:47:14 +00001265 def process(self, data):
1266 ret = self.mech(self.decode(data))
1267 if ret is None:
1268 return '*' # Abort conversation
1269 return self.encode(ret)
Guido van Rossumeda960a1998-06-18 14:24:28 +00001270
Tim Peters07e99cb2001-01-14 23:47:14 +00001271 def encode(self, inp):
1272 #
1273 # Invoke binascii.b2a_base64 iteratively with
1274 # short even length buffers, strip the trailing
1275 # line feed from the result and append. "Even"
1276 # means a number that factors to both 6 and 8,
1277 # so when it gets to the end of the 8-bit input
1278 # there's no partial 6-bit output.
1279 #
1280 oup = ''
1281 while inp:
1282 if len(inp) > 48:
1283 t = inp[:48]
1284 inp = inp[48:]
1285 else:
1286 t = inp
1287 inp = ''
1288 e = binascii.b2a_base64(t)
1289 if e:
1290 oup = oup + e[:-1]
1291 return oup
1292
1293 def decode(self, inp):
1294 if not inp:
1295 return ''
1296 return binascii.a2b_base64(inp)
1297
Guido van Rossumeda960a1998-06-18 14:24:28 +00001298
1299
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001300Mon2num = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
Tim Peters07e99cb2001-01-14 23:47:14 +00001301 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001302
1303def Internaldate2tuple(resp):
Tim Peters07e99cb2001-01-14 23:47:14 +00001304 """Convert IMAP4 INTERNALDATE to UT.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001305
Tim Peters07e99cb2001-01-14 23:47:14 +00001306 Returns Python time module tuple.
1307 """
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001308
Tim Peters07e99cb2001-01-14 23:47:14 +00001309 mo = InternalDate.match(resp)
1310 if not mo:
1311 return None
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001312
Tim Peters07e99cb2001-01-14 23:47:14 +00001313 mon = Mon2num[mo.group('mon')]
1314 zonen = mo.group('zonen')
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001315
Jeremy Hyltonf5d3ea02001-02-22 13:24:27 +00001316 day = int(mo.group('day'))
1317 year = int(mo.group('year'))
1318 hour = int(mo.group('hour'))
1319 min = int(mo.group('min'))
1320 sec = int(mo.group('sec'))
1321 zoneh = int(mo.group('zoneh'))
1322 zonem = int(mo.group('zonem'))
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001323
Tim Peters07e99cb2001-01-14 23:47:14 +00001324 # INTERNALDATE timezone must be subtracted to get UT
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001325
Tim Peters07e99cb2001-01-14 23:47:14 +00001326 zone = (zoneh*60 + zonem)*60
1327 if zonen == '-':
1328 zone = -zone
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001329
Tim Peters07e99cb2001-01-14 23:47:14 +00001330 tt = (year, mon, day, hour, min, sec, -1, -1, -1)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001331
Tim Peters07e99cb2001-01-14 23:47:14 +00001332 utc = time.mktime(tt)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001333
Tim Peters07e99cb2001-01-14 23:47:14 +00001334 # Following is necessary because the time module has no 'mkgmtime'.
1335 # 'mktime' assumes arg in local timezone, so adds timezone/altzone.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001336
Tim Peters07e99cb2001-01-14 23:47:14 +00001337 lt = time.localtime(utc)
1338 if time.daylight and lt[-1]:
1339 zone = zone + time.altzone
1340 else:
1341 zone = zone + time.timezone
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001342
Tim Peters07e99cb2001-01-14 23:47:14 +00001343 return time.localtime(utc - zone)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001344
1345
1346
1347def Int2AP(num):
1348
Tim Peters07e99cb2001-01-14 23:47:14 +00001349 """Convert integer to A-P string representation."""
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001350
Christian Heimesfb5faf02008-11-05 19:39:50 +00001351 val = b''; AP = b'ABCDEFGHIJKLMNOP'
Tim Peters07e99cb2001-01-14 23:47:14 +00001352 num = int(abs(num))
1353 while num:
1354 num, mod = divmod(num, 16)
Christian Heimesfb5faf02008-11-05 19:39:50 +00001355 val = AP[mod:mod+1] + val
Tim Peters07e99cb2001-01-14 23:47:14 +00001356 return val
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001357
1358
1359
1360def ParseFlags(resp):
1361
Tim Peters07e99cb2001-01-14 23:47:14 +00001362 """Convert IMAP4 flags response to python tuple."""
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001363
Tim Peters07e99cb2001-01-14 23:47:14 +00001364 mo = Flags.match(resp)
1365 if not mo:
1366 return ()
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001367
Eric S. Raymond25a0cbc2001-02-09 06:50:21 +00001368 return tuple(mo.group('flags').split())
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001369
1370
1371def Time2Internaldate(date_time):
1372
Tim Peters07e99cb2001-01-14 23:47:14 +00001373 """Convert 'date_time' to IMAP4 INTERNALDATE representation.
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001374
Tim Peters07e99cb2001-01-14 23:47:14 +00001375 Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'
1376 """
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001377
Fred Drakedb519202002-01-05 17:17:09 +00001378 if isinstance(date_time, (int, float)):
Tim Peters07e99cb2001-01-14 23:47:14 +00001379 tt = time.localtime(date_time)
Fred Drakedb519202002-01-05 17:17:09 +00001380 elif isinstance(date_time, (tuple, time.struct_time)):
Tim Peters07e99cb2001-01-14 23:47:14 +00001381 tt = date_time
Piers Lauder3fca2912002-06-17 07:07:20 +00001382 elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'):
Tim Peters07e99cb2001-01-14 23:47:14 +00001383 return date_time # Assume in correct format
Fred Drakedb519202002-01-05 17:17:09 +00001384 else:
1385 raise ValueError("date_time not of a known type")
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001386
Tim Peters07e99cb2001-01-14 23:47:14 +00001387 dt = time.strftime("%d-%b-%Y %H:%M:%S", tt)
1388 if dt[0] == '0':
1389 dt = ' ' + dt[1:]
1390 if time.daylight and tt[-1]:
1391 zone = -time.altzone
1392 else:
1393 zone = -time.timezone
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +00001394 return '"' + dt + " %+03d%02d" % divmod(zone//60, 60) + '"'
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001395
1396
1397
Guido van Rossum8c062211999-12-13 23:27:45 +00001398if __name__ == '__main__':
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001399
Piers Laudere0273de2002-11-22 05:53:04 +00001400 # To test: invoke either as 'python imaplib.py [IMAP4_server_hostname]'
1401 # or 'python imaplib.py -s "rsh IMAP4_server_hostname exec /etc/rimapd"'
1402 # to test the IMAP4_stream class
1403
Guido van Rossuma79bbac2001-08-13 15:34:41 +00001404 import getopt, getpass
Guido van Rossumd6596931998-05-29 18:08:48 +00001405
Tim Peters07e99cb2001-01-14 23:47:14 +00001406 try:
Piers Laudere0273de2002-11-22 05:53:04 +00001407 optlist, args = getopt.getopt(sys.argv[1:], 'd:s:')
Guido van Rossumb940e112007-01-10 16:19:56 +00001408 except getopt.error as val:
Piers Laudere0273de2002-11-22 05:53:04 +00001409 optlist, args = (), ()
Guido van Rossum66d45132000-03-28 20:20:53 +00001410
Piers Laudere0273de2002-11-22 05:53:04 +00001411 stream_command = None
Tim Peters07e99cb2001-01-14 23:47:14 +00001412 for opt,val in optlist:
1413 if opt == '-d':
1414 Debug = int(val)
Piers Laudere0273de2002-11-22 05:53:04 +00001415 elif opt == '-s':
1416 stream_command = val
1417 if not args: args = (stream_command,)
Guido van Rossum66d45132000-03-28 20:20:53 +00001418
Tim Peters07e99cb2001-01-14 23:47:14 +00001419 if not args: args = ('',)
Guido van Rossum66d45132000-03-28 20:20:53 +00001420
Tim Peters07e99cb2001-01-14 23:47:14 +00001421 host = args[0]
Guido van Rossumb1f08121998-06-25 02:22:16 +00001422
Tim Peters07e99cb2001-01-14 23:47:14 +00001423 USER = getpass.getuser()
Piers Lauder15e5d532001-07-20 10:52:06 +00001424 PASSWD = getpass.getpass("IMAP password for %s on %s: " % (USER, host or "localhost"))
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001425
Piers Lauder47404ff2003-04-29 23:40:59 +00001426 test_mesg = 'From: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)sdata...%(lf)s' % {'user':USER, 'lf':'\n'}
Tim Peters07e99cb2001-01-14 23:47:14 +00001427 test_seq1 = (
1428 ('login', (USER, PASSWD)),
1429 ('create', ('/tmp/xxx 1',)),
1430 ('rename', ('/tmp/xxx 1', '/tmp/yyy')),
1431 ('CREATE', ('/tmp/yyz 2',)),
1432 ('append', ('/tmp/yyz 2', None, None, test_mesg)),
1433 ('list', ('/tmp', 'yy*')),
1434 ('select', ('/tmp/yyz 2',)),
1435 ('search', (None, 'SUBJECT', 'test')),
Piers Lauderf2d7d152002-02-22 01:15:17 +00001436 ('fetch', ('1', '(FLAGS INTERNALDATE RFC822)')),
Tim Peters07e99cb2001-01-14 23:47:14 +00001437 ('store', ('1', 'FLAGS', '(\Deleted)')),
Piers Lauder15e5d532001-07-20 10:52:06 +00001438 ('namespace', ()),
Tim Peters07e99cb2001-01-14 23:47:14 +00001439 ('expunge', ()),
1440 ('recent', ()),
1441 ('close', ()),
1442 )
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001443
Tim Peters07e99cb2001-01-14 23:47:14 +00001444 test_seq2 = (
1445 ('select', ()),
1446 ('response',('UIDVALIDITY',)),
1447 ('uid', ('SEARCH', 'ALL')),
1448 ('response', ('EXISTS',)),
1449 ('append', (None, None, None, test_mesg)),
1450 ('recent', ()),
1451 ('logout', ()),
1452 )
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001453
Tim Peters07e99cb2001-01-14 23:47:14 +00001454 def run(cmd, args):
Piers Lauderf2d7d152002-02-22 01:15:17 +00001455 M._mesg('%s %s' % (cmd, args))
Guido van Rossum68468eb2003-02-27 20:14:51 +00001456 typ, dat = getattr(M, cmd)(*args)
Piers Lauderf2d7d152002-02-22 01:15:17 +00001457 M._mesg('%s => %s %s' % (cmd, typ, dat))
Piers Laudere0273de2002-11-22 05:53:04 +00001458 if typ == 'NO': raise dat[0]
Tim Peters07e99cb2001-01-14 23:47:14 +00001459 return dat
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001460
Tim Peters07e99cb2001-01-14 23:47:14 +00001461 try:
Piers Laudere0273de2002-11-22 05:53:04 +00001462 if stream_command:
1463 M = IMAP4_stream(stream_command)
1464 else:
1465 M = IMAP4(host)
1466 if M.state == 'AUTH':
Tim Peters77c06fb2002-11-24 02:35:35 +00001467 test_seq1 = test_seq1[1:] # Login not needed
Piers Lauderf2d7d152002-02-22 01:15:17 +00001468 M._mesg('PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION)
Walter Dörwald70a6b492004-02-12 17:35:32 +00001469 M._mesg('CAPABILITIES = %r' % (M.capabilities,))
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001470
Tim Peters07e99cb2001-01-14 23:47:14 +00001471 for cmd,args in test_seq1:
1472 run(cmd, args)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001473
Tim Peters07e99cb2001-01-14 23:47:14 +00001474 for ml in run('list', ('/tmp/', 'yy%')):
1475 mo = re.match(r'.*"([^"]+)"$', ml)
1476 if mo: path = mo.group(1)
Eric S. Raymond25a0cbc2001-02-09 06:50:21 +00001477 else: path = ml.split()[-1]
Tim Peters07e99cb2001-01-14 23:47:14 +00001478 run('delete', (path,))
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001479
Tim Peters07e99cb2001-01-14 23:47:14 +00001480 for cmd,args in test_seq2:
1481 dat = run(cmd, args)
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001482
Tim Peters07e99cb2001-01-14 23:47:14 +00001483 if (cmd,args) != ('uid', ('SEARCH', 'ALL')):
1484 continue
Guido van Rossum38d8f4e1998-04-11 01:22:34 +00001485
Eric S. Raymond25a0cbc2001-02-09 06:50:21 +00001486 uid = dat[-1].split()
Tim Peters07e99cb2001-01-14 23:47:14 +00001487 if not uid: continue
1488 run('uid', ('FETCH', '%s' % uid[-1],
1489 '(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)'))
Guido van Rossum66d45132000-03-28 20:20:53 +00001490
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001491 print('\nAll tests OK.')
Guido van Rossum66d45132000-03-28 20:20:53 +00001492
Tim Peters07e99cb2001-01-14 23:47:14 +00001493 except:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001494 print('\nTests failed.')
Guido van Rossum66d45132000-03-28 20:20:53 +00001495
Tim Peters07e99cb2001-01-14 23:47:14 +00001496 if not Debug:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001497 print('''
Guido van Rossum66d45132000-03-28 20:20:53 +00001498If you would like to see debugging output,
1499try: %s -d5
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001500''' % sys.argv[0])
Guido van Rossum66d45132000-03-28 20:20:53 +00001501
Tim Peters07e99cb2001-01-14 23:47:14 +00001502 raise