forked from d7415/merlin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
imaplib2.py
2481 lines (1858 loc) · 84.5 KB
/
imaplib2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""Threaded IMAP4 client.
Based on RFC 3501 and original imaplib module.
Public classes: IMAP4
IMAP4_SSL
IMAP4_stream
Public functions: Internaldate2Time
ParseFlags
Time2Internaldate
"""
__all__ = ("IMAP4", "IMAP4_SSL", "IMAP4_stream",
"Internaldate2Time", "ParseFlags", "Time2Internaldate")
__version__ = "2.33"
__release__ = "2"
__revision__ = "33"
__credits__ = """
Authentication code contributed by Donn Cave <[email protected]> June 1998.
String method conversion by ESR, February 2001.
GET/SETACL contributed by Anthony Baxter <[email protected]> April 2001.
IMAP4_SSL contributed by Tino Lange <[email protected]> March 2002.
GET/SETQUOTA contributed by Andreas Zeidler <[email protected]> June 2002.
PROXYAUTH contributed by Rick Holbert <[email protected]> November 2002.
IDLE via threads suggested by Philippe Normand <[email protected]> January 2005.
GET/SETANNOTATION contributed by Tomas Lindroos <[email protected]> June 2005.
COMPRESS/DEFLATE contributed by Bron Gondwana <[email protected]> May 2009.
STARTTLS from Jython's imaplib by Alan Kennedy.
ID contributed by Dave Baggett <[email protected]> November 2009.
Improved untagged responses handling suggested by Dave Baggett <[email protected]> November 2009.
Improved thread naming, and 0 read detection contributed by Grant Edwards <[email protected]> June 2010.
Improved timeout handling contributed by Ivan Vovnenko <[email protected]> October 2010.
Timeout handling further improved by Ethan Glasser-Camp <[email protected]> December 2010.
Time2Internaldate() patch to match RFC2060 specification of English month names from bugs.python.org/issue11024 March 2011.
starttls() bug fixed with the help of Sebastian Spaeth <[email protected]> April 2011.
Threads now set the "daemon" flag (suggested by offlineimap-project) April 2011.
Single quoting introduced with the help of Vladimir Marek <[email protected]> August 2011."""
__author__ = "Piers Lauder <[email protected]>"
__URL__ = "http://imaplib2.sourceforge.net"
__license__ = "Python License"
import binascii, errno, os, Queue, random, re, select, socket, sys, time, threading, zlib
select_module = select
# Globals
CRLF = '\r\n'
Debug = None # Backward compatibility
IMAP4_PORT = 143
IMAP4_SSL_PORT = 993
IDLE_TIMEOUT_RESPONSE = '* IDLE TIMEOUT\r\n'
IDLE_TIMEOUT = 60*29 # Don't stay in IDLE state longer
READ_POLL_TIMEOUT = 30 # Without this timeout interrupted network connections can hang reader
READ_SIZE = 32768 # Consume all available in socket
DFLT_DEBUG_BUF_LVL = 3 # Level above which the logging output goes directly to stderr
AllowedVersions = ('IMAP4REV1', 'IMAP4') # Most recent first
# Commands
CMD_VAL_STATES = 0
CMD_VAL_ASYNC = 1
NONAUTH, AUTH, SELECTED, LOGOUT = 'NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'
Commands = {
# name valid states asynchronous
'APPEND': ((AUTH, SELECTED), False),
'AUTHENTICATE': ((NONAUTH,), False),
'CAPABILITY': ((NONAUTH, AUTH, SELECTED), True),
'CHECK': ((SELECTED,), True),
'CLOSE': ((SELECTED,), False),
'COMPRESS': ((AUTH,), False),
'COPY': ((SELECTED,), True),
'CREATE': ((AUTH, SELECTED), True),
'DELETE': ((AUTH, SELECTED), True),
'DELETEACL': ((AUTH, SELECTED), True),
'EXAMINE': ((AUTH, SELECTED), False),
'EXPUNGE': ((SELECTED,), True),
'FETCH': ((SELECTED,), True),
'GETACL': ((AUTH, SELECTED), True),
'GETANNOTATION':((AUTH, SELECTED), True),
'GETQUOTA': ((AUTH, SELECTED), True),
'GETQUOTAROOT': ((AUTH, SELECTED), True),
'ID': ((NONAUTH, AUTH, LOGOUT, SELECTED), True),
'IDLE': ((SELECTED,), False),
'LIST': ((AUTH, SELECTED), True),
'LOGIN': ((NONAUTH,), False),
'LOGOUT': ((NONAUTH, AUTH, LOGOUT, SELECTED), False),
'LSUB': ((AUTH, SELECTED), True),
'MYRIGHTS': ((AUTH, SELECTED), True),
'NAMESPACE': ((AUTH, SELECTED), True),
'NOOP': ((NONAUTH, AUTH, SELECTED), True),
'PARTIAL': ((SELECTED,), True),
'PROXYAUTH': ((AUTH,), False),
'RENAME': ((AUTH, SELECTED), True),
'SEARCH': ((SELECTED,), True),
'SELECT': ((AUTH, SELECTED), False),
'SETACL': ((AUTH, SELECTED), False),
'SETANNOTATION':((AUTH, SELECTED), True),
'SETQUOTA': ((AUTH, SELECTED), False),
'SORT': ((SELECTED,), True),
'STARTTLS': ((NONAUTH,), False),
'STATUS': ((AUTH, SELECTED), True),
'STORE': ((SELECTED,), True),
'SUBSCRIBE': ((AUTH, SELECTED), False),
'THREAD': ((SELECTED,), True),
'UID': ((SELECTED,), True),
'UNSUBSCRIBE': ((AUTH, SELECTED), False),
}
UID_direct = ('SEARCH', 'SORT', 'THREAD')
def Int2AP(num):
"""string = Int2AP(num)
Return 'num' converted to a string using characters from the set 'A'..'P'
"""
val, a2p = [], 'ABCDEFGHIJKLMNOP'
num = int(abs(num))
while num:
num, mod = divmod(num, 16)
val.insert(0, a2p[mod])
return ''.join(val)
class Request(object):
"""Private class to represent a request awaiting response."""
def __init__(self, parent, name=None, callback=None, cb_arg=None, cb_self=False):
self.parent = parent
self.name = name
self.callback = callback # Function called to process result
if not cb_self:
self.callback_arg = cb_arg # Optional arg passed to "callback"
else:
self.callback_arg = (self, cb_arg) # Self reference required in callback arg
self.tag = '%s%s' % (parent.tagpre, parent.tagnum)
parent.tagnum += 1
self.ready = threading.Event()
self.response = None
self.aborted = None
self.data = None
def abort(self, typ, val):
self.aborted = (typ, val)
self.deliver(None)
def get_response(self, exc_fmt=None):
self.callback = None
if __debug__: self.parent._log(3, '%s:%s.ready.wait' % (self.name, self.tag))
self.ready.wait()
if self.aborted is not None:
typ, val = self.aborted
if exc_fmt is None:
exc_fmt = '%s - %%s' % typ
raise typ(exc_fmt % str(val))
return self.response
def deliver(self, response):
if self.callback is not None:
self.callback((response, self.callback_arg, self.aborted))
return
self.response = response
self.ready.set()
if __debug__: self.parent._log(3, '%s:%s.ready.set' % (self.name, self.tag))
class IMAP4(object):
"""Threaded IMAP4 client class.
Instantiate with:
IMAP4(host=None, port=None, debug=None, debug_file=None, identifier=None, timeout=None, debug_buf_lvl=None)
host - host's name (default: localhost);
port - port number (default: standard IMAP4 port);
debug - debug level (default: 0 - no debug);
debug_file - debug stream (default: sys.stderr);
identifier - thread identifier prefix (default: host);
timeout - timeout in seconds when expecting a command response (default: no timeout),
debug_buf_lvl - debug level at which buffering is turned off.
All IMAP4rev1 commands are supported by methods of the same name.
Each command returns a tuple: (type, [data, ...]) where 'type'
is usually 'OK' or 'NO', and 'data' is either the text from the
tagged response, or untagged results from command. Each 'data' is
either a string, or a tuple. If a tuple, then the first part is the
header of the response, and the second part contains the data (ie:
'literal' value).
Errors raise the exception class <instance>.error("<reason>").
IMAP4 server errors raise <instance>.abort("<reason>"), which is
a sub-class of 'error'. Mailbox status changes from READ-WRITE to
READ-ONLY raise the exception class <instance>.readonly("<reason>"),
which is a sub-class of 'abort'.
"error" exceptions imply a program error.
"abort" exceptions imply the connection should be reset, and
the command re-tried.
"readonly" exceptions imply the command should be re-tried.
All commands take two optional named arguments:
'callback' and 'cb_arg'
If 'callback' is provided then the command is asynchronous, so after
the command is queued for transmission, the call returns immediately
with the tuple (None, None).
The result will be posted by invoking "callback" with one arg, a tuple:
callback((result, cb_arg, None))
or, if there was a problem:
callback((None, cb_arg, (exception class, reason)))
Otherwise the command is synchronous (waits for result). But note
that state-changing commands will both block until previous commands
have completed, and block subsequent commands until they have finished.
All (non-callback) arguments to commands are converted to strings,
except for AUTHENTICATE, and the last argument to APPEND which is
passed as an IMAP4 literal. If necessary (the string contains any
non-printing characters or white-space and isn't enclosed with
either parentheses or double or single quotes) each string is
quoted. However, the 'password' argument to the LOGIN command is
always quoted. If you want to avoid having an argument string
quoted (eg: the 'flags' argument to STORE) then enclose the string
in parentheses (eg: "(\Deleted)"). If you are using "sequence sets"
containing the wildcard character '*', then enclose the argument
in single quotes: the quotes will be removed and the resulting
string passed unquoted. Note also that you can pass in an argument
with a type that doesn't evaluate to 'basestring' (eg: 'bytearray')
and it will be converted to a string without quoting.
There is one instance variable, 'state', that is useful for tracking
whether the client needs to login to the server. If it has the
value "AUTH" after instantiating the class, then the connection
is pre-authenticated (otherwise it will be "NONAUTH"). Selecting a
mailbox changes the state to be "SELECTED", closing a mailbox changes
back to "AUTH", and once the client has logged out, the state changes
to "LOGOUT" and no further commands may be issued.
Note: to use this module, you must read the RFCs pertaining to the
IMAP4 protocol, as the semantics of the arguments to each IMAP4
command are left to the invoker, not to mention the results. Also,
most IMAP servers implement a sub-set of the commands available here.
Note also that you must call logout() to shut down threads before
discarding an instance.
"""
class error(Exception): pass # Logical errors - debug required
class abort(error): pass # Service errors - close and retry
class readonly(abort): pass # Mailbox status changed to READ-ONLY
continuation_cre = re.compile(r'\+( (?P<data>.*))?')
literal_cre = re.compile(r'.*{(?P<size>\d+)}$')
mapCRLF_cre = re.compile(r'\r\n|\r|\n')
# Need to quote "atom-specials" :-
# "(" / ")" / "{" / SP / 0x00 - 0x1f / 0x7f / "%" / "*" / DQUOTE / "\" / "]"
# so match not the inverse set
mustquote_cre = re.compile(r"[^!#$&'+,./0-9:;<=>?@A-Z\[^_`a-z|}~-]")
response_code_cre = re.compile(r'\[(?P<type>[A-Z-]+)( (?P<data>[^\]]*))?\]')
# sequence_set_cre = re.compile(r"^[0-9]+(:([0-9]+|\*))?(,[0-9]+(:([0-9]+|\*))?)*$")
untagged_response_cre = re.compile(r'\* (?P<type>[A-Z-]+)( (?P<data>.*))?')
untagged_status_cre = re.compile(r'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?')
def __init__(self, host=None, port=None, debug=None, debug_file=None, identifier=None, timeout=None, debug_buf_lvl=None):
self.state = NONAUTH # IMAP4 protocol state
self.literal = None # A literal argument to a command
self.tagged_commands = {} # Tagged commands awaiting response
self.untagged_responses = [] # [[typ: [data, ...]], ...]
self.mailbox = None # Current mailbox selected
self.mailboxes = {} # Untagged responses state per mailbox
self.is_readonly = False # READ-ONLY desired state
self.idle_rqb = None # Server IDLE Request - see _IdleCont
self.idle_timeout = None # Must prod server occasionally
self._expecting_data = 0 # Expecting message data
self._accumulated_data = [] # Message data accumulated so far
self._literal_expected = None # Message data descriptor
self.compressor = None # COMPRESS/DEFLATE if not None
self.decompressor = None
# Create unique tag for this session,
# and compile tagged response matcher.
self.tagnum = 0
self.tagpre = Int2AP(random.randint(4096, 65535))
self.tagre = re.compile(r'(?P<tag>'
+ self.tagpre
+ r'\d+) (?P<type>[A-Z]+) (?P<data>.*)')
if __debug__: self._init_debug(debug, debug_file, debug_buf_lvl)
self.resp_timeout = timeout # Timeout waiting for command response
if timeout is not None and timeout < READ_POLL_TIMEOUT:
self.read_poll_timeout = timeout
else:
self.read_poll_timeout = READ_POLL_TIMEOUT
self.read_size = READ_SIZE
# Open socket to server.
self.open(host, port)
if __debug__:
if debug:
self._mesg('connected to %s on port %s' % (self.host, self.port))
# Threading
if identifier is not None:
self.identifier = identifier
else:
self.identifier = self.host
if self.identifier:
self.identifier += ' '
self.Terminate = self.TerminateReader = False
self.state_change_free = threading.Event()
self.state_change_pending = threading.Lock()
self.commands_lock = threading.Lock()
self.idle_lock = threading.Lock()
self.ouq = Queue.Queue(10)
self.inq = Queue.Queue()
self.wrth = threading.Thread(target=self._writer)
self.wrth.setDaemon(True)
self.wrth.start()
self.rdth = threading.Thread(target=self._reader)
self.rdth.setDaemon(True)
self.rdth.start()
self.inth = threading.Thread(target=self._handler)
self.inth.setDaemon(True)
self.inth.start()
# Get server welcome message,
# request and store CAPABILITY response.
try:
self.welcome = self._request_push(tag='continuation').get_response('IMAP4 protocol error: %s')[1]
if self._get_untagged_response('PREAUTH'):
self.state = AUTH
if __debug__: self._log(1, 'state => AUTH')
elif self._get_untagged_response('OK'):
if __debug__: self._log(1, 'state => NONAUTH')
else:
raise self.error('unrecognised server welcome message: %s' % `self.welcome`)
typ, dat = self.capability()
if dat == [None]:
raise self.error('no CAPABILITY response from server')
self.capabilities = tuple(dat[-1].upper().split())
if __debug__: self._log(1, 'CAPABILITY: %r' % (self.capabilities,))
for version in AllowedVersions:
if not version in self.capabilities:
continue
self.PROTOCOL_VERSION = version
break
else:
raise self.error('server not IMAP4 compliant')
except:
self._close_threads()
raise
def __getattr__(self, attr):
# Allow UPPERCASE variants of IMAP4 command methods.
if attr in Commands:
return getattr(self, attr.lower())
raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
# Overridable methods
def open(self, host=None, port=None):
"""open(host=None, port=None)
Setup connection to remote server on "host:port"
(default: localhost:standard IMAP4 port).
This connection will be used by the routines:
read, send, shutdown, socket."""
self.host = self._choose_nonull_or_dflt('', host)
self.port = self._choose_nonull_or_dflt(IMAP4_PORT, port)
self.sock = self.open_socket()
self.read_fd = self.sock.fileno()
def open_socket(self):
"""open_socket()
Open socket choosing first address family available."""
msg = (-1, 'could not open socket')
for res in socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
except socket.error, msg:
continue
try:
for i in (0, 1):
try:
s.connect(sa)
break
except socket.error, msg:
if len(msg.args) < 2 or msg.args[0] != errno.EINTR:
raise
else:
raise socket.error(msg)
except socket.error, msg:
s.close()
continue
break
else:
raise socket.error(msg)
return s
def ssl_wrap_socket(self):
# Allow sending of keep-alive messages - seems to prevent some servers
# from closing SSL, leading to deadlocks.
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
try:
import ssl
if self.ca_certs is not None:
cert_reqs = ssl.CERT_REQUIRED
else:
cert_reqs = ssl.CERT_NONE
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile, ca_certs=self.ca_certs, cert_reqs=cert_reqs)
ssl_exc = ssl.SSLError
self.read_fd = self.sock.fileno()
except ImportError:
# No ssl module, and socket.ssl has no fileno(), and does not allow certificate verification
raise socket.sslerror("imaplib2 SSL mode does not work without ssl module")
if self.cert_verify_cb is not None:
cert_err = self.cert_verify_cb(self.sock.getpeercert(), self.host)
if cert_err:
raise ssl_exc(cert_err)
def start_compressing(self):
"""start_compressing()
Enable deflate compression on the socket (RFC 4978)."""
# rfc 1951 - pure DEFLATE, so use -15 for both windows
self.decompressor = zlib.decompressobj(-15)
self.compressor = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15)
def read(self, size):
"""data = read(size)
Read at most 'size' bytes from remote."""
if self.decompressor is None:
return self.sock.recv(size)
if self.decompressor.unconsumed_tail:
data = self.decompressor.unconsumed_tail
else:
data = self.sock.recv(READ_SIZE)
return self.decompressor.decompress(data, size)
def send(self, data):
"""send(data)
Send 'data' to remote."""
if self.compressor is not None:
data = self.compressor.compress(data)
data += self.compressor.flush(zlib.Z_SYNC_FLUSH)
self.sock.sendall(data)
def shutdown(self):
"""shutdown()
Close I/O established in "open"."""
self.sock.close()
def socket(self):
"""socket = socket()
Return socket instance used to connect to IMAP4 server."""
return self.sock
# Utility methods
def enable_compression(self):
"""enable_compression()
Ask the server to start compressing the connection.
Should be called from user of this class after instantiation, as in:
if 'COMPRESS=DEFLATE' in imapobj.capabilities:
imapobj.enable_compression()"""
try:
typ, dat = self._simple_command('COMPRESS', 'DEFLATE')
if typ == 'OK':
self.start_compressing()
if __debug__: self._log(1, 'Enabled COMPRESS=DEFLATE')
finally:
self._release_state_change()
def pop_untagged_responses(self):
""" for typ,data in pop_untagged_responses(): pass
Generator for any remaining untagged responses.
Returns and removes untagged responses in order of reception.
Use at your own risk!"""
while self.untagged_responses:
self.commands_lock.acquire()
try:
yield self.untagged_responses.pop(0)
finally:
self.commands_lock.release()
def recent(self, **kw):
"""(typ, [data]) = recent()
Return 'RECENT' responses if any exist,
else prompt server for an update using the 'NOOP' command.
'data' is None if no new messages,
else list of RECENT responses, most recent last."""
name = 'RECENT'
typ, dat = self._untagged_response(None, [None], name)
if dat != [None]:
return self._deliver_dat(typ, dat, kw)
kw['untagged_response'] = name
return self.noop(**kw) # Prod server for response
def response(self, code, **kw):
"""(code, [data]) = response(code)
Return data for response 'code' if received, or None.
Old value for response 'code' is cleared."""
typ, dat = self._untagged_response(code, [None], code.upper())
return self._deliver_dat(typ, dat, kw)
# IMAP4 commands
def append(self, mailbox, flags, date_time, message, **kw):
"""(typ, [data]) = append(mailbox, flags, date_time, message)
Append message to named mailbox.
All args except `message' can be None."""
name = 'APPEND'
if not mailbox:
mailbox = 'INBOX'
if flags:
if (flags[0],flags[-1]) != ('(',')'):
flags = '(%s)' % flags
else:
flags = None
if date_time:
date_time = Time2Internaldate(date_time)
else:
date_time = None
self.literal = self.mapCRLF_cre.sub(CRLF, message)
try:
return self._simple_command(name, mailbox, flags, date_time, **kw)
finally:
self._release_state_change()
def authenticate(self, mechanism, authobject, **kw):
"""(typ, [data]) = authenticate(mechanism, authobject)
Authenticate command - requires response processing.
'mechanism' specifies which authentication mechanism is to
be used - it must appear in <instance>.capabilities in the
form AUTH=<mechanism>.
'authobject' must be a callable object:
data = authobject(response)
It will be called to process server continuation responses.
It should return data that will be encoded and sent to server.
It should return None if the client abort response '*' should
be sent instead."""
self.literal = _Authenticator(authobject).process
try:
typ, dat = self._simple_command('AUTHENTICATE', mechanism.upper())
if typ != 'OK':
self._deliver_exc(self.error, dat[-1], kw)
self.state = AUTH
if __debug__: self._log(1, 'state => AUTH')
finally:
self._release_state_change()
return self._deliver_dat(typ, dat, kw)
def capability(self, **kw):
"""(typ, [data]) = capability()
Fetch capabilities list from server."""
name = 'CAPABILITY'
kw['untagged_response'] = name
return self._simple_command(name, **kw)
def check(self, **kw):
"""(typ, [data]) = check()
Checkpoint mailbox on server."""
return self._simple_command('CHECK', **kw)
def close(self, **kw):
"""(typ, [data]) = close()
Close currently selected mailbox.
Deleted messages are removed from writable mailbox.
This is the recommended command before 'LOGOUT'."""
if self.state != 'SELECTED':
raise self.error('No mailbox selected.')
try:
typ, dat = self._simple_command('CLOSE')
finally:
self.state = AUTH
if __debug__: self._log(1, 'state => AUTH')
self._release_state_change()
return self._deliver_dat(typ, dat, kw)
def copy(self, message_set, new_mailbox, **kw):
"""(typ, [data]) = copy(message_set, new_mailbox)
Copy 'message_set' messages onto end of 'new_mailbox'."""
return self._simple_command('COPY', message_set, new_mailbox, **kw)
def create(self, mailbox, **kw):
"""(typ, [data]) = create(mailbox)
Create new mailbox."""
return self._simple_command('CREATE', mailbox, **kw)
def delete(self, mailbox, **kw):
"""(typ, [data]) = delete(mailbox)
Delete old mailbox."""
return self._simple_command('DELETE', mailbox, **kw)
def deleteacl(self, mailbox, who, **kw):
"""(typ, [data]) = deleteacl(mailbox, who)
Delete the ACLs (remove any rights) set for who on mailbox."""
return self._simple_command('DELETEACL', mailbox, who, **kw)
def examine(self, mailbox='INBOX', **kw):
"""(typ, [data]) = examine(mailbox='INBOX')
Select a mailbox for READ-ONLY access. (Flushes all untagged responses.)
'data' is count of messages in mailbox ('EXISTS' response).
Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so
other responses should be obtained via "response('FLAGS')" etc."""
return self.select(mailbox=mailbox, readonly=True, **kw)
def expunge(self, **kw):
"""(typ, [data]) = expunge()
Permanently remove deleted items from selected mailbox.
Generates 'EXPUNGE' response for each deleted message.
'data' is list of 'EXPUNGE'd message numbers in order received."""
name = 'EXPUNGE'
kw['untagged_response'] = name
return self._simple_command(name, **kw)
def fetch(self, message_set, message_parts, **kw):
"""(typ, [data, ...]) = fetch(message_set, message_parts)
Fetch (parts of) messages.
'message_parts' should be a string of selected parts
enclosed in parentheses, eg: "(UID BODY[TEXT])".
'data' are tuples of message part envelope and data,
followed by a string containing the trailer."""
name = 'FETCH'
kw['untagged_response'] = name
return self._simple_command(name, message_set, message_parts, **kw)
def getacl(self, mailbox, **kw):
"""(typ, [data]) = getacl(mailbox)
Get the ACLs for a mailbox."""
kw['untagged_response'] = 'ACL'
return self._simple_command('GETACL', mailbox, **kw)
def getannotation(self, mailbox, entry, attribute, **kw):
"""(typ, [data]) = getannotation(mailbox, entry, attribute)
Retrieve ANNOTATIONs."""
kw['untagged_response'] = 'ANNOTATION'
return self._simple_command('GETANNOTATION', mailbox, entry, attribute, **kw)
def getquota(self, root, **kw):
"""(typ, [data]) = getquota(root)
Get the quota root's resource usage and limits.
(Part of the IMAP4 QUOTA extension defined in rfc2087.)"""
kw['untagged_response'] = 'QUOTA'
return self._simple_command('GETQUOTA', root, **kw)
def getquotaroot(self, mailbox, **kw):
# Hmmm, this is non-std! Left for backwards-compatibility, sigh.
# NB: usage should have been defined as:
# (typ, [QUOTAROOT responses...]) = getquotaroot(mailbox)
# (typ, [QUOTA responses...]) = response('QUOTA')
"""(typ, [[QUOTAROOT responses...], [QUOTA responses...]]) = getquotaroot(mailbox)
Get the list of quota roots for the named mailbox."""
typ, dat = self._simple_command('GETQUOTAROOT', mailbox)
typ, quota = self._untagged_response(typ, dat, 'QUOTA')
typ, quotaroot = self._untagged_response(typ, dat, 'QUOTAROOT')
return self._deliver_dat(typ, [quotaroot, quota], kw)
def id(self, *kv_pairs, **kw):
"""(typ, [data]) = <instance>.id(kv_pairs)
'kv_pairs' is a possibly empty list of keys and values.
'data' is a list of ID key value pairs or NIL.
NB: a single argument is assumed to be correctly formatted and is passed through unchanged
(for backward compatibility with earlier version).
Exchange information for problem analysis and determination.
The ID extension is defined in RFC 2971. """
name = 'ID'
kw['untagged_response'] = name
if not kv_pairs:
data = 'NIL'
elif len(kv_pairs) == 1:
data = kv_pairs[0] # Assume invoker passing correctly formatted string (back-compat)
else:
data = '(%s)' % ' '.join([(arg and self._quote(arg) or 'NIL') for arg in kv_pairs])
return self._simple_command(name, (data,), **kw)
def idle(self, timeout=None, **kw):
""""(typ, [data]) = idle(timeout=None)
Put server into IDLE mode until server notifies some change,
or 'timeout' (secs) occurs (default: 29 minutes),
or another IMAP4 command is scheduled."""
name = 'IDLE'
self.literal = _IdleCont(self, timeout).process
try:
return self._simple_command(name, **kw)
finally:
self._release_state_change()
def list(self, directory='""', pattern='*', **kw):
"""(typ, [data]) = list(directory='""', pattern='*')
List mailbox names in directory matching pattern.
'data' is list of LIST responses.
NB: for 'pattern':
% matches all except separator ( so LIST "" "%" returns names at root)
* matches all (so LIST "" "*" returns whole directory tree from root)"""
name = 'LIST'
kw['untagged_response'] = name
return self._simple_command(name, directory, pattern, **kw)
def login(self, user, password, **kw):
"""(typ, [data]) = login(user, password)
Identify client using plaintext password.
NB: 'password' will be quoted."""
try:
typ, dat = self._simple_command('LOGIN', user, self._quote(password))
if typ != 'OK':
self._deliver_exc(self.error, dat[-1], kw)
self.state = AUTH
if __debug__: self._log(1, 'state => AUTH')
finally:
self._release_state_change()
return self._deliver_dat(typ, dat, kw)
def login_cram_md5(self, user, password, **kw):
"""(typ, [data]) = login_cram_md5(user, password)
Force use of CRAM-MD5 authentication."""
self.user, self.password = user, password
return self.authenticate('CRAM-MD5', self._CRAM_MD5_AUTH, **kw)
def _CRAM_MD5_AUTH(self, challenge):
"""Authobject to use with CRAM-MD5 authentication."""
import hmac
return self.user + " " + hmac.HMAC(self.password, challenge).hexdigest()
def logout(self, **kw):
"""(typ, [data]) = logout()
Shutdown connection to server.
Returns server 'BYE' response.
NB: You must call this to shut down threads before discarding an instance."""
self.state = LOGOUT
if __debug__: self._log(1, 'state => LOGOUT')
try:
try:
typ, dat = self._simple_command('LOGOUT')
except:
typ, dat = 'NO', ['%s: %s' % sys.exc_info()[:2]]
if __debug__: self._log(1, dat)
self._close_threads()
finally:
self._release_state_change()
if __debug__: self._log(1, 'connection closed')
bye = self._get_untagged_response('BYE', leave=True)
if bye:
typ, dat = 'BYE', bye
return self._deliver_dat(typ, dat, kw)
def lsub(self, directory='""', pattern='*', **kw):
"""(typ, [data, ...]) = lsub(directory='""', pattern='*')
List 'subscribed' mailbox names in directory matching pattern.
'data' are tuples of message part envelope and data."""
name = 'LSUB'
kw['untagged_response'] = name
return self._simple_command(name, directory, pattern, **kw)
def myrights(self, mailbox, **kw):
"""(typ, [data]) = myrights(mailbox)
Show my ACLs for a mailbox (i.e. the rights that I have on mailbox)."""
name = 'MYRIGHTS'
kw['untagged_response'] = name
return self._simple_command(name, mailbox, **kw)
def namespace(self, **kw):
"""(typ, [data, ...]) = namespace()
Returns IMAP namespaces ala rfc2342."""
name = 'NAMESPACE'
kw['untagged_response'] = name
return self._simple_command(name, **kw)
def noop(self, **kw):
"""(typ, [data]) = noop()
Send NOOP command."""
if __debug__: self._dump_ur(3)
return self._simple_command('NOOP', **kw)
def partial(self, message_num, message_part, start, length, **kw):
"""(typ, [data, ...]) = partial(message_num, message_part, start, length)
Fetch truncated part of a message.
'data' is tuple of message part envelope and data.
NB: obsolete."""
name = 'PARTIAL'
kw['untagged_response'] = 'FETCH'
return self._simple_command(name, message_num, message_part, start, length, **kw)
def proxyauth(self, user, **kw):
"""(typ, [data]) = proxyauth(user)
Assume authentication as 'user'.
(Allows an authorised administrator to proxy into any user's mailbox.)"""
try:
return self._simple_command('PROXYAUTH', user, **kw)
finally:
self._release_state_change()
def rename(self, oldmailbox, newmailbox, **kw):
"""(typ, [data]) = rename(oldmailbox, newmailbox)
Rename old mailbox name to new."""
return self._simple_command('RENAME', oldmailbox, newmailbox, **kw)
def search(self, charset, *criteria, **kw):
"""(typ, [data]) = search(charset, criterion, ...)
Search mailbox for matching messages.
'data' is space separated list of matching message numbers."""
name = 'SEARCH'
kw['untagged_response'] = name
if charset:
return self._simple_command(name, 'CHARSET', charset, *criteria, **kw)
return self._simple_command(name, *criteria, **kw)
def select(self, mailbox='INBOX', readonly=False, **kw):
"""(typ, [data]) = select(mailbox='INBOX', readonly=False)
Select a mailbox. (Restores any previous untagged responses.)
'data' is count of messages in mailbox ('EXISTS' response).
Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so
other responses should be obtained via "response('FLAGS')" etc."""
self.commands_lock.acquire()
# Save state of old mailbox, restore state for new...
self.mailboxes[self.mailbox] = self.untagged_responses
self.untagged_responses = self.mailboxes.setdefault(mailbox, [])
self.commands_lock.release()
self.mailbox = mailbox
self.is_readonly = readonly and True or False
if readonly:
name = 'EXAMINE'
else:
name = 'SELECT'
try:
rqb = self._command(name, mailbox)
typ, dat = rqb.get_response('command: %s => %%s' % rqb.name)
if typ != 'OK':
if self.state == SELECTED:
self.state = AUTH
if __debug__: self._log(1, 'state => AUTH')
if typ == 'BAD':
self._deliver_exc(self.error, '%s command error: %s %s. Data: %.100s' % (name, typ, dat, mailbox), kw)
return self._deliver_dat(typ, dat, kw)
self.state = SELECTED
if __debug__: self._log(1, 'state => SELECTED')
finally:
self._release_state_change()
if self._get_untagged_response('READ-ONLY', leave=True) and not readonly:
if __debug__: self._dump_ur(1)
self._deliver_exc(self.readonly, '%s is not writable' % mailbox, kw)
typ, dat = self._untagged_response(typ, [None], 'EXISTS')
return self._deliver_dat(typ, dat, kw)