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