blob: e6754ef320031b310ad40fefbdbee8767ae323fc [file] [log] [blame]
Guido van Rossumc2c07fa1998-04-09 13:51:46 +00001"""IMAP4 client.
2
3Based on RFC 2060.
4
5Author: Piers Lauder <piers@cs.su.oz.au> December 1997.
6
7Public class: IMAP4
8Public variable: Debug
9Public functions: Internaldate2tuple
10 Int2AP
11 ParseFlags
12 Time2Internaldate
13"""
14
15import os, re, socket, string, time
16
17# Globals
18
19CRLF = '\r\n'
20Debug = 0
21IMAP4_PORT = 143
22
23# Commands
24
25Commands = {
26 # name valid states
27 'APPEND': ('AUTH', 'SELECTED'),
28 'AUTHENTICATE': ('NONAUTH',),
29 'CAPABILITY': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
30 'CHECK': ('SELECTED',),
31 'CLOSE': ('SELECTED',),
32 'COPY': ('SELECTED',),
33 'CREATE': ('AUTH', 'SELECTED'),
34 'DELETE': ('AUTH', 'SELECTED'),
35 'EXAMINE': ('AUTH', 'SELECTED'),
36 'EXPUNGE': ('SELECTED',),
37 'FETCH': ('SELECTED',),
38 'LIST': ('AUTH', 'SELECTED'),
39 'LOGIN': ('NONAUTH',),
40 'LOGOUT': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
41 'LSUB': ('AUTH', 'SELECTED'),
42 'NOOP': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
43 'RENAME': ('AUTH', 'SELECTED'),
44 'SEARCH': ('SELECTED',),
45 'SELECT': ('AUTH', 'SELECTED'),
46 'STATUS': ('AUTH', 'SELECTED'),
47 'STORE': ('SELECTED',),
48 'SUBSCRIBE': ('AUTH', 'SELECTED'),
49 'UID': ('SELECTED',),
50 'UNSUBSCRIBE': ('AUTH', 'SELECTED'),
51 }
52
53# Patterns to match server responses
54
55Continuation = re.compile(r'\+ (?P<data>.*)')
56Flags = re.compile(r'.*FLAGS \((?P<flags>[^\)]*)\)')
57InternalDate = re.compile(r'.*INTERNALDATE "'
58 r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-(?P<year>[0-9][0-9][0-9][0-9])'
59 r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
60 r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
61 r'"')
62Literal = re.compile(r'(?P<data>.*) {(?P<size>\d+)}$')
63Response_code = re.compile(r'\[(?P<type>[A-Z-]+)( (?P<data>[^\]]*))?\]')
64Untagged_response = re.compile(r'\* (?P<type>[A-Z-]+) (?P<data>.*)')
65Untagged_status = re.compile(r'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?')
66
67
68
69class IMAP4:
70
71 """IMAP4 client class.
72
73 Instantiate with: IMAP4([host[, port]])
74
75 host - host's name (default: localhost);
76 port - port number (default: standard IMAP4 port).
77
78 All IMAP4rev1 commands are supported by methods of the same
79 name (in lower-case). Each command returns a tuple: (type, [data, ...])
80 where 'type' is usually 'OK' or 'NO', and 'data' is either the
81 text from the tagged response, or untagged results from command.
82
83 Errors raise the exception class <instance>.error("<reason>").
84 IMAP4 server errors raise <instance>.abort("<reason>"),
85 which is a sub-class of 'error'.
86 """
87
88 class error(Exception): pass # Logical errors - debug required
89 class abort(error): pass # Service errors - close and retry
90 COUNT = [0] # Count instantiations
91
92
93 def __init__(self, host = '', port = IMAP4_PORT):
94 self.host = host
95 self.port = port
96 self.debug = Debug
97 self.state = 'LOGOUT'
98 self.tagged_commands = {} # Tagged commands awaiting response
99 self.untagged_responses = {} # {typ: [data, ...], ...}
100 self.continuation_response = '' # Last continuation response
101 self.tagnum = 0
102
103 # Open socket to server.
104
105 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
106 self.sock.connect(self.host, self.port)
107 self.file = self.sock.makefile('r')
108
109 # Create unique tag for this session,
110 # and compile tagged response matcher.
111
112 self.COUNT[0] = self.COUNT[0] + 1
113 self.tagpre = Int2AP((os.getpid()<<8)+self.COUNT[0])
114 self.tagre = re.compile(r'(?P<tag>'
115 + self.tagpre
116 + r'\d+) (?P<type>[A-Z]+) (?P<data>.*)')
117
118 # Get server welcome message,
119 # request and store CAPABILITY response.
120
121 if __debug__ and self.debug >= 1:
122 print '\tnew IMAP4 connection, tag=%s' % self.tagpre
123
124 self.welcome = self._get_response()
125 if self.untagged_responses.has_key('PREAUTH'):
126 self.state = 'AUTH'
127 elif self.untagged_responses.has_key('OK'):
128 self.state = 'NONAUTH'
129# elif self.untagged_responses.has_key('BYE'):
130 else:
131 raise self.error(self.welcome)
132
133 cap = 'CAPABILITY'
134 self._simple_command(cap)
135 if not self.untagged_responses.has_key(cap):
136 raise self.error('no CAPABILITY response from server')
137 self.capabilities = tuple(string.split(self.untagged_responses[cap][-1]))
138 if not 'IMAP4REV1' in self.capabilities:
139 raise self.error('server not IMAP4REV1 compliant')
140
141 if __debug__ and self.debug >= 3:
142 print '\tCAPABILITIES: %s' % `self.capabilities`
143
144
145 def __getattr__(self, attr):
146 """Allow UPPERCASE variants of all following IMAP4 commands."""
147 if Commands.has_key(attr):
148 return eval("self.%s" % string.lower(attr))
149 raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
150
151
152 # Public methods
153
154
155 def append(self, mailbox, flags, date_time, message):
156 """Append message to named mailbox.
157
158 (typ, [data]) = <instance>.append(mailbox, flags, date_time, message)
159 """
160 name = 'APPEND'
161 if flags:
162 flags = '(%s)' % flags
163 else:
164 flags = None
165 if date_time:
166 date_time = Time2Internaldate(date_time)
167 else:
168 date_time = None
169 tag = self._command(name, mailbox, flags, date_time, message)
170 return self._command_complete(name, tag)
171
172
173 def authenticate(self, func):
174 """Authenticate command - requires response processing.
175
176 UNIMPLEMENTED
177 """
178 raise self.error('UNIMPLEMENTED')
179
180
181 def check(self):
182 """Checkpoint mailbox on server.
183
184 (typ, [data]) = <instance>.check()
185 """
186 return self._simple_command('CHECK')
187
188
189 def close(self):
190 """Close currently selected mailbox.
191 Deleted messages are removed from writable mailbox.
192 This is the recommended command before 'LOGOUT'.
193
194 (typ, [data]) = <instance>.close()
195 """
196 try:
197 try: typ, dat = self._simple_command('CLOSE')
198 except EOFError: typ, dat = None, [None]
199 finally:
200 self.state = 'AUTH'
201 return typ, dat
202
203
204 def copy(self, message_set, new_mailbox):
205 """Copy 'message_set' messages onto end of 'new_mailbox'.
206
207 (typ, [data]) = <instance>.copy(message_set, new_mailbox)
208 """
209 return self._simple_command('COPY', message_set, new_mailbox)
210
211
212 def create(self, mailbox):
213 """Create new mailbox.
214
215 (typ, [data]) = <instance>.create(mailbox)
216 """
217 return self._simple_command('CREATE', mailbox)
218
219
220 def delete(self, mailbox):
221 """Delete old mailbox.
222
223 (typ, [data]) = <instance>.delete(mailbox)
224 """
225 return self._simple_command('DELETE', mailbox)
226
227
228 def expunge(self):
229 """Permanently remove deleted items from selected mailbox.
230 Generates 'EXPUNGE' response for each deleted message.
231
232 (typ, [data]) = <instance>.expunge()
233
234 'data' is list of 'EXPUNGE'd message numbers in order received.
235 """
236 name = 'EXPUNGE'
237 typ, dat = self._simple_command(name)
238 return self._untagged_response(typ, name)
239
240
241 def fetch(self, message_set, message_parts):
242 """Fetch (parts of) messages.
243
244 (typ, [data, ...]) = <instance>.fetch(message_set, message_parts)
245
246 'data' are tuples of message part envelope and data.
247 """
248 name = 'FETCH'
249 typ, dat = self._simple_command(name, message_set, message_parts)
250 return self._untagged_response(typ, name)
251
252
253 def list(self, directory='""', pattern='*'):
254 """List mailbox names in directory matching pattern.
255
256 (typ, [data]) = <instance>.list(directory='""', pattern='*')
257
258 'data' is list of LIST responses.
259 """
260 name = 'LIST'
261 typ, dat = self._simple_command(name, directory, pattern)
262 return self._untagged_response(typ, name)
263
264
265 def login(self, user, password):
266 """Identify client using plaintext password.
267
268 (typ, [data]) = <instance>.list(user, password)
269 """
270 if not 'AUTH=LOGIN' in self.capabilities:
271 raise self.error("server doesn't allow LOGIN authorisation")
272 typ, dat = self._simple_command('LOGIN', user, password)
273 if typ != 'OK':
274 raise self.error(dat)
275 self.state = 'AUTH'
276 return typ, dat
277
278
279 def logout(self):
280 """Shutdown connection to server.
281
282 (typ, [data]) = <instance>.logout()
283
284 Returns server 'BYE' response.
285 """
286 self.state = 'LOGOUT'
287 try: typ, dat = self._simple_command('LOGOUT')
288 except EOFError: typ, dat = None, [None]
289 self.file.close()
290 self.sock.close()
291 if self.untagged_responses.has_key('BYE'):
292 return 'BYE', self.untagged_responses['BYE']
293 return typ, dat
294
295
296 def lsub(self, directory='""', pattern='*'):
297 """List 'subscribed' mailbox names in directory matching pattern.
298
299 (typ, [data, ...]) = <instance>.lsub(directory='""', pattern='*')
300
301 'data' are tuples of message part envelope and data.
302 """
303 name = 'LSUB'
304 typ, dat = self._simple_command(name, directory, pattern)
305 return self._untagged_response(typ, name)
306
307
308 def recent(self):
309 """Prompt server for an update.
310
311 (typ, [data]) = <instance>.recent()
312
313 'data' is None if no new messages,
314 else value of RECENT response.
315 """
316 name = 'RECENT'
317 typ, dat = self._untagged_response('OK', name)
318 if dat[-1]:
319 return typ, dat
320 typ, dat = self._simple_command('NOOP')
321 return self._untagged_response(typ, name)
322
323
324 def rename(self, oldmailbox, newmailbox):
325 """Rename old mailbox name to new.
326
327 (typ, data) = <instance>.rename(oldmailbox, newmailbox)
328 """
329 return self._simple_command('RENAME', oldmailbox, newmailbox)
330
331
332 def response(self, code):
333 """Return data for response 'code' if received, or None.
334
335 (code, [data]) = <instance>.response(code)
336 """
337 return code, self.untagged_responses.get(code, [None])
338
339
340 def search(self, charset, criteria):
341 """Search mailbox for matching messages.
342
343 (typ, [data]) = <instance>.search(charset, criteria)
344
345 'data' is space separated list of matching message numbers.
346 """
347 name = 'SEARCH'
348 if charset:
349 charset = 'CHARSET ' + charset
350 typ, dat = self._simple_command(name, charset, criteria)
351 return self._untagged_response(typ, name)
352
353
354 def select(self, mailbox='INBOX', readonly=None):
355 """Select a mailbox.
356
357 (typ, [data]) = <instance>.select(mailbox='INBOX', readonly=None)
358
359 'data' is count of messages in mailbox ('EXISTS' response).
360 """
361 # Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY')
362 # Remove immediately interesting responses
363 for r in ('EXISTS', 'READ-WRITE'):
364 if self.untagged_responses.has_key(r):
365 del self.untagged_responses[r]
366 if readonly:
367 name = 'EXAMINE'
368 else:
369 name = 'SELECT'
370 typ, dat = self._simple_command(name, mailbox)
371 if typ == 'OK':
372 self.state = 'SELECTED'
373 elif typ == 'NO':
374 self.state = 'AUTH'
375 if not readonly and not self.untagged_responses.has_key('READ-WRITE'):
376 raise self.error('%s is not writable' % mailbox)
377 return typ, self.untagged_responses.get('EXISTS', [None])
378
379
380 def status(self, mailbox, names):
381 """Request named status conditions for mailbox.
382
383 (typ, [data]) = <instance>.status(mailbox, names)
384 """
385 name = 'STATUS'
386 typ, dat = self._simple_command(name, mailbox, names)
387 return self._untagged_response(typ, name)
388
389
390 def store(self, message_set, command, flag_list):
391 """Alters flag dispositions for messages in mailbox.
392
393 (typ, [data]) = <instance>.store(message_set, command, flag_list)
394 """
395 command = '%s %s' % (command, flag_list)
396 typ, dat = self._simple_command('STORE', message_set, command)
397 return self._untagged_response(typ, 'FETCH')
398
399
400 def subscribe(self, mailbox):
401 """Subscribe to new mailbox.
402
403 (typ, [data]) = <instance>.subscribe(mailbox)
404 """
405 return self._simple_command('SUBSCRIBE', mailbox)
406
407
408 def uid(self, command, args):
409 """Execute "command args" with messages identified by UID,
410 rather than message number.
411
412 (typ, [data]) = <instance>.uid(command, args)
413
414 Returns response appropriate to 'command'.
415 """
416 name = 'UID'
417 typ, dat = self._simple_command('UID', command, args)
418 if command == 'SEARCH':
419 name = 'SEARCH'
420 else:
421 name = 'FETCH'
422 typ, dat2 = self._untagged_response(typ, name)
423 if dat2[-1]: dat = dat2
424 return typ, dat
425
426
427 def unsubscribe(self, mailbox):
428 """Unsubscribe from old mailbox.
429
430 (typ, [data]) = <instance>.unsubscribe(mailbox)
431 """
432 return self._simple_command('UNSUBSCRIBE', mailbox)
433
434
435 def xatom(self, name, arg1=None, arg2=None):
436 """Allow simple extension commands
437 notified by server in CAPABILITY response.
438
439 (typ, [data]) = <instance>.xatom(name, arg1=None, arg2=None)
440 """
441 if name[0] != 'X' or not name in self.capabilities:
442 raise self.error('unknown extension command: %s' % name)
443 return self._simple_command(name, arg1, arg2)
444
445
446
447 # Private methods
448
449
450 def _append_untagged(self, typ, dat):
451
452 if self.untagged_responses.has_key(typ):
453 self.untagged_responses[typ].append(dat)
454 else:
455 self.untagged_responses[typ] = [dat]
456
457 if __debug__ and self.debug >= 5:
458 print '\tuntagged_responses[%s] += %.20s..' % (typ, `dat`)
459
460
461 def _command(self, name, dat1=None, dat2=None, dat3=None, literal=None):
462
463 if self.state not in Commands[name]:
464 raise self.error(
465 'command %s illegal in state %s' % (name, self.state))
466
467 tag = self._new_tag()
468 data = '%s %s' % (tag, name)
469 for d in (dat1, dat2, dat3):
470 if d is not None: data = '%s %s' % (data, d)
471 if literal is not None:
472 data = '%s {%s}' % (data, len(literal))
473
474 try:
475 self.sock.send('%s%s' % (data, CRLF))
476 except socket.error, val:
477 raise self.abort('socket error: %s' % val)
478
479 if __debug__ and self.debug >= 4:
480 print '\t> %s' % data
481
482 if literal is None:
483 return tag
484
485 # Wait for continuation response
486
487 while self._get_response():
488 if self.tagged_commands[tag]: # BAD/NO?
489 return tag
490
491 # Send literal
492
493 if __debug__ and self.debug >= 4:
494 print '\twrite literal size %s' % len(literal)
495
496 try:
497 self.sock.send(literal)
498 self.sock.send(CRLF)
499 except socket.error, val:
500 raise self.abort('socket error: %s' % val)
501
502 return tag
503
504
505 def _command_complete(self, name, tag):
506 try:
507 typ, data = self._get_tagged_response(tag)
508 except self.abort, val:
509 raise self.abort('command: %s => %s' % (name, val))
510 except self.error, val:
511 raise self.error('command: %s => %s' % (name, val))
512 if self.untagged_responses.has_key('BYE') and name != 'LOGOUT':
513 raise self.abort(self.untagged_responses['BYE'][-1])
514 if typ == 'BAD':
515 raise self.error('%s command error: %s %s' % (name, typ, data))
516 return typ, data
517
518
519 def _get_response(self):
520
521 # Read response and store.
522 #
523 # Returns None for continuation responses,
524 # otherwise first response line received
525
526 # Protocol mandates all lines terminated by CRLF.
527
528 resp = self._get_line()[:-2]
529
530 # Command completion response?
531
532 if self._match(self.tagre, resp):
533 tag = self.mo.group('tag')
534 if not self.tagged_commands.has_key(tag):
535 raise self.abort('unexpected tagged response: %s' % resp)
536
537 typ = self.mo.group('type')
538 dat = self.mo.group('data')
539 self.tagged_commands[tag] = (typ, [dat])
540 else:
541 dat2 = None
542
543 # '*' (untagged) responses?
544
545 if not self._match(Untagged_response, resp):
546 if self._match(Untagged_status, resp):
547 dat2 = self.mo.group('data2')
548
549 if self.mo is None:
550 # Only other possibility is '+' (continuation) rsponse...
551
552 if self._match(Continuation, resp):
553 self.continuation_response = self.mo.group('data')
554 return None # NB: indicates continuation
555
556 raise self.abort('unexpected response: %s' % resp)
557
558 typ = self.mo.group('type')
559 dat = self.mo.group('data')
560 if dat2: dat = dat + ' ' + dat2
561
562 # Is there a literal to come?
563
564 while self._match(Literal, dat):
565
566 # Read literal direct from connection.
567
568 size = string.atoi(self.mo.group('size'))
569 if __debug__ and self.debug >= 4:
570 print '\tread literal size %s' % size
571 data = self.file.read(size)
572
573 # Store response with literal as tuple
574
575 self._append_untagged(typ, (dat, data))
576
577 # Read trailer - possibly containing another literal
578
579 dat = self._get_line()[:-2]
580
581 self._append_untagged(typ, dat)
582
583 # Bracketed response information?
584
585 if typ in ('OK', 'NO', 'BAD') and self._match(Response_code, dat):
586 self._append_untagged(self.mo.group('type'), self.mo.group('data'))
587
588 return resp
589
590
591 def _get_tagged_response(self, tag):
592
593 while 1:
594 result = self.tagged_commands[tag]
595 if result is not None:
596 del self.tagged_commands[tag]
597 return result
598 self._get_response()
599
600
601 def _get_line(self):
602
603 line = self.file.readline()
604 if not line:
605 raise EOFError
606
607 # Protocol mandates all lines terminated by CRLF
608
609 if __debug__ and self.debug >= 4:
610 print '\t< %s' % line[:-2]
611 return line
612
613
614 def _match(self, cre, s):
615
616 # Run compiled regular expression match method on 's'.
617 # Save result, return success.
618
619 self.mo = cre.match(s)
620 if __debug__ and self.mo is not None and self.debug >= 5:
621 print "\tmatched r'%s' => %s" % (cre.pattern, `self.mo.groups()`)
622 return self.mo is not None
623
624
625 def _new_tag(self):
626
627 tag = '%s%s' % (self.tagpre, self.tagnum)
628 self.tagnum = self.tagnum + 1
629 self.tagged_commands[tag] = None
630 return tag
631
632
633 def _simple_command(self, name, dat1=None, dat2=None):
634
635 return self._command_complete(name, self._command(name, dat1, dat2))
636
637
638 def _untagged_response(self, typ, name):
639
640 if not self.untagged_responses.has_key(name):
641 return typ, [None]
642 data = self.untagged_responses[name]
643 del self.untagged_responses[name]
644 return typ, data
645
646
647
648Mon2num = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
649 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
650
651def Internaldate2tuple(resp):
652
653 """
654 Convert IMAP4 INTERNALDATE to UT.
655
656 Returns Python time module tuple.
657 """
658
659 mo = InternalDate.match(resp)
660 if not mo:
661 return None
662
663 mon = Mon2num[mo.group('mon')]
664 zonen = mo.group('zonen')
665
666 for name in ('day', 'year', 'hour', 'min', 'sec', 'zoneh', 'zonem'):
667 exec "%s = string.atoi(mo.group('%s'))" % (name, name)
668
669 # INTERNALDATE timezone must be subtracted to get UT
670
671 zone = (zoneh*60 + zonem)*60
672 if zonen == '-':
673 zone = -zone
674
675 tt = (year, mon, day, hour, min, sec, -1, -1, -1)
676
677 utc = time.mktime(tt)
678
679 # Following is necessary because the time module has no 'mkgmtime'.
680 # 'mktime' assumes arg in local timezone, so adds timezone/altzone.
681
682 lt = time.localtime(utc)
683 if time.daylight and lt[-1]:
684 zone = zone + time.altzone
685 else:
686 zone = zone + time.timezone
687
688 return time.localtime(utc - zone)
689
690
691
692def Int2AP(num):
693
694 """Convert integer to A-P string representation. """
695
696 val = ''; AP = 'ABCDEFGHIJKLMNOP'
697 while num:
698 num, mod = divmod(num, 16)
699 val = AP[mod] + val
700 return val
701
702
703
704def ParseFlags(resp):
705
706 """Convert IMAP4 flags response to python tuple. """
707
708 mo = Flags.match(resp)
709 if not mo:
710 return ()
711
712 return tuple(string.split(mo.group('flags')))
713
714
715def Time2Internaldate(date_time):
716
717 """Convert 'date_time' to IMAP4 INTERNALDATE representation.
718
719 Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'
720 """
721
722 dttype = type(date_time)
723 if dttype is type(1):
724 tt = time.localtime(date_time)
725 elif dttype is type(()):
726 tt = date_time
727 elif dttype is type(""):
728 return date_time # Assume in correct format
729 else: raise ValueError
730
731 dt = time.strftime("%d-%b-%Y %H:%M:%S", tt)
732 if dt[0] == '0':
733 dt = ' ' + dt[1:]
734 if time.daylight and tt[-1]:
735 zone = -time.altzone
736 else:
737 zone = -time.timezone
738 return '"' + dt + " %+02d%02d" % divmod(zone/60, 60) + '"'
739
740
741
742if __debug__ and __name__ == '__main__':
743
744 import getpass
745 USER = getpass.getuser()
746 PASSWD = getpass.getpass()
747
748 test_seq1 = (
749 ('login', (USER, PASSWD)),
750 ('create', ('/tmp/xxx',)),
751 ('rename', ('/tmp/xxx', '/tmp/yyy')),
752 ('CREATE', ('/tmp/yyz',)),
753 ('append', ('/tmp/yyz', None, None, 'From: anon@x.y.z\n\ndata...')),
754 ('select', ('/tmp/yyz',)),
755 ('recent', ()),
756 ('uid', ('SEARCH', 'ALL')),
757 ('fetch', ('1', '(INTERNALDATE RFC822)')),
758 ('store', ('1', 'FLAGS', '(\Deleted)')),
759 ('expunge', ()),
760 ('close', ()),
761 )
762
763 test_seq2 = (
764 ('select', ()),
765 ('response',('UIDVALIDITY',)),
766 ('uid', ('SEARCH', 'ALL')),
767 ('recent', ()),
768 ('response', ('EXISTS',)),
769 ('logout', ()),
770 )
771
772 def run(cmd, args):
773 typ, dat = apply(eval('M.%s' % cmd), args)
774 print ' %s %s\n => %s %s' % (cmd, args, typ, dat)
775 return dat
776
777 Debug = 4
778 M = IMAP4()
779
780 for cmd,args in test_seq1:
781 run(cmd, args)
782
783 for ml in M.list('/tmp/', 'yy%')[1]:
784 path = string.split(ml)[-1]
785 print '%s %s' % M.delete(path)
786
787 for cmd,args in test_seq2:
788 dat = run(cmd, args)
789
790 if (cmd,args) == ('uid', ('SEARCH', 'ALL')):
791 uid = string.split(dat[0])[-1]
792 run('uid', ('FETCH', '%s (FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822)' % uid))