Debian Codegraph @

lib-python/3/imaplib.py

raw symbols SCIP
1 """IMAP4 client.
2
3 Based on RFC 2060.
4
5 Public class: IMAP4
6 Public variable: Debug
7 Public functions: Internaldate2tuple
8 Int2AP
9 ParseFlags
10 Time2Internaldate
11 """
12
13 # Author: Piers Lauder <[email protected]> December 1997.
14 #
15 # Authentication code contributed by Donn Cave <[email protected]> June 1998.
16 # String method conversion by ESR, February 2001.
17 # GET/SETACL contributed by Anthony Baxter <[email protected]> April 2001.
18 # IMAP4_SSL contributed by Tino Lange <[email protected]> March 2002.
19 # GET/SETQUOTA contributed by Andreas Zeidler <[email protected]> June 2002.
20 # PROXYAUTH contributed by Rick Holbert <[email protected]> November 2002.
21 # GET/SETANNOTATION contributed by Tomas Lindroos <[email protected]> June 2005.
22
23 __version__ = "2.58"
24
25 import binascii, errno, random, re, socket, subprocess, sys, time, calendar
26 from datetime import datetime, timezone, timedelta
27 from io import DEFAULT_BUFFER_SIZE
28
29 try:
30 import ssl
31 HAVE_SSL = True
32 except ImportError:
33 HAVE_SSL = False
34
35 __all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple",
36 "Int2AP", "ParseFlags", "Time2Internaldate"]
37
38 # Globals
39
40 CRLF = b'\r\n'
41 Debug = 0
42 IMAP4_PORT = 143
43 IMAP4_SSL_PORT = 993
44 AllowedVersions = ('IMAP4REV1', 'IMAP4') # Most recent first
45
46 # Maximal line length when calling readline(). This is to prevent
47 # reading arbitrary length lines. RFC 3501 and 2060 (IMAP 4rev1)
48 # don't specify a line length. RFC 2683 suggests limiting client
49 # command lines to 1000 octets and that servers should be prepared
50 # to accept command lines up to 8000 octets, so we used to use 10K here.
51 # In the modern world (eg: gmail) the response to, for example, a
52 # search command can be quite large, so we now use 1M.
53 _MAXLINE = 1000000
54
55 # Data larger than this will be read in chunks, to prevent extreme
56 # overallocation.
57 _SAFE_BUF_SIZE = 1 << 20
58
59 # Commands
60
61 Commands = {
62 # name valid states
63 'APPEND': ('AUTH', 'SELECTED'),
64 'AUTHENTICATE': ('NONAUTH',),
65 'CAPABILITY': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
66 'CHECK': ('SELECTED',),
67 'CLOSE': ('SELECTED',),
68 'COPY': ('SELECTED',),
69 'CREATE': ('AUTH', 'SELECTED'),
70 'DELETE': ('AUTH', 'SELECTED'),
71 'DELETEACL': ('AUTH', 'SELECTED'),
72 'ENABLE': ('AUTH', ),
73 'EXAMINE': ('AUTH', 'SELECTED'),
74 'EXPUNGE': ('SELECTED',),
75 'FETCH': ('SELECTED',),
76 'GETACL': ('AUTH', 'SELECTED'),
77 'GETANNOTATION':('AUTH', 'SELECTED'),
78 'GETQUOTA': ('AUTH', 'SELECTED'),
79 'GETQUOTAROOT': ('AUTH', 'SELECTED'),
80 'MYRIGHTS': ('AUTH', 'SELECTED'),
81 'LIST': ('AUTH', 'SELECTED'),
82 'LOGIN': ('NONAUTH',),
83 'LOGOUT': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
84 'LSUB': ('AUTH', 'SELECTED'),
85 'MOVE': ('SELECTED',),
86 'NAMESPACE': ('AUTH', 'SELECTED'),
87 'NOOP': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
88 'PARTIAL': ('SELECTED',), # NB: obsolete
89 'PROXYAUTH': ('AUTH',),
90 'RENAME': ('AUTH', 'SELECTED'),
91 'SEARCH': ('SELECTED',),
92 'SELECT': ('AUTH', 'SELECTED'),
93 'SETACL': ('AUTH', 'SELECTED'),
94 'SETANNOTATION':('AUTH', 'SELECTED'),
95 'SETQUOTA': ('AUTH', 'SELECTED'),
96 'SORT': ('SELECTED',),
97 'STARTTLS': ('NONAUTH',),
98 'STATUS': ('AUTH', 'SELECTED'),
99 'STORE': ('SELECTED',),
100 'SUBSCRIBE': ('AUTH', 'SELECTED'),
101 'THREAD': ('SELECTED',),
102 'UID': ('SELECTED',),
103 'UNSUBSCRIBE': ('AUTH', 'SELECTED'),
104 'UNSELECT': ('SELECTED',),
105 }
106
107 # Patterns to match server responses
108
109 Continuation = re.compile(br'\+( (?P<data>.*))?')
110 Flags = re.compile(br'.*FLAGS \((?P<flags>[^\)]*)\)')
111 InternalDate = re.compile(br'.*INTERNALDATE "'
112 br'(?P<day>[ 0123][0-9])-(?P<mon>[A-Z][a-z][a-z])-(?P<year>[0-9][0-9][0-9][0-9])'
113 br' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
114 br' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
115 br'"')
116 # Literal is no longer used; kept for backward compatibility.
117 Literal = re.compile(br'.*{(?P<size>\d+)}$', re.ASCII)
118 MapCRLF = re.compile(br'\r\n|\r|\n')
119 # We no longer exclude the ']' character from the data portion of the response
120 # code, even though it violates the RFC. Popular IMAP servers such as Gmail
121 # allow flags with ']', and there are programs (including imaplib!) that can
122 # produce them. The problem with this is if the 'text' portion of the response
123 # includes a ']' we'll parse the response wrong (which is the point of the RFC
124 # restriction). However, that seems less likely to be a problem in practice
125 # than being unable to correctly parse flags that include ']' chars, which
126 # was reported as a real-world problem in issue #21815.
127 Response_code = re.compile(br'\[(?P<type>[A-Z-]+)( (?P<data>.*))?\]')
128 Untagged_response = re.compile(br'\* (?P<type>[A-Z-]+)( (?P<data>.*))?')
129 # Untagged_status is no longer used; kept for backward compatibility
130 Untagged_status = re.compile(
131 br'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?', re.ASCII)
132 # We compile these in _mode_xxx.
133 _Literal = br'.*{(?P<size>\d+)}$'
134 _Untagged_status = br'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?'
135
136
137
138 class IMAP4:
139
140 r"""IMAP4 client class.
141
142 Instantiate with: IMAP4([host[, port[, timeout=None]]])
143
144 host - host's name (default: localhost);
145 port - port number (default: standard IMAP4 port).
146 timeout - socket timeout (default: None)
147 If timeout is not given or is None,
148 the global default socket timeout is used
149
150 All IMAP4rev1 commands are supported by methods of the same
151 name (in lowercase).
152
153 All arguments to commands are converted to strings, except for
154 AUTHENTICATE, and the last argument to APPEND which is passed as
155 an IMAP4 literal. If necessary (the string contains any
156 non-printing characters or white-space and isn't enclosed with
157 either parentheses or double quotes) each string is quoted.
158 However, the 'password' argument to the LOGIN command is always
159 quoted. If you want to avoid having an argument string quoted
160 (eg: the 'flags' argument to STORE) then enclose the string in
161 parentheses (eg: "(\Deleted)").
162
163 Each command returns a tuple: (type, [data, ...]) where 'type'
164 is usually 'OK' or 'NO', and 'data' is either the text from the
165 tagged response, or untagged results from command. Each 'data'
166 is either a string, or a tuple. If a tuple, then the first part
167 is the header of the response, and the second part contains
168 the data (ie: 'literal' value).
169
170 Errors raise the exception class <instance>.error("<reason>").
171 IMAP4 server errors raise <instance>.abort("<reason>"),
172 which is a sub-class of 'error'. Mailbox status changes
173 from READ-WRITE to READ-ONLY raise the exception class
174 <instance>.readonly("<reason>"), which is a sub-class of 'abort'.
175
176 "error" exceptions imply a program error.
177 "abort" exceptions imply the connection should be reset, and
178 the command re-tried.
179 "readonly" exceptions imply the command should be re-tried.
180
181 Note: to use this module, you must read the RFCs pertaining to the
182 IMAP4 protocol, as the semantics of the arguments to each IMAP4
183 command are left to the invoker, not to mention the results. Also,
184 most IMAP servers implement a sub-set of the commands available here.
185 """
186
187 class error(Exception): pass # Logical errors - debug required
188 class abort(error): pass # Service errors - close and retry
189 class readonly(abort): pass # Mailbox status changed to READ-ONLY
190
191 def __init__(self, host='', port=IMAP4_PORT, timeout=None):
192 self.debug = Debug
193 self.state = 'LOGOUT'
194 self.literal = None # A literal argument to a command
195 self.tagged_commands = {} # Tagged commands awaiting response
196 self.untagged_responses = {} # {typ: [data, ...], ...}
197 self.continuation_response = '' # Last continuation response
198 self.is_readonly = False # READ-ONLY desired state
199 self.tagnum = 0
200 self._tls_established = False
201 self._mode_ascii()
202
203 # Open socket to server.
204
205 self.open(host, port, timeout)
206
207 try:
208 self._connect()
209 except Exception:
210 try:
211 self.shutdown()
212 except OSError:
213 pass
214 raise
215
216 def _mode_ascii(self):
217 self.utf8_enabled = False
218 self._encoding = 'ascii'
219 self.Literal = re.compile(_Literal, re.ASCII)
220 self.Untagged_status = re.compile(_Untagged_status, re.ASCII)
221
222
223 def _mode_utf8(self):
224 self.utf8_enabled = True
225 self._encoding = 'utf-8'
226 self.Literal = re.compile(_Literal)
227 self.Untagged_status = re.compile(_Untagged_status)
228
229
230 def _connect(self):
231 # Create unique tag for this session,
232 # and compile tagged response matcher.
233
234 self.tagpre = Int2AP(random.randint(4096, 65535))
235 self.tagre = re.compile(br'(?P<tag>'
236 + self.tagpre
237 + br'\d+) (?P<type>[A-Z]+) (?P<data>.*)', re.ASCII)
238
239 # Get server welcome message,
240 # request and store CAPABILITY response.
241
242 if __debug__:
243 self._cmd_log_len = 10
244 self._cmd_log_idx = 0
245 self._cmd_log = {} # Last `_cmd_log_len' interactions
246 if self.debug >= 1:
247 self._mesg('imaplib version %s' % __version__)
248 self._mesg('new IMAP4 connection, tag=%s' % self.tagpre)
249
250 self.welcome = self._get_response()
251 if 'PREAUTH' in self.untagged_responses:
252 self.state = 'AUTH'
253 elif 'OK' in self.untagged_responses:
254 self.state = 'NONAUTH'
255 else:
256 raise self.error(self.welcome)
257
258 self._get_capabilities()
259 if __debug__:
260 if self.debug >= 3:
261 self._mesg('CAPABILITIES: %r' % (self.capabilities,))
262
263 for version in AllowedVersions:
264 if not version in self.capabilities:
265 continue
266 self.PROTOCOL_VERSION = version
267 return
268
269 raise self.error('server not IMAP4 compliant')
270
271
272 def __getattr__(self, attr):
273 # Allow UPPERCASE variants of IMAP4 command methods.
274 if attr in Commands:
275 return getattr(self, attr.lower())
276 raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
277
278 def __enter__(self):
279 return self
280
281 def __exit__(self, *args):
282 if self.state == "LOGOUT":
283 return
284
285 try:
286 self.logout()
287 except OSError:
288 pass
289
290
291 # Overridable methods
292
293
294 def _create_socket(self, timeout):
295 # Default value of IMAP4.host is '', but socket.getaddrinfo()
296 # (which is used by socket.create_connection()) expects None
297 # as a default value for host.
298 if timeout is not None and not timeout:
299 raise ValueError('Non-blocking socket (timeout=0) is not supported')
300 host = None if not self.host else self.host
301 sys.audit("imaplib.open", self, self.host, self.port)
302 address = (host, self.port)
303 if timeout is not None:
304 return socket.create_connection(address, timeout)
305 return socket.create_connection(address)
306
307 def open(self, host='', port=IMAP4_PORT, timeout=None):
308 """Setup connection to remote server on "host:port"
309 (default: localhost:standard IMAP4 port).
310 This connection will be used by the routines:
311 read, readline, send, shutdown.
312 """
313 self.host = host
314 self.port = port
315 self.sock = self._create_socket(timeout)
316 self.file = self.sock.makefile('rb')
317
318
319 def read(self, size):
320 """Read 'size' bytes from remote."""
321 cursize = min(size, _SAFE_BUF_SIZE)
322 data = self.file.read(cursize)
323 while cursize < size and len(data) == cursize:
324 delta = min(cursize, size - cursize)
325 data += self.file.read(delta)
326 cursize += delta
327 return data
328
329
330 def readline(self):
331 """Read line from remote."""
332 line = self.file.readline(_MAXLINE + 1)
333 if len(line) > _MAXLINE:
334 raise self.error("got more than %d bytes" % _MAXLINE)
335 return line
336
337
338 def send(self, data):
339 """Send data to remote."""
340 sys.audit("imaplib.send", self, data)
341 self.sock.sendall(data)
342
343
344 def shutdown(self):
345 """Close I/O established in "open"."""
346 self.file.close()
347 try:
348 self.sock.shutdown(socket.SHUT_RDWR)
349 except OSError as exc:
350 # The server might already have closed the connection.
351 # On Windows, this may result in WSAEINVAL (error 10022):
352 # An invalid operation was attempted.
353 if (exc.errno != errno.ENOTCONN
354 and getattr(exc, 'winerror', 0) != 10022):
355 raise
356 finally:
357 self.sock.close()
358
359
360 def socket(self):
361 """Return socket instance used to connect to IMAP4 server.
362
363 socket = <instance>.socket()
364 """
365 return self.sock
366
367
368
369 # Utility methods
370
371
372 def recent(self):
373 """Return most recent 'RECENT' responses if any exist,
374 else prompt server for an update using the 'NOOP' command.
375
376 (typ, [data]) = <instance>.recent()
377
378 'data' is None if no new messages,
379 else list of RECENT responses, most recent last.
380 """
381 name = 'RECENT'
382 typ, dat = self._untagged_response('OK', [None], name)
383 if dat[-1]:
384 return typ, dat
385 typ, dat = self.noop() # Prod server for response
386 return self._untagged_response(typ, dat, name)
387
388
389 def response(self, code):
390 """Return data for response 'code' if received, or None.
391
392 Old value for response 'code' is cleared.
393
394 (code, [data]) = <instance>.response(code)
395 """
396 return self._untagged_response(code, [None], code.upper())
397
398
399
400 # IMAP4 commands
401
402
403 def append(self, mailbox, flags, date_time, message):
404 """Append message to named mailbox.
405
406 (typ, [data]) = <instance>.append(mailbox, flags, date_time, message)
407
408 All args except `message' can be None.
409 """
410 name = 'APPEND'
411 if not mailbox:
412 mailbox = 'INBOX'
413 if flags:
414 if (flags[0],flags[-1]) != ('(',')'):
415 flags = '(%s)' % flags
416 else:
417 flags = None
418 if date_time:
419 date_time = Time2Internaldate(date_time)
420 else:
421 date_time = None
422 literal = MapCRLF.sub(CRLF, message)
423 if self.utf8_enabled:
424 literal = b'UTF8 (' + literal + b')'
425 self.literal = literal
426 return self._simple_command(name, mailbox, flags, date_time)
427
428
429 def authenticate(self, mechanism, authobject):
430 """Authenticate command - requires response processing.
431
432 'mechanism' specifies which authentication mechanism is to
433 be used - it must appear in <instance>.capabilities in the
434 form AUTH=<mechanism>.
435
436 'authobject' must be a callable object:
437
438 data = authobject(response)
439
440 It will be called to process server continuation responses; the
441 response argument it is passed will be a bytes. It should return bytes
442 data that will be base64 encoded and sent to the server. It should
443 return None if the client abort response '*' should be sent instead.
444 """
445 mech = mechanism.upper()
446 # XXX: shouldn't this code be removed, not commented out?
447 #cap = 'AUTH=%s' % mech
448 #if not cap in self.capabilities: # Let the server decide!
449 # raise self.error("Server doesn't allow %s authentication." % mech)
450 self.literal = _Authenticator(authobject).process
451 typ, dat = self._simple_command('AUTHENTICATE', mech)
452 if typ != 'OK':
453 raise self.error(dat[-1].decode('utf-8', 'replace'))
454 self.state = 'AUTH'
455 return typ, dat
456
457
458 def capability(self):
459 """(typ, [data]) = <instance>.capability()
460 Fetch capabilities list from server."""
461
462 name = 'CAPABILITY'
463 typ, dat = self._simple_command(name)
464 return self._untagged_response(typ, dat, name)
465
466
467 def check(self):
468 """Checkpoint mailbox on server.
469
470 (typ, [data]) = <instance>.check()
471 """
472 return self._simple_command('CHECK')
473
474
475 def close(self):
476 """Close currently selected mailbox.
477
478 Deleted messages are removed from writable mailbox.
479 This is the recommended command before 'LOGOUT'.
480
481 (typ, [data]) = <instance>.close()
482 """
483 try:
484 typ, dat = self._simple_command('CLOSE')
485 finally:
486 self.state = 'AUTH'
487 return typ, dat
488
489
490 def copy(self, message_set, new_mailbox):
491 """Copy 'message_set' messages onto end of 'new_mailbox'.
492
493 (typ, [data]) = <instance>.copy(message_set, new_mailbox)
494 """
495 return self._simple_command('COPY', message_set, new_mailbox)
496
497
498 def create(self, mailbox):
499 """Create new mailbox.
500
501 (typ, [data]) = <instance>.create(mailbox)
502 """
503 return self._simple_command('CREATE', mailbox)
504
505
506 def delete(self, mailbox):
507 """Delete old mailbox.
508
509 (typ, [data]) = <instance>.delete(mailbox)
510 """
511 return self._simple_command('DELETE', mailbox)
512
513 def deleteacl(self, mailbox, who):
514 """Delete the ACLs (remove any rights) set for who on mailbox.
515
516 (typ, [data]) = <instance>.deleteacl(mailbox, who)
517 """
518 return self._simple_command('DELETEACL', mailbox, who)
519
520 def enable(self, capability):
521 """Send an RFC5161 enable string to the server.
522
523 (typ, [data]) = <instance>.enable(capability)
524 """
525 if 'ENABLE' not in self.capabilities:
526 raise IMAP4.error("Server does not support ENABLE")
527 typ, data = self._simple_command('ENABLE', capability)
528 if typ == 'OK' and 'UTF8=ACCEPT' in capability.upper():
529 self._mode_utf8()
530 return typ, data
531
532 def expunge(self):
533 """Permanently remove deleted items from selected mailbox.
534
535 Generates 'EXPUNGE' response for each deleted message.
536
537 (typ, [data]) = <instance>.expunge()
538
539 'data' is list of 'EXPUNGE'd message numbers in order received.
540 """
541 name = 'EXPUNGE'
542 typ, dat = self._simple_command(name)
543 return self._untagged_response(typ, dat, name)
544
545
546 def fetch(self, message_set, message_parts):
547 """Fetch (parts of) messages.
548
549 (typ, [data, ...]) = <instance>.fetch(message_set, message_parts)
550
551 'message_parts' should be a string of selected parts
552 enclosed in parentheses, eg: "(UID BODY[TEXT])".
553
554 'data' are tuples of message part envelope and data.
555 """
556 name = 'FETCH'
557 typ, dat = self._simple_command(name, message_set, message_parts)
558 return self._untagged_response(typ, dat, name)
559
560
561 def getacl(self, mailbox):
562 """Get the ACLs for a mailbox.
563
564 (typ, [data]) = <instance>.getacl(mailbox)
565 """
566 typ, dat = self._simple_command('GETACL', mailbox)
567 return self._untagged_response(typ, dat, 'ACL')
568
569
570 def getannotation(self, mailbox, entry, attribute):
571 """(typ, [data]) = <instance>.getannotation(mailbox, entry, attribute)
572 Retrieve ANNOTATIONs."""
573
574 typ, dat = self._simple_command('GETANNOTATION', mailbox, entry, attribute)
575 return self._untagged_response(typ, dat, 'ANNOTATION')
576
577
578 def getquota(self, root):
579 """Get the quota root's resource usage and limits.
580
581 Part of the IMAP4 QUOTA extension defined in rfc2087.
582
583 (typ, [data]) = <instance>.getquota(root)
584 """
585 typ, dat = self._simple_command('GETQUOTA', root)
586 return self._untagged_response(typ, dat, 'QUOTA')
587
588
589 def getquotaroot(self, mailbox):
590 """Get the list of quota roots for the named mailbox.
591
592 (typ, [[QUOTAROOT responses...], [QUOTA responses]]) = <instance>.getquotaroot(mailbox)
593 """
594 typ, dat = self._simple_command('GETQUOTAROOT', mailbox)
595 typ, quota = self._untagged_response(typ, dat, 'QUOTA')
596 typ, quotaroot = self._untagged_response(typ, dat, 'QUOTAROOT')
597 return typ, [quotaroot, quota]
598
599
600 def list(self, directory='""', pattern='*'):
601 """List mailbox names in directory matching pattern.
602
603 (typ, [data]) = <instance>.list(directory='""', pattern='*')
604
605 'data' is list of LIST responses.
606 """
607 name = 'LIST'
608 typ, dat = self._simple_command(name, directory, pattern)
609 return self._untagged_response(typ, dat, name)
610
611
612 def login(self, user, password):
613 """Identify client using plaintext password.
614
615 (typ, [data]) = <instance>.login(user, password)
616
617 NB: 'password' will be quoted.
618 """
619 typ, dat = self._simple_command('LOGIN', user, self._quote(password))
620 if typ != 'OK':
621 raise self.error(dat[-1])
622 self.state = 'AUTH'
623 return typ, dat
624
625
626 def login_cram_md5(self, user, password):
627 """ Force use of CRAM-MD5 authentication.
628
629 (typ, [data]) = <instance>.login_cram_md5(user, password)
630 """
631 self.user, self.password = user, password
632 return self.authenticate('CRAM-MD5', self._CRAM_MD5_AUTH)
633
634
635 def _CRAM_MD5_AUTH(self, challenge):
636 """ Authobject to use with CRAM-MD5 authentication. """
637 import hmac
638 pwd = (self.password.encode('utf-8') if isinstance(self.password, str)
639 else self.password)
640 return self.user + " " + hmac.HMAC(pwd, challenge, 'md5').hexdigest()
641
642
643 def logout(self):
644 """Shutdown connection to server.
645
646 (typ, [data]) = <instance>.logout()
647
648 Returns server 'BYE' response.
649 """
650 self.state = 'LOGOUT'
651 typ, dat = self._simple_command('LOGOUT')
652 self.shutdown()
653 return typ, dat
654
655
656 def lsub(self, directory='""', pattern='*'):
657 """List 'subscribed' mailbox names in directory matching pattern.
658
659 (typ, [data, ...]) = <instance>.lsub(directory='""', pattern='*')
660
661 'data' are tuples of message part envelope and data.
662 """
663 name = 'LSUB'
664 typ, dat = self._simple_command(name, directory, pattern)
665 return self._untagged_response(typ, dat, name)
666
667 def myrights(self, mailbox):
668 """Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
669
670 (typ, [data]) = <instance>.myrights(mailbox)
671 """
672 typ,dat = self._simple_command('MYRIGHTS', mailbox)
673 return self._untagged_response(typ, dat, 'MYRIGHTS')
674
675 def namespace(self):
676 """ Returns IMAP namespaces ala rfc2342
677
678 (typ, [data, ...]) = <instance>.namespace()
679 """
680 name = 'NAMESPACE'
681 typ, dat = self._simple_command(name)
682 return self._untagged_response(typ, dat, name)
683
684
685 def noop(self):
686 """Send NOOP command.
687
688 (typ, [data]) = <instance>.noop()
689 """
690 if __debug__:
691 if self.debug >= 3:
692 self._dump_ur(self.untagged_responses)
693 return self._simple_command('NOOP')
694
695
696 def partial(self, message_num, message_part, start, length):
697 """Fetch truncated part of a message.
698
699 (typ, [data, ...]) = <instance>.partial(message_num, message_part, start, length)
700
701 'data' is tuple of message part envelope and data.
702 """
703 name = 'PARTIAL'
704 typ, dat = self._simple_command(name, message_num, message_part, start, length)
705 return self._untagged_response(typ, dat, 'FETCH')
706
707
708 def proxyauth(self, user):
709 """Assume authentication as "user".
710
711 Allows an authorised administrator to proxy into any user's
712 mailbox.
713
714 (typ, [data]) = <instance>.proxyauth(user)
715 """
716
717 name = 'PROXYAUTH'
718 return self._simple_command('PROXYAUTH', user)
719
720
721 def rename(self, oldmailbox, newmailbox):
722 """Rename old mailbox name to new.
723
724 (typ, [data]) = <instance>.rename(oldmailbox, newmailbox)
725 """
726 return self._simple_command('RENAME', oldmailbox, newmailbox)
727
728
729 def search(self, charset, *criteria):
730 """Search mailbox for matching messages.
731
732 (typ, [data]) = <instance>.search(charset, criterion, ...)
733
734 'data' is space separated list of matching message numbers.
735 If UTF8 is enabled, charset MUST be None.
736 """
737 name = 'SEARCH'
738 if charset:
739 if self.utf8_enabled:
740 raise IMAP4.error("Non-None charset not valid in UTF8 mode")
741 typ, dat = self._simple_command(name, 'CHARSET', charset, *criteria)
742 else:
743 typ, dat = self._simple_command(name, *criteria)
744 return self._untagged_response(typ, dat, name)
745
746
747 def select(self, mailbox='INBOX', readonly=False):
748 """Select a mailbox.
749
750 Flush all untagged responses.
751
752 (typ, [data]) = <instance>.select(mailbox='INBOX', readonly=False)
753
754 'data' is count of messages in mailbox ('EXISTS' response).
755
756 Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so
757 other responses should be obtained via <instance>.response('FLAGS') etc.
758 """
759 self.untagged_responses = {} # Flush old responses.
760 self.is_readonly = readonly
761 if readonly:
762 name = 'EXAMINE'
763 else:
764 name = 'SELECT'
765 typ, dat = self._simple_command(name, mailbox)
766 if typ != 'OK':
767 self.state = 'AUTH' # Might have been 'SELECTED'
768 return typ, dat
769 self.state = 'SELECTED'
770 if 'READ-ONLY' in self.untagged_responses \
771 and not readonly:
772 if __debug__:
773 if self.debug >= 1:
774 self._dump_ur(self.untagged_responses)
775 raise self.readonly('%s is not writable' % mailbox)
776 return typ, self.untagged_responses.get('EXISTS', [None])
777
778
779 def setacl(self, mailbox, who, what):
780 """Set a mailbox acl.
781
782 (typ, [data]) = <instance>.setacl(mailbox, who, what)
783 """
784 return self._simple_command('SETACL', mailbox, who, what)
785
786
787 def setannotation(self, *args):
788 """(typ, [data]) = <instance>.setannotation(mailbox[, entry, attribute]+)
789 Set ANNOTATIONs."""
790
791 typ, dat = self._simple_command('SETANNOTATION', *args)
792 return self._untagged_response(typ, dat, 'ANNOTATION')
793
794
795 def setquota(self, root, limits):
796 """Set the quota root's resource limits.
797
798 (typ, [data]) = <instance>.setquota(root, limits)
799 """
800 typ, dat = self._simple_command('SETQUOTA', root, limits)
801 return self._untagged_response(typ, dat, 'QUOTA')
802
803
804 def sort(self, sort_criteria, charset, *search_criteria):
805 """IMAP4rev1 extension SORT command.
806
807 (typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...)
808 """
809 name = 'SORT'
810 #if not name in self.capabilities: # Let the server decide!
811 # raise self.error('unimplemented extension command: %s' % name)
812 if (sort_criteria[0],sort_criteria[-1]) != ('(',')'):
813 sort_criteria = '(%s)' % sort_criteria
814 typ, dat = self._simple_command(name, sort_criteria, charset, *search_criteria)
815 return self._untagged_response(typ, dat, name)
816
817
818 def starttls(self, ssl_context=None):
819 name = 'STARTTLS'
820 if not HAVE_SSL:
821 raise self.error('SSL support missing')
822 if self._tls_established:
823 raise self.abort('TLS session already established')
824 if name not in self.capabilities:
825 raise self.abort('TLS not supported by server')
826 # Generate a default SSL context if none was passed.
827 if ssl_context is None:
828 ssl_context = ssl._create_stdlib_context()
829 typ, dat = self._simple_command(name)
830 if typ == 'OK':
831 self.sock = ssl_context.wrap_socket(self.sock,
832 server_hostname=self.host)
833 self.file = self.sock.makefile('rb')
834 self._tls_established = True
835 self._get_capabilities()
836 else:
837 raise self.error("Couldn't establish TLS session")
838 return self._untagged_response(typ, dat, name)
839
840
841 def status(self, mailbox, names):
842 """Request named status conditions for mailbox.
843
844 (typ, [data]) = <instance>.status(mailbox, names)
845 """
846 name = 'STATUS'
847 #if self.PROTOCOL_VERSION == 'IMAP4': # Let the server decide!
848 # raise self.error('%s unimplemented in IMAP4 (obtain IMAP4rev1 server, or re-code)' % name)
849 typ, dat = self._simple_command(name, mailbox, names)
850 return self._untagged_response(typ, dat, name)
851
852
853 def store(self, message_set, command, flags):
854 """Alters flag dispositions for messages in mailbox.
855
856 (typ, [data]) = <instance>.store(message_set, command, flags)
857 """
858 if (flags[0],flags[-1]) != ('(',')'):
859 flags = '(%s)' % flags # Avoid quoting the flags
860 typ, dat = self._simple_command('STORE', message_set, command, flags)
861 return self._untagged_response(typ, dat, 'FETCH')
862
863
864 def subscribe(self, mailbox):
865 """Subscribe to new mailbox.
866
867 (typ, [data]) = <instance>.subscribe(mailbox)
868 """
869 return self._simple_command('SUBSCRIBE', mailbox)
870
871
872 def thread(self, threading_algorithm, charset, *search_criteria):
873 """IMAPrev1 extension THREAD command.
874
875 (type, [data]) = <instance>.thread(threading_algorithm, charset, search_criteria, ...)
876 """
877 name = 'THREAD'
878 typ, dat = self._simple_command(name, threading_algorithm, charset, *search_criteria)
879 return self._untagged_response(typ, dat, name)
880
881
882 def uid(self, command, *args):
883 """Execute "command arg ..." with messages identified by UID,
884 rather than message number.
885
886 (typ, [data]) = <instance>.uid(command, arg1, arg2, ...)
887
888 Returns response appropriate to 'command'.
889 """
890 command = command.upper()
891 if not command in Commands:
892 raise self.error("Unknown IMAP4 UID command: %s" % command)
893 if self.state not in Commands[command]:
894 raise self.error("command %s illegal in state %s, "
895 "only allowed in states %s" %
896 (command, self.state,
897 ', '.join(Commands[command])))
898 name = 'UID'
899 typ, dat = self._simple_command(name, command, *args)
900 if command in ('SEARCH', 'SORT', 'THREAD'):
901 name = command
902 else:
903 name = 'FETCH'
904 return self._untagged_response(typ, dat, name)
905
906
907 def unsubscribe(self, mailbox):
908 """Unsubscribe from old mailbox.
909
910 (typ, [data]) = <instance>.unsubscribe(mailbox)
911 """
912 return self._simple_command('UNSUBSCRIBE', mailbox)
913
914
915 def unselect(self):
916 """Free server's resources associated with the selected mailbox
917 and returns the server to the authenticated state.
918 This command performs the same actions as CLOSE, except
919 that no messages are permanently removed from the currently
920 selected mailbox.
921
922 (typ, [data]) = <instance>.unselect()
923 """
924 try:
925 typ, data = self._simple_command('UNSELECT')
926 finally:
927 self.state = 'AUTH'
928 return typ, data
929
930
931 def xatom(self, name, *args):
932 """Allow simple extension commands
933 notified by server in CAPABILITY response.
934
935 Assumes command is legal in current state.
936
937 (typ, [data]) = <instance>.xatom(name, arg, ...)
938
939 Returns response appropriate to extension command `name'.
940 """
941 name = name.upper()
942 #if not name in self.capabilities: # Let the server decide!
943 # raise self.error('unknown extension command: %s' % name)
944 if not name in Commands:
945 Commands[name] = (self.state,)
946 return self._simple_command(name, *args)
947
948
949
950 # Private methods
951
952
953 def _append_untagged(self, typ, dat):
954 if dat is None:
955 dat = b''
956 ur = self.untagged_responses
957 if __debug__:
958 if self.debug >= 5:
959 self._mesg('untagged_responses[%s] %s += ["%r"]' %
960 (typ, len(ur.get(typ,'')), dat))
961 if typ in ur:
962 ur[typ].append(dat)
963 else:
964 ur[typ] = [dat]
965
966
967 def _check_bye(self):
968 bye = self.untagged_responses.get('BYE')
969 if bye:
970 raise self.abort(bye[-1].decode(self._encoding, 'replace'))
971
972
973 def _command(self, name, *args):
974
975 if self.state not in Commands[name]:
976 self.literal = None
977 raise self.error("command %s illegal in state %s, "
978 "only allowed in states %s" %
979 (name, self.state,
980 ', '.join(Commands[name])))
981
982 for typ in ('OK', 'NO', 'BAD'):
983 if typ in self.untagged_responses:
984 del self.untagged_responses[typ]
985
986 if 'READ-ONLY' in self.untagged_responses \
987 and not self.is_readonly:
988 raise self.readonly('mailbox status changed to READ-ONLY')
989
990 tag = self._new_tag()
991 name = bytes(name, self._encoding)
992 data = tag + b' ' + name
993 for arg in args:
994 if arg is None: continue
995 if isinstance(arg, str):
996 arg = bytes(arg, self._encoding)
997 data = data + b' ' + arg
998
999 literal = self.literal
1000 if literal is not None:
1001 self.literal = None
1002 if type(literal) is type(self._command):
1003 literator = literal
1004 else:
1005 literator = None
1006 data = data + bytes(' {%s}' % len(literal), self._encoding)
1007
1008 if __debug__:
1009 if self.debug >= 4:
1010 self._mesg('> %r' % data)
1011 else:
1012 self._log('> %r' % data)
1013
1014 try:
1015 self.send(data + CRLF)
1016 except OSError as val:
1017 raise self.abort('socket error: %s' % val)
1018
1019 if literal is None:
1020 return tag
1021
1022 while 1:
1023 # Wait for continuation response
1024
1025 while self._get_response():
1026 if self.tagged_commands[tag]: # BAD/NO?
1027 return tag
1028
1029 # Send literal
1030
1031 if literator:
1032 literal = literator(self.continuation_response)
1033
1034 if __debug__:
1035 if self.debug >= 4:
1036 self._mesg('write literal size %s' % len(literal))
1037
1038 try:
1039 self.send(literal)
1040 self.send(CRLF)
1041 except OSError as val:
1042 raise self.abort('socket error: %s' % val)
1043
1044 if not literator:
1045 break
1046
1047 return tag
1048
1049
1050 def _command_complete(self, name, tag):
1051 logout = (name == 'LOGOUT')
1052 # BYE is expected after LOGOUT
1053 if not logout:
1054 self._check_bye()
1055 try:
1056 typ, data = self._get_tagged_response(tag, expect_bye=logout)
1057 except self.abort as val:
1058 raise self.abort('command: %s => %s' % (name, val))
1059 except self.error as val:
1060 raise self.error('command: %s => %s' % (name, val))
1061 if not logout:
1062 self._check_bye()
1063 if typ == 'BAD':
1064 raise self.error('%s command error: %s %s' % (name, typ, data))
1065 return typ, data
1066
1067
1068 def _get_capabilities(self):
1069 typ, dat = self.capability()
1070 if dat == [None]:
1071 raise self.error('no CAPABILITY response from server')
1072 dat = str(dat[-1], self._encoding)
1073 dat = dat.upper()
1074 self.capabilities = tuple(dat.split())
1075
1076
1077 def _get_response(self):
1078
1079 # Read response and store.
1080 #
1081 # Returns None for continuation responses,
1082 # otherwise first response line received.
1083
1084 resp = self._get_line()
1085
1086 # Command completion response?
1087
1088 if self._match(self.tagre, resp):
1089 tag = self.mo.group('tag')
1090 if not tag in self.tagged_commands:
1091 raise self.abort('unexpected tagged response: %r' % resp)
1092
1093 typ = self.mo.group('type')
1094 typ = str(typ, self._encoding)
1095 dat = self.mo.group('data')
1096 self.tagged_commands[tag] = (typ, [dat])
1097 else:
1098 dat2 = None
1099
1100 # '*' (untagged) responses?
1101
1102 if not self._match(Untagged_response, resp):
1103 if self._match(self.Untagged_status, resp):
1104 dat2 = self.mo.group('data2')
1105
1106 if self.mo is None:
1107 # Only other possibility is '+' (continuation) response...
1108
1109 if self._match(Continuation, resp):
1110 self.continuation_response = self.mo.group('data')
1111 return None # NB: indicates continuation
1112
1113 raise self.abort("unexpected response: %r" % resp)
1114
1115 typ = self.mo.group('type')
1116 typ = str(typ, self._encoding)
1117 dat = self.mo.group('data')
1118 if dat is None: dat = b'' # Null untagged response
1119 if dat2: dat = dat + b' ' + dat2
1120
1121 # Is there a literal to come?
1122
1123 while self._match(self.Literal, dat):
1124
1125 # Read literal direct from connection.
1126
1127 size = int(self.mo.group('size'))
1128 if __debug__:
1129 if self.debug >= 4:
1130 self._mesg('read literal size %s' % size)
1131 data = self.read(size)
1132
1133 # Store response with literal as tuple
1134
1135 self._append_untagged(typ, (dat, data))
1136
1137 # Read trailer - possibly containing another literal
1138
1139 dat = self._get_line()
1140
1141 self._append_untagged(typ, dat)
1142
1143 # Bracketed response information?
1144
1145 if typ in ('OK', 'NO', 'BAD') and self._match(Response_code, dat):
1146 typ = self.mo.group('type')
1147 typ = str(typ, self._encoding)
1148 self._append_untagged(typ, self.mo.group('data'))
1149
1150 if __debug__:
1151 if self.debug >= 1 and typ in ('NO', 'BAD', 'BYE'):
1152 self._mesg('%s response: %r' % (typ, dat))
1153
1154 return resp
1155
1156
1157 def _get_tagged_response(self, tag, expect_bye=False):
1158
1159 while 1:
1160 result = self.tagged_commands[tag]
1161 if result is not None:
1162 del self.tagged_commands[tag]
1163 return result
1164
1165 if expect_bye:
1166 typ = 'BYE'
1167 bye = self.untagged_responses.pop(typ, None)
1168 if bye is not None:
1169 # Server replies to the "LOGOUT" command with "BYE"
1170 return (typ, bye)
1171
1172 # If we've seen a BYE at this point, the socket will be
1173 # closed, so report the BYE now.
1174 self._check_bye()
1175
1176 # Some have reported "unexpected response" exceptions.
1177 # Note that ignoring them here causes loops.
1178 # Instead, send me details of the unexpected response and
1179 # I'll update the code in `_get_response()'.
1180
1181 try:
1182 self._get_response()
1183 except self.abort as val:
1184 if __debug__:
1185 if self.debug >= 1:
1186 self.print_log()
1187 raise
1188
1189
1190 def _get_line(self):
1191
1192 line = self.readline()
1193 if not line:
1194 raise self.abort('socket error: EOF')
1195
1196 # Protocol mandates all lines terminated by CRLF
1197 if not line.endswith(b'\r\n'):
1198 raise self.abort('socket error: unterminated line: %r' % line)
1199
1200 line = line[:-2]
1201 if __debug__:
1202 if self.debug >= 4:
1203 self._mesg('< %r' % line)
1204 else:
1205 self._log('< %r' % line)
1206 return line
1207
1208
1209 def _match(self, cre, s):
1210
1211 # Run compiled regular expression match method on 's'.
1212 # Save result, return success.
1213
1214 self.mo = cre.match(s)
1215 if __debug__:
1216 if self.mo is not None and self.debug >= 5:
1217 self._mesg("\tmatched %r => %r" % (cre.pattern, self.mo.groups()))
1218 return self.mo is not None
1219
1220
1221 def _new_tag(self):
1222
1223 tag = self.tagpre + bytes(str(self.tagnum), self._encoding)
1224 self.tagnum = self.tagnum + 1
1225 self.tagged_commands[tag] = None
1226 return tag
1227
1228
1229 def _quote(self, arg):
1230
1231 arg = arg.replace('\\', '\\\\')
1232 arg = arg.replace('"', '\\"')
1233
1234 return '"' + arg + '"'
1235
1236
1237 def _simple_command(self, name, *args):
1238
1239 return self._command_complete(name, self._command(name, *args))
1240
1241
1242 def _untagged_response(self, typ, dat, name):
1243 if typ == 'NO':
1244 return typ, dat
1245 if not name in self.untagged_responses:
1246 return typ, [None]
1247 data = self.untagged_responses.pop(name)
1248 if __debug__:
1249 if self.debug >= 5:
1250 self._mesg('untagged_responses[%s] => %s' % (name, data))
1251 return typ, data
1252
1253
1254 if __debug__:
1255
1256 def _mesg(self, s, secs=None):
1257 if secs is None:
1258 secs = time.time()
1259 tm = time.strftime('%M:%S', time.localtime(secs))
1260 sys.stderr.write(' %s.%02d %s\n' % (tm, (secs*100)%100, s))
1261 sys.stderr.flush()
1262
1263 def _dump_ur(self, untagged_resp_dict):
1264 if not untagged_resp_dict:
1265 return
1266 items = (f'{key}: {value!r}'
1267 for key, value in untagged_resp_dict.items())
1268 self._mesg('untagged responses dump:' + '\n\t\t'.join(items))
1269
1270 def _log(self, line):
1271 # Keep log of last `_cmd_log_len' interactions for debugging.
1272 self._cmd_log[self._cmd_log_idx] = (line, time.time())
1273 self._cmd_log_idx += 1
1274 if self._cmd_log_idx >= self._cmd_log_len:
1275 self._cmd_log_idx = 0
1276
1277 def print_log(self):
1278 self._mesg('last %d IMAP4 interactions:' % len(self._cmd_log))
1279 i, n = self._cmd_log_idx, self._cmd_log_len
1280 while n:
1281 try:
1282 self._mesg(*self._cmd_log[i])
1283 except:
1284 pass
1285 i += 1
1286 if i >= self._cmd_log_len:
1287 i = 0
1288 n -= 1
1289
1290
1291 if HAVE_SSL:
1292
1293 class IMAP4_SSL(IMAP4):
1294
1295 """IMAP4 client class over SSL connection
1296
1297 Instantiate with: IMAP4_SSL([host[, port[, keyfile[, certfile[, ssl_context[, timeout=None]]]]]])
1298
1299 host - host's name (default: localhost);
1300 port - port number (default: standard IMAP4 SSL port);
1301 keyfile - PEM formatted file that contains your private key (default: None);
1302 certfile - PEM formatted certificate chain file (default: None);
1303 ssl_context - a SSLContext object that contains your certificate chain
1304 and private key (default: None)
1305 Note: if ssl_context is provided, then parameters keyfile or
1306 certfile should not be set otherwise ValueError is raised.
1307 timeout - socket timeout (default: None) If timeout is not given or is None,
1308 the global default socket timeout is used
1309
1310 for more documentation see the docstring of the parent class IMAP4.
1311 """
1312
1313
1314 def __init__(self, host='', port=IMAP4_SSL_PORT, keyfile=None,
1315 certfile=None, ssl_context=None, timeout=None):
1316 if ssl_context is not None and keyfile is not None:
1317 raise ValueError("ssl_context and keyfile arguments are mutually "
1318 "exclusive")
1319 if ssl_context is not None and certfile is not None:
1320 raise ValueError("ssl_context and certfile arguments are mutually "
1321 "exclusive")
1322 if keyfile is not None or certfile is not None:
1323 import warnings
1324 warnings.warn("keyfile and certfile are deprecated, use a "
1325 "custom ssl_context instead", DeprecationWarning, 2)
1326 self.keyfile = keyfile
1327 self.certfile = certfile
1328 if ssl_context is None:
1329 ssl_context = ssl._create_stdlib_context(certfile=certfile,
1330 keyfile=keyfile)
1331 self.ssl_context = ssl_context
1332 IMAP4.__init__(self, host, port, timeout)
1333
1334 def _create_socket(self, timeout):
1335 sock = IMAP4._create_socket(self, timeout)
1336 return self.ssl_context.wrap_socket(sock,
1337 server_hostname=self.host)
1338
1339 def open(self, host='', port=IMAP4_SSL_PORT, timeout=None):
1340 """Setup connection to remote server on "host:port".
1341 (default: localhost:standard IMAP4 SSL port).
1342 This connection will be used by the routines:
1343 read, readline, send, shutdown.
1344 """
1345 IMAP4.open(self, host, port, timeout)
1346
1347 __all__.append("IMAP4_SSL")
1348
1349
1350 class IMAP4_stream(IMAP4):
1351
1352 """IMAP4 client class over a stream
1353
1354 Instantiate with: IMAP4_stream(command)
1355
1356 "command" - a string that can be passed to subprocess.Popen()
1357
1358 for more documentation see the docstring of the parent class IMAP4.
1359 """
1360
1361
1362 def __init__(self, command):
1363 self.command = command
1364 IMAP4.__init__(self)
1365
1366
1367 def open(self, host=None, port=None, timeout=None):
1368 """Setup a stream connection.
1369 This connection will be used by the routines:
1370 read, readline, send, shutdown.
1371 """
1372 self.host = None # For compatibility with parent class
1373 self.port = None
1374 self.sock = None
1375 self.file = None
1376 self.process = subprocess.Popen(self.command,
1377 bufsize=DEFAULT_BUFFER_SIZE,
1378 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1379 shell=True, close_fds=True)
1380 self.writefile = self.process.stdin
1381 self.readfile = self.process.stdout
1382
1383 def read(self, size):
1384 """Read 'size' bytes from remote."""
1385 return self.readfile.read(size)
1386
1387
1388 def readline(self):
1389 """Read line from remote."""
1390 return self.readfile.readline()
1391
1392
1393 def send(self, data):
1394 """Send data to remote."""
1395 self.writefile.write(data)
1396 self.writefile.flush()
1397
1398
1399 def shutdown(self):
1400 """Close I/O established in "open"."""
1401 self.readfile.close()
1402 self.writefile.close()
1403 self.process.wait()
1404
1405
1406
1407 class _Authenticator:
1408
1409 """Private class to provide en/decoding
1410 for base64-based authentication conversation.
1411 """
1412
1413 def __init__(self, mechinst):
1414 self.mech = mechinst # Callable object to provide/process data
1415
1416 def process(self, data):
1417 ret = self.mech(self.decode(data))
1418 if ret is None:
1419 return b'*' # Abort conversation
1420 return self.encode(ret)
1421
1422 def encode(self, inp):
1423 #
1424 # Invoke binascii.b2a_base64 iteratively with
1425 # short even length buffers, strip the trailing
1426 # line feed from the result and append. "Even"
1427 # means a number that factors to both 6 and 8,
1428 # so when it gets to the end of the 8-bit input
1429 # there's no partial 6-bit output.
1430 #
1431 oup = b''
1432 if isinstance(inp, str):
1433 inp = inp.encode('utf-8')
1434 while inp:
1435 if len(inp) > 48:
1436 t = inp[:48]
1437 inp = inp[48:]
1438 else:
1439 t = inp
1440 inp = b''
1441 e = binascii.b2a_base64(t)
1442 if e:
1443 oup = oup + e[:-1]
1444 return oup
1445
1446 def decode(self, inp):
1447 if not inp:
1448 return b''
1449 return binascii.a2b_base64(inp)
1450
1451 Months = ' Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ')
1452 Mon2num = {s.encode():n+1 for n, s in enumerate(Months[1:])}
1453
1454 def Internaldate2tuple(resp):
1455 """Parse an IMAP4 INTERNALDATE string.
1456
1457 Return corresponding local time. The return value is a
1458 time.struct_time tuple or None if the string has wrong format.
1459 """
1460
1461 mo = InternalDate.match(resp)
1462 if not mo:
1463 return None
1464
1465 mon = Mon2num[mo.group('mon')]
1466 zonen = mo.group('zonen')
1467
1468 day = int(mo.group('day'))
1469 year = int(mo.group('year'))
1470 hour = int(mo.group('hour'))
1471 min = int(mo.group('min'))
1472 sec = int(mo.group('sec'))
1473 zoneh = int(mo.group('zoneh'))
1474 zonem = int(mo.group('zonem'))
1475
1476 # INTERNALDATE timezone must be subtracted to get UT
1477
1478 zone = (zoneh*60 + zonem)*60
1479 if zonen == b'-':
1480 zone = -zone
1481
1482 tt = (year, mon, day, hour, min, sec, -1, -1, -1)
1483 utc = calendar.timegm(tt) - zone
1484
1485 return time.localtime(utc)
1486
1487
1488
1489 def Int2AP(num):
1490
1491 """Convert integer to A-P string representation."""
1492
1493 val = b''; AP = b'ABCDEFGHIJKLMNOP'
1494 num = int(abs(num))
1495 while num:
1496 num, mod = divmod(num, 16)
1497 val = AP[mod:mod+1] + val
1498 return val
1499
1500
1501
1502 def ParseFlags(resp):
1503
1504 """Convert IMAP4 flags response to python tuple."""
1505
1506 mo = Flags.match(resp)
1507 if not mo:
1508 return ()
1509
1510 return tuple(mo.group('flags').split())
1511
1512
1513 def Time2Internaldate(date_time):
1514
1515 """Convert date_time to IMAP4 INTERNALDATE representation.
1516
1517 Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'. The
1518 date_time argument can be a number (int or float) representing
1519 seconds since epoch (as returned by time.time()), a 9-tuple
1520 representing local time, an instance of time.struct_time (as
1521 returned by time.localtime()), an aware datetime instance or a
1522 double-quoted string. In the last case, it is assumed to already
1523 be in the correct format.
1524 """
1525 if isinstance(date_time, (int, float)):
1526 dt = datetime.fromtimestamp(date_time,
1527 timezone.utc).astimezone()
1528 elif isinstance(date_time, tuple):
1529 try:
1530 gmtoff = date_time.tm_gmtoff
1531 except AttributeError:
1532 if time.daylight:
1533 dst = date_time[8]
1534 if dst == -1:
1535 dst = time.localtime(time.mktime(date_time))[8]
1536 gmtoff = -(time.timezone, time.altzone)[dst]
1537 else:
1538 gmtoff = -time.timezone
1539 delta = timedelta(seconds=gmtoff)
1540 dt = datetime(*date_time[:6], tzinfo=timezone(delta))
1541 elif isinstance(date_time, datetime):
1542 if date_time.tzinfo is None:
1543 raise ValueError("date_time must be aware")
1544 dt = date_time
1545 elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'):
1546 return date_time # Assume in correct format
1547 else:
1548 raise ValueError("date_time not of a known type")
1549 fmt = '"%d-{}-%Y %H:%M:%S %z"'.format(Months[dt.month])
1550 return dt.strftime(fmt)
1551
1552
1553
1554 if __name__ == '__main__':
1555
1556 # To test: invoke either as 'python imaplib.py [IMAP4_server_hostname]'
1557 # or 'python imaplib.py -s "rsh IMAP4_server_hostname exec /etc/rimapd"'
1558 # to test the IMAP4_stream class
1559
1560 import getopt, getpass
1561
1562 try:
1563 optlist, args = getopt.getopt(sys.argv[1:], 'd:s:')
1564 except getopt.error as val:
1565 optlist, args = (), ()
1566
1567 stream_command = None
1568 for opt,val in optlist:
1569 if opt == '-d':
1570 Debug = int(val)
1571 elif opt == '-s':
1572 stream_command = val
1573 if not args: args = (stream_command,)
1574
1575 if not args: args = ('',)
1576
1577 host = args[0]
1578
1579 USER = getpass.getuser()
1580 PASSWD = getpass.getpass("IMAP password for %s on %s: " % (USER, host or "localhost"))
1581
1582 test_mesg = 'From: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)sdata...%(lf)s' % {'user':USER, 'lf':'\n'}
1583 test_seq1 = (
1584 ('login', (USER, PASSWD)),
1585 ('create', ('/tmp/xxx 1',)),
1586 ('rename', ('/tmp/xxx 1', '/tmp/yyy')),
1587 ('CREATE', ('/tmp/yyz 2',)),
1588 ('append', ('/tmp/yyz 2', None, None, test_mesg)),
1589 ('list', ('/tmp', 'yy*')),
1590 ('select', ('/tmp/yyz 2',)),
1591 ('search', (None, 'SUBJECT', 'test')),
1592 ('fetch', ('1', '(FLAGS INTERNALDATE RFC822)')),
1593 ('store', ('1', 'FLAGS', r'(\Deleted)')),
1594 ('namespace', ()),
1595 ('expunge', ()),
1596 ('recent', ()),
1597 ('close', ()),
1598 )
1599
1600 test_seq2 = (
1601 ('select', ()),
1602 ('response',('UIDVALIDITY',)),
1603 ('uid', ('SEARCH', 'ALL')),
1604 ('response', ('EXISTS',)),
1605 ('append', (None, None, None, test_mesg)),
1606 ('recent', ()),
1607 ('logout', ()),
1608 )
1609
1610 def run(cmd, args):
1611 M._mesg('%s %s' % (cmd, args))
1612 typ, dat = getattr(M, cmd)(*args)
1613 M._mesg('%s => %s %s' % (cmd, typ, dat))
1614 if typ == 'NO': raise dat[0]
1615 return dat
1616
1617 try:
1618 if stream_command:
1619 M = IMAP4_stream(stream_command)
1620 else:
1621 M = IMAP4(host)
1622 if M.state == 'AUTH':
1623 test_seq1 = test_seq1[1:] # Login not needed
1624 M._mesg('PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION)
1625 M._mesg('CAPABILITIES = %r' % (M.capabilities,))
1626
1627 for cmd,args in test_seq1:
1628 run(cmd, args)
1629
1630 for ml in run('list', ('/tmp/', 'yy%')):
1631 mo = re.match(r'.*"([^"]+)"$', ml)
1632 if mo: path = mo.group(1)
1633 else: path = ml.split()[-1]
1634 run('delete', (path,))
1635
1636 for cmd,args in test_seq2:
1637 dat = run(cmd, args)
1638
1639 if (cmd,args) != ('uid', ('SEARCH', 'ALL')):
1640 continue
1641
1642 uid = dat[-1].split()
1643 if not uid: continue
1644 run('uid', ('FETCH', '%s' % uid[-1],
1645 '(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)'))
1646
1647 print('\nAll tests OK.')
1648
1649 except:
1650 print('\nTests failed.')
1651
1652 if not Debug:
1653 print('''
1654 If you would like to see debugging output,
1655 try: %s -d5
1656 ''' % sys.argv[0])
1657
1658 raise