IMAPClient 4.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2080 @@
1
+ # Copyright (c) 2015, Menno Smits
2
+ # Released subject to the New BSD License
3
+ # Please see http://en.wikipedia.org/wiki/BSD_licenses
4
+
5
+ import dataclasses
6
+ import functools
7
+ import imaplib
8
+ import itertools
9
+ import re
10
+ import select
11
+ import socket
12
+ import ssl as ssl_lib
13
+ import sys
14
+ import warnings
15
+ from datetime import date, datetime
16
+ from logging import getLogger, LoggerAdapter
17
+ from operator import itemgetter
18
+ from typing import List, Optional
19
+
20
+ from . import exceptions, imap4, response_lexer, tls
21
+ from .datetime_util import datetime_to_INTERNALDATE, format_criteria_date
22
+ from .imap_utf7 import decode as decode_utf7
23
+ from .imap_utf7 import encode as encode_utf7
24
+ from .response_parser import parse_fetch_response, parse_message_list, parse_response
25
+ from .util import assert_imap_protocol, chunk, to_bytes, to_ints, to_unicode
26
+
27
+ if hasattr(select, "poll"):
28
+ POLL_SUPPORT = True
29
+ else:
30
+ # Fallback to select() on systems that don't support poll()
31
+ POLL_SUPPORT = False
32
+
33
+
34
+ logger = getLogger(__name__)
35
+
36
+ __all__ = [
37
+ "IMAPClient",
38
+ "SocketTimeout",
39
+ "DELETED",
40
+ "SEEN",
41
+ "ANSWERED",
42
+ "FLAGGED",
43
+ "DRAFT",
44
+ "RECENT",
45
+ ]
46
+
47
+
48
+ # We also offer the gmail-specific XLIST command...
49
+ if "XLIST" not in imaplib.Commands:
50
+ imaplib.Commands["XLIST"] = ("NONAUTH", "AUTH", "SELECTED")
51
+
52
+ # ...and IDLE
53
+ if "IDLE" not in imaplib.Commands:
54
+ imaplib.Commands["IDLE"] = ("NONAUTH", "AUTH", "SELECTED")
55
+
56
+ # ..and STARTTLS
57
+ if "STARTTLS" not in imaplib.Commands:
58
+ imaplib.Commands["STARTTLS"] = ("NONAUTH",)
59
+
60
+ # ...and ID. RFC2971 says that this command is valid in all states,
61
+ # but not that some servers (*cough* FastMail *cough*) don't seem to
62
+ # accept it in state NONAUTH.
63
+ if "ID" not in imaplib.Commands:
64
+ imaplib.Commands["ID"] = ("NONAUTH", "AUTH", "SELECTED")
65
+
66
+ # ... and UNSELECT. RFC3691 does not specify the state but there is no
67
+ # reason to use the command without AUTH state and a mailbox selected.
68
+ if "UNSELECT" not in imaplib.Commands:
69
+ imaplib.Commands["UNSELECT"] = ("AUTH", "SELECTED")
70
+
71
+ # .. and ENABLE.
72
+ if "ENABLE" not in imaplib.Commands:
73
+ imaplib.Commands["ENABLE"] = ("AUTH",)
74
+
75
+ # .. and MOVE for RFC6851.
76
+ if "MOVE" not in imaplib.Commands:
77
+ imaplib.Commands["MOVE"] = ("AUTH", "SELECTED")
78
+
79
+ # System flags
80
+ DELETED = rb"\Deleted"
81
+ SEEN = rb"\Seen"
82
+ ANSWERED = rb"\Answered"
83
+ FLAGGED = rb"\Flagged"
84
+ DRAFT = rb"\Draft"
85
+ RECENT = rb"\Recent" # This flag is read-only
86
+
87
+ # Special folders, see RFC6154
88
+ # \Flagged is omitted because it is the same as the flag defined above
89
+ ALL = rb"\All"
90
+ ARCHIVE = rb"\Archive"
91
+ DRAFTS = rb"\Drafts"
92
+ JUNK = rb"\Junk"
93
+ SENT = rb"\Sent"
94
+ TRASH = rb"\Trash"
95
+
96
+ # Personal namespaces that are common among providers
97
+ # used as a fallback when the server does not support the NAMESPACE capability
98
+ _POPULAR_PERSONAL_NAMESPACES = (("", ""), ("INBOX.", "."))
99
+
100
+ # Names of special folders that are common among providers
101
+ _POPULAR_SPECIAL_FOLDERS = {
102
+ SENT: ("Sent", "Sent Items", "Sent items", "Sent Messages"),
103
+ DRAFTS: ("Drafts",),
104
+ ARCHIVE: ("Archive",),
105
+ TRASH: ("Trash", "Deleted Items", "Deleted Messages", "Deleted"),
106
+ JUNK: ("Junk", "Spam"),
107
+ }
108
+
109
+ _RE_SELECT_RESPONSE = re.compile(rb"\[(?P<key>[A-Z-]+)( \((?P<data>.*)\))?\]")
110
+
111
+
112
+ class Namespace(tuple):
113
+ def __new__(cls, personal, other, shared):
114
+ return tuple.__new__(cls, (personal, other, shared))
115
+
116
+ personal = property(itemgetter(0))
117
+ other = property(itemgetter(1))
118
+ shared = property(itemgetter(2))
119
+
120
+
121
+ @dataclasses.dataclass
122
+ class SocketTimeout:
123
+ """Represents timeout configuration for an IMAP connection.
124
+
125
+ :ivar connect: maximum time to wait for a connection attempt to remote server
126
+ :ivar read: maximum time to wait for performing a read/write operation
127
+
128
+ As an example, ``SocketTimeout(connect=15, read=60)`` will make the socket
129
+ timeout if the connection takes more than 15 seconds to establish but
130
+ read/write operations can take up to 60 seconds once the connection is done.
131
+ """
132
+
133
+ connect: float
134
+ read: float
135
+
136
+
137
+ @dataclasses.dataclass
138
+ class MailboxQuotaRoots:
139
+ """Quota roots associated with a mailbox.
140
+
141
+ Represents the response of a GETQUOTAROOT command.
142
+
143
+ :ivar mailbox: the mailbox
144
+ :ivar quota_roots: list of quota roots associated with the mailbox
145
+ """
146
+
147
+ mailbox: str
148
+ quota_roots: List[str]
149
+
150
+
151
+ @dataclasses.dataclass
152
+ class Quota:
153
+ """Resource quota.
154
+
155
+ Represents the response of a GETQUOTA command.
156
+
157
+ :ivar quota_roots: the quota roots for which the limit apply
158
+ :ivar resource: the resource being limited (STORAGE, MESSAGES...)
159
+ :ivar usage: the current usage of the resource
160
+ :ivar limit: the maximum allowed usage of the resource
161
+ """
162
+
163
+ quota_root: str
164
+ resource: str
165
+ usage: bytes
166
+ limit: bytes
167
+
168
+
169
+ def require_capability(capability):
170
+ """Decorator raising CapabilityError when a capability is not available."""
171
+
172
+ def actual_decorator(func):
173
+ @functools.wraps(func)
174
+ def wrapper(client, *args, **kwargs):
175
+ if not client.has_capability(capability):
176
+ raise exceptions.CapabilityError(
177
+ "Server does not support {} capability".format(capability)
178
+ )
179
+ return func(client, *args, **kwargs)
180
+
181
+ return wrapper
182
+
183
+ return actual_decorator
184
+
185
+
186
+ class IMAPClient:
187
+ """A connection to the IMAP server specified by *host* is made when
188
+ this class is instantiated.
189
+
190
+ *port* defaults to 993, or 143 if *ssl* is ``False``.
191
+
192
+ If *use_uid* is ``True`` unique message UIDs be used for all calls
193
+ that accept message ids (defaults to ``True``).
194
+
195
+ If *ssl* is ``True`` (the default) a secure connection will be made.
196
+ Otherwise an insecure connection over plain text will be
197
+ established.
198
+
199
+ If *ssl* is ``True`` the optional *ssl_context* argument can be
200
+ used to provide an ``ssl.SSLContext`` instance used to
201
+ control SSL/TLS connection parameters. If this is not provided a
202
+ sensible default context will be used.
203
+
204
+ If *stream* is ``True`` then *host* is used as the command to run
205
+ to establish a connection to the IMAP server (defaults to
206
+ ``False``). This is useful for exotic connection or authentication
207
+ setups.
208
+
209
+ Use *timeout* to specify a timeout for the socket connected to the
210
+ IMAP server. The timeout can be either a float number, or an instance
211
+ of :py:class:`imapclient.SocketTimeout`.
212
+
213
+ * If a single float number is passed, the same timeout delay applies
214
+ during the initial connection to the server and for all future socket
215
+ reads and writes.
216
+
217
+ * In case of a ``SocketTimeout``, connection timeout and
218
+ read/write operations can have distinct timeouts.
219
+
220
+ * The default is ``None``, where no timeout is used.
221
+
222
+ The *normalise_times* attribute specifies whether datetimes
223
+ returned by ``fetch()`` are normalised to the local system time
224
+ and include no timezone information (native), or are datetimes
225
+ that include timezone information (aware). By default
226
+ *normalise_times* is True (times are normalised to the local
227
+ system time). This attribute can be changed between ``fetch()``
228
+ calls if required.
229
+
230
+ Can be used as a context manager to automatically close opened connections:
231
+
232
+ >>> with IMAPClient(host="imap.foo.org") as client:
233
+ ... client.login("bar@foo.org", "passwd")
234
+
235
+ """
236
+
237
+ # Those exceptions are kept for backward-compatibility, since
238
+ # previous versions included these attributes as references to
239
+ # imaplib original exceptions
240
+ Error = exceptions.IMAPClientError
241
+ AbortError = exceptions.IMAPClientAbortError
242
+ ReadOnlyError = exceptions.IMAPClientReadOnlyError
243
+
244
+ def __init__(
245
+ self,
246
+ host: str,
247
+ port: int = None,
248
+ use_uid: bool = True,
249
+ ssl: bool = True,
250
+ stream: bool = False,
251
+ ssl_context: Optional[ssl_lib.SSLContext] = None,
252
+ timeout: Optional[float] = None,
253
+ ):
254
+ if stream:
255
+ if port is not None:
256
+ raise ValueError("can't set 'port' when 'stream' True")
257
+ if ssl:
258
+ raise ValueError("can't use 'ssl' when 'stream' is True")
259
+ elif port is None:
260
+ port = ssl and 993 or 143
261
+
262
+ if ssl and port == 143:
263
+ logger.warning(
264
+ "Attempting to establish an encrypted connection "
265
+ "to a port (143) often used for unencrypted "
266
+ "connections"
267
+ )
268
+
269
+ self.host = host
270
+ self.port = port
271
+ self.ssl = ssl
272
+ self.ssl_context = ssl_context
273
+ self.stream = stream
274
+ self.use_uid = use_uid
275
+ self.folder_encode = True
276
+ self.normalise_times = True
277
+
278
+ # If the user gives a single timeout value, assume it is the same for
279
+ # connection and read/write operations
280
+ if not isinstance(timeout, SocketTimeout):
281
+ timeout = SocketTimeout(timeout, timeout)
282
+
283
+ self._timeout = timeout
284
+ self._starttls_done = False
285
+ self._cached_capabilities = None
286
+ self._idle_tag = None
287
+
288
+ self._imap = self._create_IMAP4()
289
+ logger.debug(
290
+ "Connected to host %s over %s",
291
+ self.host,
292
+ "SSL/TLS" if ssl else "plain text",
293
+ )
294
+
295
+ self._set_read_timeout()
296
+ # Small hack to make imaplib log everything to its own logger
297
+ imaplib_logger = IMAPlibLoggerAdapter(getLogger("imapclient.imaplib"), {})
298
+ self._imap.debug = 5
299
+ self._imap._mesg = imaplib_logger.debug
300
+
301
+ def __enter__(self):
302
+ return self
303
+
304
+ def __exit__(self, exc_type, exc_val, exc_tb):
305
+ """Logout and closes the connection when exiting the context manager.
306
+
307
+ All exceptions during logout and connection shutdown are caught because
308
+ an error here usually means the connection was already closed.
309
+ """
310
+ try:
311
+ self.logout()
312
+ except Exception:
313
+ try:
314
+ self.shutdown()
315
+ except Exception as e:
316
+ logger.info("Could not close the connection cleanly: %s", e)
317
+
318
+ def _create_IMAP4(self):
319
+ if self.stream:
320
+ return imaplib.IMAP4_stream(self.host)
321
+
322
+ connect_timeout = getattr(self._timeout, "connect", None)
323
+
324
+ if self.ssl:
325
+ return tls.IMAP4_TLS(
326
+ self.host,
327
+ self.port,
328
+ self.ssl_context,
329
+ connect_timeout,
330
+ )
331
+
332
+ return imap4.IMAP4WithTimeout(self.host, self.port, connect_timeout)
333
+
334
+ def _set_read_timeout(self):
335
+ if self._timeout is not None:
336
+ self.socket().settimeout(self._timeout.read)
337
+
338
+ @property
339
+ def _sock(self):
340
+ warnings.warn("_sock is deprecated. Use socket().", DeprecationWarning)
341
+ return self.socket()
342
+
343
+ def socket(self):
344
+ """Returns socket used to connect to server.
345
+
346
+ The socket is provided for polling purposes only.
347
+ It can be used in,
348
+ for example, :py:meth:`selectors.BaseSelector.register`
349
+ and :py:meth:`asyncio.loop.add_reader` to wait for data.
350
+
351
+ .. WARNING::
352
+ All other uses of the returned socket are unsupported.
353
+ This includes reading from and writing to the socket,
354
+ as they are likely to break internal bookkeeping of messages.
355
+ """
356
+ # In py2, imaplib has sslobj (for SSL connections), and sock for non-SSL.
357
+ # In the py3 version it's just sock.
358
+ return getattr(self._imap, "sslobj", self._imap.sock)
359
+
360
+ @require_capability("STARTTLS")
361
+ def starttls(self, ssl_context=None):
362
+ """Switch to an SSL encrypted connection by sending a STARTTLS command.
363
+
364
+ The *ssl_context* argument is optional and should be a
365
+ :py:class:`ssl.SSLContext` object. If no SSL context is given, a SSL
366
+ context with reasonable default settings will be used.
367
+
368
+ You can enable checking of the hostname in the certificate presented
369
+ by the server against the hostname which was used for connecting, by
370
+ setting the *check_hostname* attribute of the SSL context to ``True``.
371
+ The default SSL context has this setting enabled.
372
+
373
+ Raises :py:exc:`Error` if the SSL connection could not be established.
374
+
375
+ Raises :py:exc:`AbortError` if the server does not support STARTTLS
376
+ or an SSL connection is already established.
377
+ """
378
+ if self.ssl or self._starttls_done:
379
+ raise exceptions.IMAPClientAbortError("TLS session already established")
380
+
381
+ typ, data = self._imap._simple_command("STARTTLS")
382
+ self._checkok("starttls", typ, data)
383
+
384
+ self._starttls_done = True
385
+
386
+ self._imap.sock = tls.wrap_socket(self._imap.sock, ssl_context, self.host)
387
+ self._imap.file = self._imap.sock.makefile("rb")
388
+ return data[0]
389
+
390
+ def login(self, username: str, password: str):
391
+ """Login using *username* and *password*, returning the
392
+ server response.
393
+ """
394
+ try:
395
+ rv = self._command_and_check(
396
+ "login",
397
+ to_unicode(username),
398
+ to_unicode(password),
399
+ unpack=True,
400
+ )
401
+ except exceptions.IMAPClientError as e:
402
+ raise exceptions.LoginError(str(e))
403
+
404
+ logger.debug("Logged in as %s", username)
405
+ return rv
406
+
407
+ def oauth2_login(
408
+ self,
409
+ user: str,
410
+ access_token: str,
411
+ mech: str = "XOAUTH2",
412
+ vendor: Optional[str] = None,
413
+ ):
414
+ """Authenticate using the OAUTH2 or XOAUTH2 methods.
415
+
416
+ Gmail and Yahoo both support the 'XOAUTH2' mechanism, but Yahoo requires
417
+ the 'vendor' portion in the payload.
418
+ """
419
+ auth_string = "user=%s\1auth=Bearer %s\1" % (user, access_token)
420
+ if vendor:
421
+ auth_string += "vendor=%s\1" % vendor
422
+ auth_string += "\1"
423
+ try:
424
+ return self._command_and_check("authenticate", mech, lambda x: auth_string)
425
+ except exceptions.IMAPClientError as e:
426
+ raise exceptions.LoginError(str(e))
427
+
428
+ def oauthbearer_login(self, identity, access_token):
429
+ """Authenticate using the OAUTHBEARER method.
430
+
431
+ This is supported by Gmail and is meant to supersede the non-standard
432
+ 'OAUTH2' and 'XOAUTH2' mechanisms.
433
+ """
434
+ # https://tools.ietf.org/html/rfc5801#section-4
435
+ # Technically this is the authorization_identity, but at least for Gmail it's
436
+ # mandatory and practically behaves like the regular username/identity.
437
+ if identity:
438
+ gs2_header = "n,a=%s," % identity.replace("=", "=3D").replace(",", "=2C")
439
+ else:
440
+ gs2_header = "n,,"
441
+ # https://tools.ietf.org/html/rfc6750#section-2.1
442
+ http_authz = "Bearer %s" % access_token
443
+ # https://tools.ietf.org/html/rfc7628#section-3.1
444
+ auth_string = "%s\1auth=%s\1\1" % (gs2_header, http_authz)
445
+ try:
446
+ return self._command_and_check(
447
+ "authenticate", "OAUTHBEARER", lambda x: auth_string
448
+ )
449
+ except exceptions.IMAPClientError as e:
450
+ raise exceptions.LoginError(str(e))
451
+
452
+ def plain_login(self, identity, password, authorization_identity=None):
453
+ """Authenticate using the PLAIN method (requires server support)."""
454
+ if not authorization_identity:
455
+ authorization_identity = ""
456
+ auth_string = "%s\0%s\0%s" % (authorization_identity, identity, password)
457
+ try:
458
+ return self._command_and_check(
459
+ "authenticate", "PLAIN", lambda _: auth_string, unpack=True
460
+ )
461
+ except exceptions.IMAPClientError as e:
462
+ raise exceptions.LoginError(str(e))
463
+
464
+ def sasl_login(self, mech_name, mech_callable):
465
+ """Authenticate using a provided SASL mechanism (requires server support).
466
+
467
+ The *mech_callable* will be called with one parameter (the server
468
+ challenge as bytes) and must return the corresponding client response
469
+ (as bytes, or as string which will be automatically encoded).
470
+
471
+ It will be called as many times as the server produces challenges,
472
+ which will depend on the specific SASL mechanism. (If the mechanism is
473
+ defined as "client-first", the server will nevertheless produce a
474
+ zero-length challenge.)
475
+
476
+ For example, PLAIN has just one step with empty challenge, so a handler
477
+ might look like this::
478
+
479
+ plain_mech = lambda _: "\\0%s\\0%s" % (username, password)
480
+
481
+ imap.sasl_login("PLAIN", plain_mech)
482
+
483
+ A more complex but still stateless handler might look like this::
484
+
485
+ def example_mech(challenge):
486
+ if challenge == b"Username:"
487
+ return username.encode("utf-8")
488
+ elif challenge == b"Password:"
489
+ return password.encode("utf-8")
490
+ else:
491
+ return b""
492
+
493
+ imap.sasl_login("EXAMPLE", example_mech)
494
+
495
+ A stateful handler might look like this::
496
+
497
+ class ScramSha256SaslMechanism():
498
+ def __init__(self, username, password):
499
+ ...
500
+
501
+ def __call__(self, challenge):
502
+ self.step += 1
503
+ if self.step == 1:
504
+ response = ...
505
+ elif self.step == 2:
506
+ response = ...
507
+ return response
508
+
509
+ scram_mech = ScramSha256SaslMechanism(username, password)
510
+
511
+ imap.sasl_login("SCRAM-SHA-256", scram_mech)
512
+ """
513
+ try:
514
+ return self._command_and_check(
515
+ "authenticate", mech_name, mech_callable, unpack=True
516
+ )
517
+ except exceptions.IMAPClientError as e:
518
+ raise exceptions.LoginError(str(e))
519
+
520
+ def logout(self):
521
+ """Logout, returning the server response."""
522
+ typ, data = self._imap.logout()
523
+ self._check_resp("BYE", "logout", typ, data)
524
+ logger.debug("Logged out, connection closed")
525
+ return data[0]
526
+
527
+ def shutdown(self) -> None:
528
+ """Close the connection to the IMAP server (without logging out)
529
+
530
+ In most cases, :py:meth:`.logout` should be used instead of
531
+ this. The logout method also shutdown down the connection.
532
+ """
533
+ self._imap.shutdown()
534
+ logger.info("Connection closed")
535
+
536
+ @require_capability("ENABLE")
537
+ def enable(self, *capabilities):
538
+ """Activate one or more server side capability extensions.
539
+
540
+ Most capabilities do not need to be enabled. This is only
541
+ required for extensions which introduce backwards incompatible
542
+ behaviour. Two capabilities which may require enable are
543
+ ``CONDSTORE`` and ``UTF8=ACCEPT``.
544
+
545
+ A list of the requested extensions that were successfully
546
+ enabled on the server is returned.
547
+
548
+ Once enabled each extension remains active until the IMAP
549
+ connection is closed.
550
+
551
+ See :rfc:`5161` for more details.
552
+ """
553
+ if self._imap.state != "AUTH":
554
+ raise exceptions.IllegalStateError(
555
+ "ENABLE command illegal in state %s" % self._imap.state
556
+ )
557
+
558
+ resp = self._raw_command_untagged(
559
+ b"ENABLE",
560
+ [to_bytes(c) for c in capabilities],
561
+ uid=False,
562
+ response_name="ENABLED",
563
+ unpack=True,
564
+ )
565
+ if not resp:
566
+ return []
567
+ return resp.split()
568
+
569
+ @require_capability("ID")
570
+ def id_(self, parameters=None):
571
+ """Issue the ID command, returning a dict of server implementation
572
+ fields.
573
+
574
+ *parameters* should be specified as a dictionary of field/value pairs,
575
+ for example: ``{"name": "IMAPClient", "version": "0.12"}``
576
+ """
577
+ if parameters is None:
578
+ args = "NIL"
579
+ else:
580
+ if not isinstance(parameters, dict):
581
+ raise TypeError("'parameters' should be a dictionary")
582
+ args = seq_to_parenstr(
583
+ _quote(v) for v in itertools.chain.from_iterable(parameters.items())
584
+ )
585
+
586
+ typ, data = self._imap._simple_command("ID", args)
587
+ self._checkok("id", typ, data)
588
+ typ, data = self._imap._untagged_response(typ, data, "ID")
589
+ return parse_response(data)
590
+
591
+ def capabilities(self):
592
+ """Returns the server capability list.
593
+
594
+ If the session is authenticated and the server has returned an
595
+ untagged CAPABILITY response at authentication time, this
596
+ response will be returned. Otherwise, the CAPABILITY command
597
+ will be issued to the server, with the results cached for
598
+ future calls.
599
+
600
+ If the session is not yet authenticated, the capabilities
601
+ requested at connection time will be returned.
602
+ """
603
+ # Ensure cached capabilities aren't used post-STARTTLS. As per
604
+ # https://tools.ietf.org/html/rfc2595#section-3.1
605
+ if self._starttls_done and self._imap.state == "NONAUTH":
606
+ self._cached_capabilities = None
607
+ return self._do_capabilites()
608
+
609
+ # If a capability response has been cached, use that.
610
+ if self._cached_capabilities:
611
+ return self._cached_capabilities
612
+
613
+ # If the server returned an untagged CAPABILITY response
614
+ # (during authentication), cache it and return that.
615
+ untagged = _dict_bytes_normaliser(self._imap.untagged_responses)
616
+ response = untagged.pop("CAPABILITY", None)
617
+ if response:
618
+ self._cached_capabilities = self._normalise_capabilites(response[0])
619
+ return self._cached_capabilities
620
+
621
+ # If authenticated, but don't have a capability response, ask for one
622
+ if self._imap.state in ("SELECTED", "AUTH"):
623
+ self._cached_capabilities = self._do_capabilites()
624
+ return self._cached_capabilities
625
+
626
+ # Return capabilities that imaplib requested at connection
627
+ # time (pre-auth)
628
+ return tuple(to_bytes(c) for c in self._imap.capabilities)
629
+
630
+ def _do_capabilites(self):
631
+ raw_response = self._command_and_check("capability", unpack=True)
632
+ return self._normalise_capabilites(raw_response)
633
+
634
+ def _normalise_capabilites(self, raw_response):
635
+ raw_response = to_bytes(raw_response)
636
+ return tuple(raw_response.upper().split())
637
+
638
+ def has_capability(self, capability):
639
+ """Return ``True`` if the IMAP server has the given *capability*."""
640
+ # FIXME: this will not detect capabilities that are backwards
641
+ # compatible with the current level. For instance the SORT
642
+ # capabilities may in the future be named SORT2 which is
643
+ # still compatible with the current standard and will not
644
+ # be detected by this method.
645
+ return to_bytes(capability).upper() in self.capabilities()
646
+
647
+ @require_capability("NAMESPACE")
648
+ def namespace(self):
649
+ """Return the namespace for the account as a (personal, other,
650
+ shared) tuple.
651
+
652
+ Each element may be None if no namespace of that type exists,
653
+ or a sequence of (prefix, separator) pairs.
654
+
655
+ For convenience the tuple elements may be accessed
656
+ positionally or using attributes named *personal*, *other* and
657
+ *shared*.
658
+
659
+ See :rfc:`2342` for more details.
660
+ """
661
+ data = self._command_and_check("namespace")
662
+ parts = []
663
+ for item in parse_response(data):
664
+ if item is None:
665
+ parts.append(item)
666
+ else:
667
+ converted = []
668
+ for prefix, separator in item:
669
+ if self.folder_encode:
670
+ prefix = decode_utf7(prefix)
671
+ converted.append((prefix, to_unicode(separator)))
672
+ parts.append(tuple(converted))
673
+ return Namespace(*parts)
674
+
675
+ def list_folders(self, directory="", pattern="*"):
676
+ """Get a listing of folders on the server as a list of
677
+ ``(flags, delimiter, name)`` tuples.
678
+
679
+ Specifying *directory* will limit returned folders to the
680
+ given base directory. The directory and any child directories
681
+ will returned.
682
+
683
+ Specifying *pattern* will limit returned folders to those with
684
+ matching names. The wildcards are supported in
685
+ *pattern*. ``*`` matches zero or more of any character and
686
+ ``%`` matches 0 or more characters except the folder
687
+ delimiter.
688
+
689
+ Calling list_folders with no arguments will recursively list
690
+ all folders available for the logged in user.
691
+
692
+ Folder names are always returned as unicode strings, and
693
+ decoded from modified UTF-7, except if folder_decode is not
694
+ set.
695
+ """
696
+ return self._do_list("LIST", directory, pattern)
697
+
698
+ @require_capability("XLIST")
699
+ def xlist_folders(self, directory="", pattern="*"):
700
+ """Execute the XLIST command, returning ``(flags, delimiter,
701
+ name)`` tuples.
702
+
703
+ This method returns special flags for each folder and a
704
+ localized name for certain folders (e.g. the name of the
705
+ inbox may be localized and the flags can be used to
706
+ determine the actual inbox, even if the name has been
707
+ localized.
708
+
709
+ A ``XLIST`` response could look something like::
710
+
711
+ [((b'\\HasNoChildren', b'\\Inbox'), b'/', u'Inbox'),
712
+ ((b'\\Noselect', b'\\HasChildren'), b'/', u'[Gmail]'),
713
+ ((b'\\HasNoChildren', b'\\AllMail'), b'/', u'[Gmail]/All Mail'),
714
+ ((b'\\HasNoChildren', b'\\Drafts'), b'/', u'[Gmail]/Drafts'),
715
+ ((b'\\HasNoChildren', b'\\Important'), b'/', u'[Gmail]/Important'),
716
+ ((b'\\HasNoChildren', b'\\Sent'), b'/', u'[Gmail]/Sent Mail'),
717
+ ((b'\\HasNoChildren', b'\\Spam'), b'/', u'[Gmail]/Spam'),
718
+ ((b'\\HasNoChildren', b'\\Starred'), b'/', u'[Gmail]/Starred'),
719
+ ((b'\\HasNoChildren', b'\\Trash'), b'/', u'[Gmail]/Trash')]
720
+
721
+ This is a *deprecated* Gmail-specific IMAP extension (See
722
+ https://developers.google.com/gmail/imap_extensions#xlist_is_deprecated
723
+ for more information).
724
+
725
+ The *directory* and *pattern* arguments are as per
726
+ list_folders().
727
+ """
728
+ return self._do_list("XLIST", directory, pattern)
729
+
730
+ def list_sub_folders(self, directory="", pattern="*"):
731
+ """Return a list of subscribed folders on the server as
732
+ ``(flags, delimiter, name)`` tuples.
733
+
734
+ The default behaviour will list all subscribed folders. The
735
+ *directory* and *pattern* arguments are as per list_folders().
736
+ """
737
+ return self._do_list("LSUB", directory, pattern)
738
+
739
+ def _do_list(self, cmd, directory, pattern):
740
+ directory = self._normalise_folder(directory)
741
+ pattern = self._normalise_folder(pattern)
742
+ typ, dat = self._imap._simple_command(cmd, directory, pattern)
743
+ self._checkok(cmd, typ, dat)
744
+ typ, dat = self._imap._untagged_response(typ, dat, cmd)
745
+ return self._proc_folder_list(dat)
746
+
747
+ def _proc_folder_list(self, folder_data):
748
+ # Filter out empty strings and None's.
749
+ # This also deals with the special case of - no 'untagged'
750
+ # responses (ie, no folders). This comes back as [None].
751
+ folder_data = [item for item in folder_data if item not in (b"", None)]
752
+
753
+ ret = []
754
+ parsed = parse_response(folder_data)
755
+ for flags, delim, name in chunk(parsed, size=3):
756
+ if isinstance(name, int):
757
+ # Some IMAP implementations return integer folder names
758
+ # with quotes. These get parsed to ints so convert them
759
+ # back to strings.
760
+ name = str(name)
761
+ elif self.folder_encode:
762
+ name = decode_utf7(name)
763
+
764
+ ret.append((flags, delim, name))
765
+ return ret
766
+
767
+ def find_special_folder(self, folder_flag):
768
+ """Try to locate a special folder, like the Sent or Trash folder.
769
+
770
+ >>> server.find_special_folder(imapclient.SENT)
771
+ 'INBOX.Sent'
772
+
773
+ This function tries its best to find the correct folder (if any) but
774
+ uses heuristics when the server is unable to precisely tell where
775
+ special folders are located.
776
+
777
+ Returns the name of the folder if found, or None otherwise.
778
+ """
779
+ # Detect folder by looking for known attributes
780
+ # TODO: avoid listing all folders by using extended LIST (RFC6154)
781
+ for folder in self.list_folders():
782
+ if folder and len(folder[0]) > 0 and folder_flag in folder[0]:
783
+ return folder[2]
784
+
785
+ # Detect folder by looking for common names
786
+ # We only look for folders in the "personal" namespace of the user
787
+ if self.has_capability("NAMESPACE"):
788
+ personal_namespaces = self.namespace().personal
789
+ else:
790
+ personal_namespaces = _POPULAR_PERSONAL_NAMESPACES
791
+
792
+ for personal_namespace in personal_namespaces:
793
+ for pattern in _POPULAR_SPECIAL_FOLDERS.get(folder_flag, tuple()):
794
+ pattern = personal_namespace[0] + pattern
795
+ sent_folders = self.list_folders(pattern=pattern)
796
+ if sent_folders:
797
+ return sent_folders[0][2]
798
+
799
+ return None
800
+
801
+ def select_folder(self, folder, readonly=False):
802
+ """Set the current folder on the server.
803
+
804
+ Future calls to methods such as search and fetch will act on
805
+ the selected folder.
806
+
807
+ Returns a dictionary containing the ``SELECT`` response. At least
808
+ the ``b'EXISTS'``, ``b'FLAGS'`` and ``b'RECENT'`` keys are guaranteed
809
+ to exist. An example::
810
+
811
+ {b'EXISTS': 3,
812
+ b'FLAGS': (b'\\Answered', b'\\Flagged', b'\\Deleted', ... ),
813
+ b'RECENT': 0,
814
+ b'PERMANENTFLAGS': (b'\\Answered', b'\\Flagged', b'\\Deleted', ... ),
815
+ b'READ-WRITE': True,
816
+ b'UIDNEXT': 11,
817
+ b'UIDVALIDITY': 1239278212}
818
+ """
819
+ self._command_and_check("select", self._normalise_folder(folder), readonly)
820
+ return self._process_select_response(self._imap.untagged_responses)
821
+
822
+ @require_capability("UNSELECT")
823
+ def unselect_folder(self):
824
+ r"""Unselect the current folder and release associated resources.
825
+
826
+ Unlike ``close_folder``, the ``UNSELECT`` command does not expunge
827
+ the mailbox, keeping messages with \Deleted flag set for example.
828
+
829
+ Returns the UNSELECT response string returned by the server.
830
+ """
831
+ logger.debug("< UNSELECT")
832
+ # IMAP4 class has no `unselect` method so we can't use `_command_and_check` there
833
+ typ, data = self._imap._simple_command("UNSELECT")
834
+ # Mirror imaplib.IMAP4.unselect: return the connection to the
835
+ # authenticated state so subsequent commands (e.g. ENABLE) are legal.
836
+ if typ == "OK":
837
+ self._imap.state = "AUTH"
838
+ return data[0]
839
+
840
+ def _process_select_response(self, resp):
841
+ untagged = _dict_bytes_normaliser(resp)
842
+ out = {}
843
+
844
+ # imaplib doesn't parse these correctly (broken regex) so replace
845
+ # with the raw values out of the OK section
846
+ for line in untagged.get("OK", []):
847
+ match = _RE_SELECT_RESPONSE.match(line)
848
+ if match:
849
+ key = match.group("key")
850
+ if key == b"PERMANENTFLAGS":
851
+ out[key] = tuple(match.group("data").split())
852
+
853
+ for key, value in untagged.items():
854
+ key = key.upper()
855
+ if key in (b"OK", b"PERMANENTFLAGS"):
856
+ continue # already handled above
857
+ if key in (
858
+ b"EXISTS",
859
+ b"RECENT",
860
+ b"UIDNEXT",
861
+ b"UIDVALIDITY",
862
+ b"HIGHESTMODSEQ",
863
+ ):
864
+ value = int(value[0])
865
+ elif key == b"READ-WRITE":
866
+ value = True
867
+ elif key == b"FLAGS":
868
+ value = tuple(value[0][1:-1].split())
869
+ out[key] = value
870
+ return out
871
+
872
+ def noop(self):
873
+ """Execute the NOOP command.
874
+
875
+ This command returns immediately, returning any server side
876
+ status updates. It can also be used to reset any auto-logout
877
+ timers.
878
+
879
+ The return value is the server command response message
880
+ followed by a list of status responses. For example::
881
+
882
+ (b'NOOP completed.',
883
+ [(4, b'EXISTS'),
884
+ (3, b'FETCH', (b'FLAGS', (b'bar', b'sne'))),
885
+ (6, b'FETCH', (b'FLAGS', (b'sne',)))])
886
+
887
+ """
888
+ tag = self._imap._command("NOOP")
889
+ return self._consume_until_tagged_response(tag, "NOOP")
890
+
891
+ @require_capability("IDLE")
892
+ def idle(self):
893
+ """Put the server into IDLE mode.
894
+
895
+ In this mode the server will return unsolicited responses
896
+ about changes to the selected mailbox. This method returns
897
+ immediately. Use ``idle_check()`` to look for IDLE responses
898
+ and ``idle_done()`` to stop IDLE mode.
899
+
900
+ .. note::
901
+
902
+ Any other commands issued while the server is in IDLE
903
+ mode will fail.
904
+
905
+ See :rfc:`2177` for more information about the IDLE extension.
906
+ """
907
+ self._idle_tag = self._imap._command("IDLE")
908
+ resp = self._imap._get_response()
909
+ if resp is not None:
910
+ raise exceptions.IMAPClientError("Unexpected IDLE response: %s" % resp)
911
+
912
+ def _poll_socket(self, sock, timeout=None):
913
+ """
914
+ Polls the socket for events telling us it's available to read.
915
+ This implementation is more scalable because it ALLOWS your process
916
+ to have more than 1024 file descriptors.
917
+ """
918
+ poller = select.poll()
919
+ poller.register(sock.fileno(), select.POLLIN)
920
+ timeout = timeout * 1000 if timeout is not None else None
921
+ return poller.poll(timeout)
922
+
923
+ def _select_poll_socket(self, sock, timeout=None):
924
+ """
925
+ Polls the socket for events telling us it's available to read.
926
+ This implementation is a fallback because it FAILS if your process
927
+ has more than 1024 file descriptors.
928
+ We still need this for Windows and some other niche systems.
929
+ """
930
+ return select.select([sock], [], [], timeout)[0]
931
+
932
+ @require_capability("IDLE")
933
+ def idle_check(self, timeout=None):
934
+ """Check for any IDLE responses sent by the server.
935
+
936
+ This method should only be called if the server is in IDLE
937
+ mode (see ``idle()``).
938
+
939
+ By default, this method will block until an IDLE response is
940
+ received. If *timeout* is provided, the call will block for at
941
+ most this many seconds while waiting for an IDLE response.
942
+
943
+ The return value is a list of received IDLE responses. These
944
+ will be parsed with values converted to appropriate types. For
945
+ example::
946
+
947
+ [(b'OK', b'Still here'),
948
+ (1, b'EXISTS'),
949
+ (1, b'FETCH', (b'FLAGS', (b'\\NotJunk',)))]
950
+ """
951
+ sock = self.socket()
952
+
953
+ # make the socket non-blocking so the timeout can be
954
+ # implemented for this call
955
+ sock.settimeout(None)
956
+ sock.setblocking(0)
957
+
958
+ if POLL_SUPPORT:
959
+ poll_func = self._poll_socket
960
+ else:
961
+ poll_func = self._select_poll_socket
962
+
963
+ try:
964
+ resps = []
965
+ events = poll_func(sock, timeout)
966
+ if events:
967
+ while True:
968
+ try:
969
+ line = self._imap._get_line()
970
+ except (socket.timeout, socket.error):
971
+ break
972
+ except IMAPClient.AbortError:
973
+ # An imaplib.IMAP4.abort with "EOF" is raised
974
+ # under Python 3
975
+ err = sys.exc_info()[1]
976
+ if "EOF" in err.args[0]:
977
+ break
978
+ raise
979
+ else:
980
+ resps.append(_parse_untagged_response(line))
981
+ return resps
982
+ finally:
983
+ sock.setblocking(1)
984
+ self._set_read_timeout()
985
+
986
+ @require_capability("IDLE")
987
+ def idle_done(self):
988
+ """Take the server out of IDLE mode.
989
+
990
+ This method should only be called if the server is already in
991
+ IDLE mode.
992
+
993
+ The return value is of the form ``(command_text,
994
+ idle_responses)`` where *command_text* is the text sent by the
995
+ server when the IDLE command finished (eg. ``b'Idle
996
+ terminated'``) and *idle_responses* is a list of parsed idle
997
+ responses received since the last call to ``idle_check()`` (if
998
+ any). These are returned in parsed form as per
999
+ ``idle_check()``.
1000
+ """
1001
+ logger.debug("< DONE")
1002
+ self._imap.send(b"DONE\r\n")
1003
+ return self._consume_until_tagged_response(self._idle_tag, "IDLE")
1004
+
1005
+ def folder_status(self, folder, what=None):
1006
+ """Return the status of *folder*.
1007
+
1008
+ *what* should be a sequence of status items to query. This
1009
+ defaults to ``('MESSAGES', 'RECENT', 'UIDNEXT', 'UIDVALIDITY',
1010
+ 'UNSEEN')``.
1011
+
1012
+ Returns a dictionary of the status items for the folder with
1013
+ keys matching *what*.
1014
+ """
1015
+ if what is None:
1016
+ what = ("MESSAGES", "RECENT", "UIDNEXT", "UIDVALIDITY", "UNSEEN")
1017
+ else:
1018
+ what = normalise_text_list(what)
1019
+ what_ = "(%s)" % (" ".join(what))
1020
+
1021
+ fname = self._normalise_folder(folder)
1022
+ data = self._command_and_check("status", fname, what_)
1023
+ response = parse_response(data)
1024
+ status_items = response[-1]
1025
+ return dict(as_pairs(status_items))
1026
+
1027
+ def close_folder(self):
1028
+ """Close the currently selected folder, returning the server
1029
+ response string.
1030
+ """
1031
+ return self._command_and_check("close", unpack=True)
1032
+
1033
+ def create_folder(self, folder):
1034
+ """Create *folder* on the server returning the server response string."""
1035
+ return self._command_and_check(
1036
+ "create", self._normalise_folder(folder), unpack=True
1037
+ )
1038
+
1039
+ def rename_folder(self, old_name, new_name):
1040
+ """Change the name of a folder on the server."""
1041
+ return self._command_and_check(
1042
+ "rename",
1043
+ self._normalise_folder(old_name),
1044
+ self._normalise_folder(new_name),
1045
+ unpack=True,
1046
+ )
1047
+
1048
+ def delete_folder(self, folder):
1049
+ """Delete *folder* on the server returning the server response string."""
1050
+ return self._command_and_check(
1051
+ "delete", self._normalise_folder(folder), unpack=True
1052
+ )
1053
+
1054
+ def folder_exists(self, folder):
1055
+ """Return ``True`` if *folder* exists on the server."""
1056
+ return len(self.list_folders("", folder)) > 0
1057
+
1058
+ def subscribe_folder(self, folder):
1059
+ """Subscribe to *folder*, returning the server response string."""
1060
+ return self._command_and_check("subscribe", self._normalise_folder(folder))
1061
+
1062
+ def unsubscribe_folder(self, folder):
1063
+ """Unsubscribe to *folder*, returning the server response string."""
1064
+ return self._command_and_check("unsubscribe", self._normalise_folder(folder))
1065
+
1066
+ def search(self, criteria="ALL", charset=None):
1067
+ """Return a list of messages ids from the currently selected
1068
+ folder matching *criteria*.
1069
+
1070
+ *criteria* should be a sequence of one or more criteria
1071
+ items. Each criteria item may be either unicode or
1072
+ bytes. Example values::
1073
+
1074
+ [u'UNSEEN']
1075
+ [u'SMALLER', 500]
1076
+ [b'NOT', b'DELETED']
1077
+ [u'TEXT', u'foo bar', u'FLAGGED', u'SUBJECT', u'baz']
1078
+ [u'SINCE', date(2005, 4, 3)]
1079
+
1080
+ IMAPClient will perform conversion and quoting as
1081
+ required. The caller shouldn't do this.
1082
+
1083
+ It is also possible (but not recommended) to pass the combined
1084
+ criteria as a single string. In this case IMAPClient won't
1085
+ perform quoting, allowing lower-level specification of
1086
+ criteria. Examples of this style::
1087
+
1088
+ u'UNSEEN'
1089
+ u'SMALLER 500'
1090
+ b'NOT DELETED'
1091
+ u'TEXT "foo bar" FLAGGED SUBJECT "baz"'
1092
+ b'SINCE 03-Apr-2005'
1093
+
1094
+ To support complex search expressions, criteria lists can be
1095
+ nested. IMAPClient will insert parentheses in the right
1096
+ places. The following will match messages that are both not
1097
+ flagged and do not have "foo" in the subject::
1098
+
1099
+ ['NOT', ['SUBJECT', 'foo', 'FLAGGED']]
1100
+
1101
+ *charset* specifies the character set of the criteria. It
1102
+ defaults to US-ASCII as this is the only charset that a server
1103
+ is required to support by the RFC. UTF-8 is commonly supported
1104
+ however.
1105
+
1106
+ Any criteria specified using unicode will be encoded as per
1107
+ *charset*. Specifying a unicode criteria that can not be
1108
+ encoded using *charset* will result in an error.
1109
+
1110
+ Any criteria specified using bytes will be sent as-is but
1111
+ should use an encoding that matches *charset* (the character
1112
+ set given is still passed on to the server).
1113
+
1114
+ See :rfc:`3501#section-6.4.4` for more details.
1115
+
1116
+ Note that criteria arguments that are 8-bit will be
1117
+ transparently sent by IMAPClient as IMAP literals to ensure
1118
+ adherence to IMAP standards.
1119
+
1120
+ The returned list of message ids will have a special *modseq*
1121
+ attribute. This is set if the server included a MODSEQ value
1122
+ to the search response (i.e. if a MODSEQ criteria was included
1123
+ in the search).
1124
+
1125
+ """
1126
+ return self._search(criteria, charset)
1127
+
1128
+ @require_capability("X-GM-EXT-1")
1129
+ def gmail_search(self, query, charset="UTF-8"):
1130
+ """Search using Gmail's X-GM-RAW attribute.
1131
+
1132
+ *query* should be a valid Gmail search query string. For
1133
+ example: ``has:attachment in:unread``. The search string may
1134
+ be unicode and will be encoded using the specified *charset*
1135
+ (defaulting to UTF-8).
1136
+
1137
+ This method only works for IMAP servers that support X-GM-RAW,
1138
+ which is only likely to be Gmail.
1139
+
1140
+ See https://developers.google.com/gmail/imap_extensions#extension_of_the_search_command_x-gm-raw
1141
+ for more info.
1142
+ """
1143
+ return self._search([b"X-GM-RAW", query], charset)
1144
+
1145
+ def _search(self, criteria, charset):
1146
+ args = []
1147
+ if charset:
1148
+ args.extend([b"CHARSET", to_bytes(charset)])
1149
+ args.extend(_normalise_search_criteria(criteria, charset))
1150
+
1151
+ try:
1152
+ data = self._raw_command_untagged(b"SEARCH", args)
1153
+ except imaplib.IMAP4.error as e:
1154
+ # Make BAD IMAP responses easier to understand to the user, with a link to the docs
1155
+ m = re.match(r"SEARCH command error: BAD \[(.+)\]", str(e))
1156
+ if m:
1157
+ raise exceptions.InvalidCriteriaError(
1158
+ "{original_msg}\n\n"
1159
+ "This error may have been caused by a syntax error in the criteria: "
1160
+ "{criteria}\nPlease refer to the documentation for more information "
1161
+ "about search criteria syntax..\n"
1162
+ "https://imapclient.readthedocs.io/en/master/#imapclient.IMAPClient.search".format(
1163
+ original_msg=m.group(1),
1164
+ criteria=(
1165
+ '"%s"' % criteria
1166
+ if not isinstance(criteria, list)
1167
+ else criteria
1168
+ ),
1169
+ )
1170
+ )
1171
+
1172
+ # If the exception is not from a BAD IMAP response, re-raise as-is
1173
+ raise
1174
+
1175
+ return parse_message_list(data)
1176
+
1177
+ @require_capability("SORT")
1178
+ def sort(self, sort_criteria, criteria="ALL", charset="UTF-8"):
1179
+ """Return a list of message ids from the currently selected
1180
+ folder, sorted by *sort_criteria* and optionally filtered by
1181
+ *criteria*.
1182
+
1183
+ *sort_criteria* may be specified as a sequence of strings or a
1184
+ single string. IMAPClient will take care any required
1185
+ conversions. Valid *sort_criteria* values::
1186
+
1187
+ ['ARRIVAL']
1188
+ ['SUBJECT', 'ARRIVAL']
1189
+ 'ARRIVAL'
1190
+ 'REVERSE SIZE'
1191
+
1192
+ The *criteria* and *charset* arguments are as per
1193
+ :py:meth:`.search`.
1194
+
1195
+ See :rfc:`5256` for full details.
1196
+
1197
+ Note that SORT is an extension to the IMAP4 standard so it may
1198
+ not be supported by all IMAP servers.
1199
+ """
1200
+ args = [
1201
+ _normalise_sort_criteria(sort_criteria),
1202
+ to_bytes(charset),
1203
+ ]
1204
+ args.extend(_normalise_search_criteria(criteria, charset))
1205
+ ids = self._raw_command_untagged(b"SORT", args, unpack=True)
1206
+ return [int(i) for i in ids.split()]
1207
+
1208
+ def thread(self, algorithm="REFERENCES", criteria="ALL", charset="UTF-8"):
1209
+ """Return a list of messages threads from the currently
1210
+ selected folder which match *criteria*.
1211
+
1212
+ Each returned thread is a list of messages ids. An example
1213
+ return value containing three message threads::
1214
+
1215
+ ((1, 2), (3,), (4, 5, 6))
1216
+
1217
+ The optional *algorithm* argument specifies the threading
1218
+ algorithm to use.
1219
+
1220
+ The *criteria* and *charset* arguments are as per
1221
+ :py:meth:`.search`.
1222
+
1223
+ See :rfc:`5256` for more details.
1224
+ """
1225
+ algorithm = to_bytes(algorithm)
1226
+ if not self.has_capability(b"THREAD=" + algorithm):
1227
+ raise exceptions.CapabilityError(
1228
+ "The server does not support %s threading algorithm" % algorithm
1229
+ )
1230
+
1231
+ args = [algorithm, to_bytes(charset)] + _normalise_search_criteria(
1232
+ criteria, charset
1233
+ )
1234
+ data = self._raw_command_untagged(b"THREAD", args)
1235
+ return parse_response(data)
1236
+
1237
+ def get_flags(self, messages):
1238
+ """Return the flags set for each message in *messages* from
1239
+ the currently selected folder.
1240
+
1241
+ The return value is a dictionary structured like this: ``{
1242
+ msgid1: (flag1, flag2, ... ), }``.
1243
+ """
1244
+ response = self.fetch(messages, ["FLAGS"])
1245
+ return self._filter_fetch_dict(response, b"FLAGS")
1246
+
1247
+ def add_flags(self, messages, flags, silent=False):
1248
+ """Add *flags* to *messages* in the currently selected folder.
1249
+
1250
+ *flags* should be a sequence of strings.
1251
+
1252
+ Returns the flags set for each modified message (see
1253
+ *get_flags*), or None if *silent* is true.
1254
+ """
1255
+ return self._store(b"+FLAGS", messages, flags, b"FLAGS", silent=silent)
1256
+
1257
+ def remove_flags(self, messages, flags, silent=False):
1258
+ """Remove one or more *flags* from *messages* in the currently
1259
+ selected folder.
1260
+
1261
+ *flags* should be a sequence of strings.
1262
+
1263
+ Returns the flags set for each modified message (see
1264
+ *get_flags*), or None if *silent* is true.
1265
+ """
1266
+ return self._store(b"-FLAGS", messages, flags, b"FLAGS", silent=silent)
1267
+
1268
+ def set_flags(self, messages, flags, silent=False):
1269
+ """Set the *flags* for *messages* in the currently selected
1270
+ folder.
1271
+
1272
+ *flags* should be a sequence of strings.
1273
+
1274
+ Returns the flags set for each modified message (see
1275
+ *get_flags*), or None if *silent* is true.
1276
+ """
1277
+ return self._store(b"FLAGS", messages, flags, b"FLAGS", silent=silent)
1278
+
1279
+ def get_gmail_labels(self, messages):
1280
+ """Return the label set for each message in *messages* in the
1281
+ currently selected folder.
1282
+
1283
+ The return value is a dictionary structured like this: ``{
1284
+ msgid1: (label1, label2, ... ), }``.
1285
+
1286
+ This only works with IMAP servers that support the X-GM-LABELS
1287
+ attribute (eg. Gmail).
1288
+ """
1289
+ response = self.fetch(messages, [b"X-GM-LABELS"])
1290
+ response = self._filter_fetch_dict(response, b"X-GM-LABELS")
1291
+ return {msg: utf7_decode_sequence(labels) for msg, labels in response.items()}
1292
+
1293
+ def add_gmail_labels(self, messages, labels, silent=False):
1294
+ """Add *labels* to *messages* in the currently selected folder.
1295
+
1296
+ *labels* should be a sequence of strings.
1297
+
1298
+ Returns the label set for each modified message (see
1299
+ *get_gmail_labels*), or None if *silent* is true.
1300
+
1301
+ This only works with IMAP servers that support the X-GM-LABELS
1302
+ attribute (eg. Gmail).
1303
+ """
1304
+ return self._gm_label_store(b"+X-GM-LABELS", messages, labels, silent=silent)
1305
+
1306
+ def remove_gmail_labels(self, messages, labels, silent=False):
1307
+ """Remove one or more *labels* from *messages* in the
1308
+ currently selected folder, or None if *silent* is true.
1309
+
1310
+ *labels* should be a sequence of strings.
1311
+
1312
+ Returns the label set for each modified message (see
1313
+ *get_gmail_labels*).
1314
+
1315
+ This only works with IMAP servers that support the X-GM-LABELS
1316
+ attribute (eg. Gmail).
1317
+ """
1318
+ return self._gm_label_store(b"-X-GM-LABELS", messages, labels, silent=silent)
1319
+
1320
+ def set_gmail_labels(self, messages, labels, silent=False):
1321
+ """Set the *labels* for *messages* in the currently selected
1322
+ folder.
1323
+
1324
+ *labels* should be a sequence of strings.
1325
+
1326
+ Returns the label set for each modified message (see
1327
+ *get_gmail_labels*), or None if *silent* is true.
1328
+
1329
+ This only works with IMAP servers that support the X-GM-LABELS
1330
+ attribute (eg. Gmail).
1331
+ """
1332
+ return self._gm_label_store(b"X-GM-LABELS", messages, labels, silent=silent)
1333
+
1334
+ def delete_messages(self, messages, silent=False):
1335
+ """Delete one or more *messages* from the currently selected
1336
+ folder.
1337
+
1338
+ Returns the flags set for each modified message (see
1339
+ *get_flags*).
1340
+ """
1341
+ return self.add_flags(messages, DELETED, silent=silent)
1342
+
1343
+ def fetch(self, messages, data, modifiers=None):
1344
+ """Retrieve selected *data* associated with one or more
1345
+ *messages* in the currently selected folder.
1346
+
1347
+ *data* should be specified as a sequence of strings, one item
1348
+ per data selector, for example ``['INTERNALDATE',
1349
+ 'RFC822']``.
1350
+
1351
+ *modifiers* are required for some extensions to the IMAP
1352
+ protocol (eg. :rfc:`4551`). These should be a sequence of strings
1353
+ if specified, for example ``['CHANGEDSINCE 123']``.
1354
+
1355
+ A dictionary is returned, indexed by message number. Each item
1356
+ in this dictionary is also a dictionary, with an entry
1357
+ corresponding to each item in *data*. Returned values will be
1358
+ appropriately typed. For example, integer values will be returned as
1359
+ Python integers, timestamps will be returned as datetime
1360
+ instances and ENVELOPE responses will be returned as
1361
+ :py:class:`Envelope <imapclient.response_types.Envelope>` instances.
1362
+
1363
+ String data will generally be returned as bytes (Python 3) or
1364
+ str (Python 2).
1365
+
1366
+ In addition to an element for each *data* item, the dict
1367
+ returned for each message also contains a *SEQ* key containing
1368
+ the sequence number for the message. This allows for mapping
1369
+ between the UID and sequence number (when the *use_uid*
1370
+ property is ``True``).
1371
+
1372
+ Example::
1373
+
1374
+ >> c.fetch([3293, 3230], ['INTERNALDATE', 'FLAGS'])
1375
+ {3230: {b'FLAGS': (b'\\Seen',),
1376
+ b'INTERNALDATE': datetime.datetime(2011, 1, 30, 13, 32, 9),
1377
+ b'SEQ': 84},
1378
+ 3293: {b'FLAGS': (),
1379
+ b'INTERNALDATE': datetime.datetime(2011, 2, 24, 19, 30, 36),
1380
+ b'SEQ': 110}}
1381
+
1382
+ Note that due to IMAP unsolicited FETCH responses the return
1383
+ value may include fields not matching the original data query.
1384
+ It is up to the caller to handle that gracefully.
1385
+ """
1386
+ if not messages:
1387
+ return {}
1388
+
1389
+ args = [
1390
+ "FETCH",
1391
+ join_message_ids(messages),
1392
+ seq_to_parenstr_upper(data),
1393
+ seq_to_parenstr_upper(modifiers) if modifiers else None,
1394
+ ]
1395
+ if self.use_uid:
1396
+ args.insert(0, "UID")
1397
+ tag = self._imap._command(*args)
1398
+ typ, data = self._imap._command_complete("FETCH", tag)
1399
+ self._checkok("fetch", typ, data)
1400
+ typ, data = self._imap._untagged_response(typ, data, "FETCH")
1401
+ response = parse_fetch_response(data, self.normalise_times, self.use_uid)
1402
+ # Drop unsolicited responses for other messages
1403
+ return {
1404
+ message_id: response[message_id]
1405
+ for message_id in to_ints(messages)
1406
+ if message_id in response
1407
+ }
1408
+
1409
+ def append(self, folder, msg, flags=(), msg_time=None):
1410
+ """Append a message to *folder*.
1411
+
1412
+ *msg* should be a string contains the full message including
1413
+ headers.
1414
+
1415
+ *flags* should be a sequence of message flags to set. If not
1416
+ specified no flags will be set.
1417
+
1418
+ *msg_time* is an optional datetime instance specifying the
1419
+ date and time to set on the message. The server will set a
1420
+ time if it isn't specified. If *msg_time* contains timezone
1421
+ information (tzinfo), this will be honoured. Otherwise the
1422
+ local machine's time zone sent to the server.
1423
+
1424
+ Returns the APPEND response as returned by the server.
1425
+ """
1426
+ if msg_time:
1427
+ time_val = '"%s"' % datetime_to_INTERNALDATE(msg_time)
1428
+ time_val = to_unicode(time_val)
1429
+ else:
1430
+ time_val = None
1431
+ return self._command_and_check(
1432
+ "append",
1433
+ self._normalise_folder(folder),
1434
+ seq_to_parenstr(flags),
1435
+ time_val,
1436
+ to_bytes(msg),
1437
+ unpack=True,
1438
+ )
1439
+
1440
+ @require_capability("MULTIAPPEND")
1441
+ def multiappend(self, folder, msgs):
1442
+ """Append messages to *folder* using the MULTIAPPEND feature from :rfc:`3502`.
1443
+
1444
+ *msgs* must be an iterable. Each item must be either a string containing the
1445
+ full message including headers, or a dict containing the keys "msg" with the
1446
+ full message as before, "flags" with a sequence of message flags to set, and
1447
+ "date" with a datetime instance specifying the internal date to set.
1448
+ The keys "flags" and "date" are optional.
1449
+
1450
+ Returns the APPEND response from the server.
1451
+ """
1452
+
1453
+ def chunks():
1454
+ for m in msgs:
1455
+ if isinstance(m, dict):
1456
+ if "flags" in m:
1457
+ yield to_bytes(seq_to_parenstr(m["flags"]))
1458
+ if "date" in m:
1459
+ yield to_bytes('"%s"' % datetime_to_INTERNALDATE(m["date"]))
1460
+ yield _literal(to_bytes(m["msg"]))
1461
+ else:
1462
+ yield _literal(to_bytes(m))
1463
+
1464
+ msgs = list(chunks())
1465
+
1466
+ return self._raw_command(
1467
+ b"APPEND",
1468
+ [self._normalise_folder(folder)] + msgs,
1469
+ uid=False,
1470
+ )
1471
+
1472
+ def copy(self, messages, folder):
1473
+ """Copy one or more messages from the current folder to
1474
+ *folder*. Returns the COPY response string returned by the
1475
+ server.
1476
+ """
1477
+ return self._command_and_check(
1478
+ "copy",
1479
+ join_message_ids(messages),
1480
+ self._normalise_folder(folder),
1481
+ uid=True,
1482
+ unpack=True,
1483
+ )
1484
+
1485
+ @require_capability("MOVE")
1486
+ def move(self, messages, folder):
1487
+ """Atomically move messages to another folder.
1488
+
1489
+ Requires the MOVE capability, see :rfc:`6851`.
1490
+
1491
+ :param messages: List of message UIDs to move.
1492
+ :param folder: The destination folder name.
1493
+ """
1494
+ return self._command_and_check(
1495
+ "move",
1496
+ join_message_ids(messages),
1497
+ self._normalise_folder(folder),
1498
+ uid=True,
1499
+ unpack=True,
1500
+ )
1501
+
1502
+ def expunge(self, messages=None):
1503
+ """Use of the *messages* argument is discouraged.
1504
+ Please see the ``uid_expunge`` method instead.
1505
+
1506
+ When, no *messages* are specified, remove all messages
1507
+ from the currently selected folder that have the
1508
+ ``\\Deleted`` flag set.
1509
+
1510
+ The return value is the server response message
1511
+ followed by a list of expunge responses. For example::
1512
+
1513
+ ('Expunge completed.',
1514
+ [(2, 'EXPUNGE'),
1515
+ (1, 'EXPUNGE'),
1516
+ (0, 'RECENT')])
1517
+
1518
+ In this case, the responses indicate that the message with
1519
+ sequence numbers 2 and 1 where deleted, leaving no recent
1520
+ messages in the folder.
1521
+
1522
+ See :rfc:`3501#section-6.4.3` section 6.4.3 and
1523
+ :rfc:`3501#section-7.4.1` section 7.4.1 for more details.
1524
+
1525
+ When *messages* are specified, remove the specified messages
1526
+ from the selected folder, provided those messages also have
1527
+ the ``\\Deleted`` flag set. The return value is ``None`` in
1528
+ this case.
1529
+
1530
+ Expunging messages by id(s) requires that *use_uid* is
1531
+ ``True`` for the client.
1532
+
1533
+ See :rfc:`4315#section-2.1` section 2.1 for more details.
1534
+ """
1535
+ if messages:
1536
+ if not self.use_uid:
1537
+ raise ValueError("cannot EXPUNGE by ID when not using uids")
1538
+ return self._command_and_check(
1539
+ "EXPUNGE", join_message_ids(messages), uid=True
1540
+ )
1541
+ tag = self._imap._command("EXPUNGE")
1542
+ return self._consume_until_tagged_response(tag, "EXPUNGE")
1543
+
1544
+ @require_capability("UIDPLUS")
1545
+ def uid_expunge(self, messages):
1546
+ """Expunge deleted messages with the specified message ids from the
1547
+ folder.
1548
+
1549
+ This requires the UIDPLUS capability.
1550
+
1551
+ See :rfc:`4315#section-2.1` section 2.1 for more details.
1552
+ """
1553
+ return self._command_and_check("EXPUNGE", join_message_ids(messages), uid=True)
1554
+
1555
+ @require_capability("ACL")
1556
+ def getacl(self, folder):
1557
+ """Returns a list of ``(who, acl)`` tuples describing the
1558
+ access controls for *folder*.
1559
+ """
1560
+ data = self._command_and_check("getacl", self._normalise_folder(folder))
1561
+ parts = list(response_lexer.TokenSource(data))
1562
+ parts = parts[1:] # First item is folder name
1563
+ return [(parts[i], parts[i + 1]) for i in range(0, len(parts), 2)]
1564
+
1565
+ @require_capability("ACL")
1566
+ def setacl(self, folder, who, what):
1567
+ """Set an ACL (*what*) for user (*who*) for a folder.
1568
+
1569
+ Set *what* to an empty string to remove an ACL. Returns the
1570
+ server response string.
1571
+ """
1572
+ return self._command_and_check(
1573
+ "setacl", self._normalise_folder(folder), who, what, unpack=True
1574
+ )
1575
+
1576
+ @require_capability("QUOTA")
1577
+ def get_quota(self, mailbox="INBOX"):
1578
+ """Get the quotas associated with a mailbox.
1579
+
1580
+ Returns a list of Quota objects.
1581
+ """
1582
+ return self.get_quota_root(mailbox)[1]
1583
+
1584
+ @require_capability("QUOTA")
1585
+ def _get_quota(self, quota_root=""):
1586
+ """Get the quotas associated with a quota root.
1587
+
1588
+ This method is not private but put behind an underscore to show that
1589
+ it is a low-level function. Users probably want to use `get_quota`
1590
+ instead.
1591
+
1592
+ Returns a list of Quota objects.
1593
+ """
1594
+ return _parse_quota(self._command_and_check("getquota", _quote(quota_root)))
1595
+
1596
+ @require_capability("QUOTA")
1597
+ def get_quota_root(self, mailbox):
1598
+ """Get the quota roots for a mailbox.
1599
+
1600
+ The IMAP server responds with the quota root and the quotas associated
1601
+ so there is usually no need to call `get_quota` after.
1602
+
1603
+ See :rfc:`2087` for more details.
1604
+
1605
+ Return a tuple of MailboxQuotaRoots and list of Quota associated
1606
+ """
1607
+ quota_root_rep = self._raw_command_untagged(
1608
+ b"GETQUOTAROOT", to_bytes(mailbox), uid=False, response_name="QUOTAROOT"
1609
+ )
1610
+ quota_rep = self._imap.untagged_responses.pop("QUOTA", [])
1611
+ quota_root_rep = parse_response(quota_root_rep)
1612
+ quota_root = MailboxQuotaRoots(
1613
+ to_unicode(quota_root_rep[0]), [to_unicode(q) for q in quota_root_rep[1:]]
1614
+ )
1615
+ return quota_root, _parse_quota(quota_rep)
1616
+
1617
+ @require_capability("QUOTA")
1618
+ def set_quota(self, quotas):
1619
+ """Set one or more quotas on resources.
1620
+
1621
+ :param quotas: list of Quota objects
1622
+ """
1623
+ if not quotas:
1624
+ return
1625
+
1626
+ quota_root = None
1627
+ set_quota_args = []
1628
+
1629
+ for quota in quotas:
1630
+ if quota_root is None:
1631
+ quota_root = quota.quota_root
1632
+ elif quota_root != quota.quota_root:
1633
+ raise ValueError("set_quota only accepts a single quota root")
1634
+
1635
+ set_quota_args.append("{} {}".format(quota.resource, quota.limit))
1636
+
1637
+ set_quota_args = " ".join(set_quota_args)
1638
+ args = [to_bytes(_quote(quota_root)), to_bytes("({})".format(set_quota_args))]
1639
+
1640
+ response = self._raw_command_untagged(
1641
+ b"SETQUOTA", args, uid=False, response_name="QUOTA"
1642
+ )
1643
+ return _parse_quota(response)
1644
+
1645
+ def _check_resp(self, expected, command, typ, data):
1646
+ """Check command responses for errors.
1647
+
1648
+ Raises IMAPClient.Error if the command fails.
1649
+ """
1650
+ if typ != expected:
1651
+ raise exceptions.IMAPClientError(
1652
+ "%s failed: %s" % (command, to_unicode(data[0]))
1653
+ )
1654
+
1655
+ def _consume_until_tagged_response(self, tag, command):
1656
+ tagged_commands = self._imap.tagged_commands
1657
+ resps = []
1658
+ while True:
1659
+ line = self._imap._get_response()
1660
+ if tagged_commands[tag]:
1661
+ break
1662
+ resps.append(_parse_untagged_response(line))
1663
+ typ, data = tagged_commands.pop(tag)
1664
+ self._checkok(command, typ, data)
1665
+ return data[0], resps
1666
+
1667
+ def _raw_command_untagged(
1668
+ self, command, args, response_name=None, unpack=False, uid=True
1669
+ ):
1670
+ # TODO: eventually this should replace _command_and_check (call it _command)
1671
+ typ, data = self._raw_command(command, args, uid=uid)
1672
+ if response_name is None:
1673
+ response_name = command
1674
+ typ, data = self._imap._untagged_response(typ, data, to_unicode(response_name))
1675
+ self._checkok(to_unicode(command), typ, data)
1676
+ if unpack:
1677
+ return data[0]
1678
+ return data
1679
+
1680
+ def _raw_command(self, command, args, uid=True):
1681
+ """Run the specific command with the arguments given. 8-bit arguments
1682
+ are sent as literals. The return value is (typ, data).
1683
+
1684
+ This sidesteps much of imaplib's command sending
1685
+ infrastructure because imaplib can't send more than one
1686
+ literal.
1687
+
1688
+ *command* should be specified as bytes.
1689
+ *args* should be specified as a list of bytes.
1690
+ """
1691
+ command = command.upper()
1692
+
1693
+ # Check for LITERAL+ now because if capabilities haven't been cached
1694
+ # yet, we can't call CAPABILITY while sending another command.
1695
+ has_literal_plus = self.has_capability("LITERAL+")
1696
+
1697
+ if isinstance(args, tuple):
1698
+ args = list(args)
1699
+ if not isinstance(args, list):
1700
+ args = [args]
1701
+
1702
+ tag = self._imap._new_tag()
1703
+ prefix = [to_bytes(tag)]
1704
+ if uid and self.use_uid:
1705
+ prefix.append(b"UID")
1706
+ prefix.append(command)
1707
+
1708
+ line = []
1709
+ for item, is_last in _iter_with_last(prefix + args):
1710
+ if not isinstance(item, bytes):
1711
+ raise ValueError("command args must be passed as bytes")
1712
+
1713
+ if _is8bit(item):
1714
+ # If a line was already started send it
1715
+ if line:
1716
+ out = b" ".join(line)
1717
+ logger.debug("> %s", out)
1718
+ self._imap.send(out)
1719
+ line = []
1720
+
1721
+ # Now send the (unquoted) literal
1722
+ if isinstance(item, _quoted):
1723
+ item = item.original
1724
+ self._send_literal(tag, item, has_literal_plus)
1725
+ if not is_last:
1726
+ self._imap.send(b" ")
1727
+ else:
1728
+ line.append(item)
1729
+
1730
+ if line:
1731
+ out = b" ".join(line)
1732
+ logger.debug("> %s", out)
1733
+ self._imap.send(out)
1734
+
1735
+ self._imap.send(b"\r\n")
1736
+
1737
+ return self._imap._command_complete(to_unicode(command), tag)
1738
+
1739
+ def _send_literal(self, tag, item, has_literal_plus):
1740
+ """Send a single literal for the command with *tag*."""
1741
+ if has_literal_plus:
1742
+ out = b" {" + str(len(item)).encode("ascii") + b"+}\r\n" + item
1743
+ logger.debug("> %s", debug_trunc(out, 64))
1744
+ self._imap.send(out)
1745
+ return
1746
+
1747
+ out = b" {" + str(len(item)).encode("ascii") + b"}\r\n"
1748
+ logger.debug("> %s", out)
1749
+ self._imap.send(out)
1750
+
1751
+ # Wait for continuation response
1752
+ while self._imap._get_response():
1753
+ tagged_resp = self._imap.tagged_commands.get(tag)
1754
+ if tagged_resp:
1755
+ raise exceptions.IMAPClientAbortError(
1756
+ "unexpected response while waiting for continuation response: "
1757
+ + repr(tagged_resp)
1758
+ )
1759
+
1760
+ logger.debug(" (literal) > %s", debug_trunc(item, 256))
1761
+ self._imap.send(item)
1762
+
1763
+ def _command_and_check(
1764
+ self, command, *args, unpack: bool = False, uid: bool = False
1765
+ ):
1766
+ if uid and self.use_uid:
1767
+ command = to_unicode(command) # imaplib must die
1768
+ typ, data = self._imap.uid(command, *args)
1769
+ else:
1770
+ meth = getattr(self._imap, to_unicode(command))
1771
+ typ, data = meth(*args)
1772
+ self._checkok(command, typ, data)
1773
+ if unpack:
1774
+ return data[0]
1775
+ return data
1776
+
1777
+ def _checkok(self, command, typ, data):
1778
+ self._check_resp("OK", command, typ, data)
1779
+
1780
+ def _gm_label_store(self, cmd, messages, labels, silent):
1781
+ response = self._store(
1782
+ cmd, messages, self._normalise_labels(labels), b"X-GM-LABELS", silent=silent
1783
+ )
1784
+ return (
1785
+ {msg: utf7_decode_sequence(labels) for msg, labels in response.items()}
1786
+ if response
1787
+ else None
1788
+ )
1789
+
1790
+ def _store(self, cmd, messages, flags, fetch_key, silent):
1791
+ """Worker function for the various flag manipulation methods.
1792
+
1793
+ *cmd* is the STORE command to use (eg. '+FLAGS').
1794
+ """
1795
+ if not messages:
1796
+ return {}
1797
+ if silent:
1798
+ cmd += b".SILENT"
1799
+
1800
+ data = self._command_and_check(
1801
+ "store", join_message_ids(messages), cmd, seq_to_parenstr(flags), uid=True
1802
+ )
1803
+ if silent:
1804
+ return None
1805
+ response = parse_fetch_response(data)
1806
+ # Drop unsolicited responses for other messages
1807
+ without_unsolicited = {
1808
+ message_id: response[message_id]
1809
+ for message_id in to_ints(messages)
1810
+ if message_id in response
1811
+ }
1812
+ return self._filter_fetch_dict(without_unsolicited, fetch_key)
1813
+
1814
+ def _filter_fetch_dict(self, fetch_dict, key):
1815
+ return dict((msgid, data[key]) for msgid, data in fetch_dict.items())
1816
+
1817
+ def _normalise_folder(self, folder_name):
1818
+ if isinstance(folder_name, bytes):
1819
+ folder_name = folder_name.decode("ascii")
1820
+ if self.folder_encode:
1821
+ folder_name = encode_utf7(folder_name)
1822
+ return _quote(folder_name)
1823
+
1824
+ def _normalise_labels(self, labels):
1825
+ if isinstance(labels, (str, bytes)):
1826
+ labels = (labels,)
1827
+ return [_quote(encode_utf7(label)) for label in labels]
1828
+
1829
+ @property
1830
+ def welcome(self):
1831
+ """access the server greeting message"""
1832
+ try:
1833
+ return self._imap.welcome
1834
+ except AttributeError:
1835
+ pass
1836
+
1837
+
1838
+ def _quote(arg):
1839
+ if isinstance(arg, str):
1840
+ arg = arg.replace("\\", "\\\\")
1841
+ arg = arg.replace('"', '\\"')
1842
+ q = '"'
1843
+ else:
1844
+ arg = arg.replace(b"\\", b"\\\\")
1845
+ arg = arg.replace(b'"', b'\\"')
1846
+ q = b'"'
1847
+ return q + arg + q
1848
+
1849
+
1850
+ def _normalise_search_criteria(criteria, charset=None):
1851
+ if not criteria:
1852
+ raise exceptions.InvalidCriteriaError("no criteria specified")
1853
+ if not charset:
1854
+ charset = "us-ascii"
1855
+
1856
+ if isinstance(criteria, (str, bytes)):
1857
+ return [to_bytes(criteria, charset)]
1858
+
1859
+ out = []
1860
+ for item in criteria:
1861
+ if isinstance(item, int):
1862
+ out.append(str(item).encode("ascii"))
1863
+ elif isinstance(item, (datetime, date)):
1864
+ out.append(format_criteria_date(item))
1865
+ elif isinstance(item, (list, tuple)):
1866
+ # Process nested criteria list and wrap in parens.
1867
+ inner = _normalise_search_criteria(item)
1868
+ inner[0] = b"(" + inner[0]
1869
+ inner[-1] = inner[-1] + b")"
1870
+ out.extend(inner) # flatten
1871
+ else:
1872
+ out.append(_quoted.maybe(to_bytes(item, charset)))
1873
+ return out
1874
+
1875
+
1876
+ def _normalise_sort_criteria(criteria, charset=None):
1877
+ if isinstance(criteria, (str, bytes)):
1878
+ criteria = [criteria]
1879
+ return b"(" + b" ".join(to_bytes(item).upper() for item in criteria) + b")"
1880
+
1881
+
1882
+ class _literal(bytes):
1883
+ """Hold message data that should always be sent as a literal."""
1884
+
1885
+
1886
+ class _quoted(bytes):
1887
+ """
1888
+ This class holds a quoted bytes value which provides access to the
1889
+ unquoted value via the *original* attribute.
1890
+
1891
+ They should be created via the *maybe* classmethod.
1892
+ """
1893
+
1894
+ @classmethod
1895
+ def maybe(cls, original):
1896
+ """Maybe quote a bytes value.
1897
+
1898
+ If the input requires no quoting it is returned unchanged.
1899
+
1900
+ If quoting is required a *_quoted* instance is returned. This
1901
+ holds the quoted version of the input while also providing
1902
+ access to the original unquoted source.
1903
+ """
1904
+ quoted = original.replace(b"\\", b"\\\\")
1905
+ quoted = quoted.replace(b'"', b'\\"')
1906
+ if quoted != original or b" " in quoted or not quoted:
1907
+ out = cls(b'"' + quoted + b'"')
1908
+ out.original = original
1909
+ return out
1910
+ return original
1911
+
1912
+
1913
+ # normalise_text_list, seq_to_parentstr etc have to return unicode
1914
+ # because imaplib handles flags and sort criteria assuming these are
1915
+ # passed as unicode
1916
+ def normalise_text_list(items):
1917
+ return list(_normalise_text_list(items))
1918
+
1919
+
1920
+ def seq_to_parenstr(items):
1921
+ return _join_and_paren(_normalise_text_list(items))
1922
+
1923
+
1924
+ def seq_to_parenstr_upper(items):
1925
+ return _join_and_paren(item.upper() for item in _normalise_text_list(items))
1926
+
1927
+
1928
+ def _join_and_paren(items):
1929
+ return "(" + " ".join(items) + ")"
1930
+
1931
+
1932
+ def _normalise_text_list(items):
1933
+ if isinstance(items, (str, bytes)):
1934
+ items = (items,)
1935
+ return (to_unicode(c) for c in items)
1936
+
1937
+
1938
+ def join_message_ids(messages):
1939
+ """Convert a sequence of messages ids or a single integer message id
1940
+ into an id byte string for use with IMAP commands
1941
+ """
1942
+ if isinstance(messages, (str, bytes, int)):
1943
+ messages = (to_bytes(messages),)
1944
+ return b",".join(_maybe_int_to_bytes(m) for m in messages)
1945
+
1946
+
1947
+ def _maybe_int_to_bytes(val):
1948
+ if isinstance(val, int):
1949
+ return str(val).encode("us-ascii")
1950
+ return to_bytes(val)
1951
+
1952
+
1953
+ def _parse_untagged_response(text):
1954
+ assert_imap_protocol(text.startswith(b"* "))
1955
+ text = text[2:]
1956
+ if text.startswith((b"OK ", b"NO ")):
1957
+ return tuple(text.split(b" ", 1))
1958
+ return parse_response([text])
1959
+
1960
+
1961
+ def as_pairs(items):
1962
+ i = 0
1963
+ last_item = None
1964
+ for item in items:
1965
+ if i % 2:
1966
+ yield last_item, item
1967
+ else:
1968
+ last_item = item
1969
+ i += 1
1970
+
1971
+
1972
+ def as_triplets(items):
1973
+ a = iter(items)
1974
+ return zip(a, a, a)
1975
+
1976
+
1977
+ def _is8bit(data):
1978
+ return isinstance(data, _literal) or any(b > 127 for b in data)
1979
+
1980
+
1981
+ def _iter_with_last(items):
1982
+ last_i = len(items) - 1
1983
+ for i, item in enumerate(items):
1984
+ yield item, i == last_i
1985
+
1986
+
1987
+ _not_present = object()
1988
+
1989
+
1990
+ class _dict_bytes_normaliser:
1991
+ """Wrap a dict with unicode/bytes keys and normalise the keys to
1992
+ bytes.
1993
+ """
1994
+
1995
+ def __init__(self, d):
1996
+ self._d = d
1997
+
1998
+ def iteritems(self):
1999
+ for key, value in self._d.items():
2000
+ yield to_bytes(key), value
2001
+
2002
+ # For Python 3 compatibility.
2003
+ items = iteritems
2004
+
2005
+ def __contains__(self, ink):
2006
+ for k in self._gen_keys(ink):
2007
+ if k in self._d:
2008
+ return True
2009
+ return False
2010
+
2011
+ def get(self, ink, default=_not_present):
2012
+ for k in self._gen_keys(ink):
2013
+ try:
2014
+ return self._d[k]
2015
+ except KeyError:
2016
+ pass
2017
+ if default == _not_present:
2018
+ raise KeyError(ink)
2019
+ return default
2020
+
2021
+ def pop(self, ink, default=_not_present):
2022
+ for k in self._gen_keys(ink):
2023
+ try:
2024
+ return self._d.pop(k)
2025
+ except KeyError:
2026
+ pass
2027
+ if default == _not_present:
2028
+ raise KeyError(ink)
2029
+ return default
2030
+
2031
+ def _gen_keys(self, k):
2032
+ yield k
2033
+ if isinstance(k, bytes):
2034
+ yield to_unicode(k)
2035
+ else:
2036
+ yield to_bytes(k)
2037
+
2038
+
2039
+ def debug_trunc(v, maxlen):
2040
+ if len(v) < maxlen:
2041
+ return repr(v)
2042
+ hl = maxlen // 2
2043
+ return repr(v[:hl]) + "..." + repr(v[-hl:])
2044
+
2045
+
2046
+ def utf7_decode_sequence(seq):
2047
+ return [decode_utf7(s) for s in seq]
2048
+
2049
+
2050
+ def _parse_quota(quota_rep):
2051
+ quota_rep = parse_response(quota_rep)
2052
+ rv = []
2053
+ for quota_root, quota_resource_infos in as_pairs(quota_rep):
2054
+ for quota_resource_info in as_triplets(quota_resource_infos):
2055
+ rv.append(
2056
+ Quota(
2057
+ quota_root=to_unicode(quota_root),
2058
+ resource=to_unicode(quota_resource_info[0]),
2059
+ usage=quota_resource_info[1],
2060
+ limit=quota_resource_info[2],
2061
+ )
2062
+ )
2063
+ return rv
2064
+
2065
+
2066
+ class IMAPlibLoggerAdapter(LoggerAdapter):
2067
+ """Adapter preventing IMAP secrets from going to the logging facility."""
2068
+
2069
+ def process(self, msg, kwargs):
2070
+ # msg is usually unicode but see #367. Convert bytes to
2071
+ # unicode if required.
2072
+ if isinstance(msg, bytes):
2073
+ msg = msg.decode("ascii", "ignore")
2074
+
2075
+ for command in ("LOGIN", "AUTHENTICATE"):
2076
+ if msg.startswith(">") and command in msg:
2077
+ msg_start = msg.split(command)[0]
2078
+ msg = "{}{} **REDACTED**".format(msg_start, command)
2079
+ break
2080
+ return super().process(msg, kwargs)