[%@sdZdZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z m Z m Z ddlmZyddlZdZWnek rdZYnXdd d d d d gZdZdZdZdZddfZdZi'ddfd6dfd6ddddfd6dfd6dfd6dfd6ddfd6ddfd6ddfd6ddfd 6dfd!6dfd"6ddfd#6ddfd$6ddfd%6ddfd&6ddfd'6ddfd(6dfd)6ddddfd6ddfd*6ddfd+6ddddfd,6dfd-6dfd.6ddfd/6dfd06ddfd16ddfd26ddfd36ddfd46dfd56dfd66ddfd76dfd86ddfd96dfd:6dfd;6ddfd<6Zejd=Zejd>Zejd?Zejd@ejZ ejdAZ!ejdBZ"ejdCZ#ejdDejZ$GdEddZ%erGdFdGdGe%Z&ej'dGnGdHd d e%Z(GdIdJdJZ)dKj*dLZ+dMdNe,e+dOdDZ-dPd Z.dQd Z/dRd Z0dSd Z1e2dTkrddl3Z3ddl4Z4y)e3j3ej5dOddU\Z6Z7Wn:e3j8k rZ9zfff\Z6Z7WYddZ9[9XnXdZ:xWe6D]O\Z;Z9e;dVkr e<e9Zn(e;dWkr1e9Z:e7 r.e:fZ7nnqWe7 rHdXfZ7ne7dZ=e4j>Z?e4j4dYe?e=psdZfZ@d[ie?d\6d]d^6ZAd_e?e@ffd`daffdbdadcffdddffdeddddeAffdfdgdhffdiddffdjddkdlffdmdndoffdpdndqdrffdsffdtffduffdvfffZBdiffdwdxffdyd0dzffdwd{ffdedddeAffduffd|fffZCd}d~ZDye:re(e:ZEn e%e=ZEeEjFdkreBdOdZBneEjGdeEjHeEjGdeEjIfx!eBD]\ZJZ7eDeJe7q9WxheDdfddfD]QZKejLdeKZMeMreMjNdOZOneKj*dO ZOeDdeOfqlWxeCD]|\ZJZ7eDeJe7ZPeJe7fdyd0dzffkrqnePdO j*ZQeQ r%qneDdyd"deQdO dfqWeRdWn4eRde reRdej5dnYnXndS)zIMAP4 client. Based on RFC 2060. Public class: IMAP4 Public variable: Debug Public functions: Internaldate2tuple Int2AP ParseFlags Time2Internaldate z2.58N)datetimetimezone timedelta)DEFAULT_BUFFER_SIZETFIMAP4 IMAP4_streamInternaldate2tupleInt2AP ParseFlagsTime2Internaldates iZ IMAP4REV1i'AUTHSELECTEDAPPENDNONAUTH AUTHENTICATELOGOUT CAPABILITYCHECKCLOSECOPYCREATEDELETE DELETEACLEXAMINEEXPUNGEFETCHGETACL GETANNOTATIONGETQUOTA GETQUOTAROOTMYRIGHTSLISTLOGINLSUB NAMESPACENOOPPARTIAL PROXYAUTHRENAMESEARCHSELECTSETACL SETANNOTATIONSETQUOTASORTSTARTTLSSTATUSSTORE SUBSCRIBETHREADUID UNSUBSCRIBEs\+( (?P.*))?s.*FLAGS \((?P[^\)]*)\)s.*INTERNALDATE "(?P[ 0123][0-9])-(?P[A-Z][a-z][a-z])-(?P[0-9][0-9][0-9][0-9]) (?P[0-9][0-9]):(?P[0-9][0-9]):(?P[0-9][0-9]) (?P[-+])(?P[0-9][0-9])(?P[0-9][0-9])"s.*{(?P\d+)}$s \r\n|\r|\ns)\[(?P[A-Z-]+)( (?P[^\]]*))?\]s$\* (?P[A-Z-]+)( (?P.*))?s3\* (?P\d+) (?P[A-Z-]+)( (?P.*))?c@seZdZdZGdddeZGdddeZGdddeZded d Z d d Z d dZ ddZ deddZ ddZddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Zd3d4Zd5d6Zd7d8Z d9d:Z!d;d<Z"d=d>Z#d?d@dAdBZ$dCdDZ%dEdFZ&dGdHZ'dIdJZ(d?d@dKdLZ)dMdNZ*dOdPZ+dQdRZ,dSdTZ-dUdVZ.dWdXZ/dYdZZ0d[d\d]d^Z1d_d`Z2dadbZ3dcddZ4dedfZ5dgdhdiZ6djdkZ7dldmZ8dndoZ9dpdqZ:drdsZ;dtduZ<dvdwZ=dxdyZ>dzd{Z?d|d}Z@d~dZAddZBddZCddZDddZEddZFddZGddZHddZIddZJdgddZKddZLddZMddZNdgS)raIMAP4 client class. Instantiate with: IMAP4([host[, port]]) host - host's name (default: localhost); port - port number (default: standard IMAP4 port). All IMAP4rev1 commands are supported by methods of the same name (in lower-case). All arguments to commands are converted to strings, except for AUTHENTICATE, and the last argument to APPEND which is passed as an IMAP4 literal. If necessary (the string contains any non-printing characters or white-space and isn't enclosed with either parentheses or double quotes) each string is quoted. However, the 'password' argument to the LOGIN command is always quoted. If you want to avoid having an argument string quoted (eg: the 'flags' argument to STORE) then enclose the string in parentheses (eg: "(\Deleted)"). Each command returns a tuple: (type, [data, ...]) where 'type' is usually 'OK' or 'NO', and 'data' is either the text from the tagged response, or untagged results from command. Each 'data' is either a string, or a tuple. If a tuple, then the first part is the header of the response, and the second part contains the data (ie: 'literal' value). Errors raise the exception class .error(""). IMAP4 server errors raise .abort(""), which is a sub-class of 'error'. Mailbox status changes from READ-WRITE to READ-ONLY raise the exception class .readonly(""), which is a sub-class of 'abort'. "error" exceptions imply a program error. "abort" exceptions imply the connection should be reset, and the command re-tried. "readonly" exceptions imply the command should be re-tried. Note: to use this module, you must read the RFCs pertaining to the IMAP4 protocol, as the semantics of the arguments to each IMAP4 command are left to the invoker, not to mention the results. Also, most IMAP servers implement a sub-set of the commands available here. c@seZdZdS)z IMAP4.errorN)__name__ __module__ __qualname__r:r:/usr/lib/python3.4/imaplib.pyerrors r<c@seZdZdS)z IMAP4.abortN)r7r8r9r:r:r:r;aborts r=c@seZdZdS)zIMAP4.readonlyN)r7r8r9r:r:r:r;readonlys r>cCst|_d|_d|_i|_i|_d|_d|_d|_d|_ |j ||y|j Wn8t k ry|j Wntk rYnXYnXdS)Nrr?Fr)Debugdebugstateliteraltagged_commandsuntagged_responsescontinuation_response is_readonlytagnum_tls_establishedopen_connect ExceptionshutdownOSError)selfhostportr:r:r;__init__s$           zIMAP4.__init__cCs]ttjdd|_tjd|jdtj|_d|_d|_ i|_ |j dkr|j dt |j d |jn|j|_d |jkrd |_n-d |jkrd |_n|j|j|j|j dkr|j d|jfnx-tD]%}||jkr<q!n||_dSW|jddS)Niis(?Ps"\d+) (?P[A-Z]+) (?P.*) rzimaplib version %sznew IMAP4 connection, tag=%sZPREAUTHr OKrzCAPABILITIES: %rzserver not IMAP4 compliant)r randomZrandinttagprerecompileASCIItagre _cmd_log_len _cmd_log_idx_cmd_logrA_mesg __version__ _get_responseZwelcomerErBr<_get_capabilities capabilitiesAllowedVersionsPROTOCOL_VERSION)rOversionr:r:r;rKs0        zIMAP4._connectcCs3|tkrt||jStd|dS)NzUnknown IMAP4 command: '%s')CommandsgetattrlowerAttributeError)rOattrr:r:r; __getattr__s zIMAP4.__getattr__cCstj|j|jfS)N)socketZcreate_connectionrPrQ)rOr:r:r;_create_socketszIMAP4._create_socketcCs:||_||_|j|_|jjd|_dS)zSetup connection to remote server on "host:port" (default: localhost:standard IMAP4 port). This connection will be used by the routines: read, readline, send, shutdown. rbN)rPrQrosockmakefilefile)rOrPrQr:r:r;rJs  z IMAP4.opencCs|jj|S)zRead 'size' bytes from remote.)rsread)rOsizer:r:r;rtsz IMAP4.readcCsB|jjtd}t|tkr>|jdtn|S)zRead line from remote.rTzgot more than %d bytes)rsreadline_MAXLINElenr<)rOliner:r:r;rv szIMAP4.readlinecCs|jj|dS)zSend data to remote.N)rqZsendall)rOdatar:r:r;sendsz IMAP4.sendcCs}|jjz[y|jjtjWn=tk rf}z|jtjkrTnWYdd}~XnXWd|jjXdS)z Close I/O established in "open".N) rscloserqrMrnZ SHUT_RDWRrNerrnoZENOTCONN)rOer:r:r;rMs zIMAP4.shutdowncCs|jS)zfReturn socket instance used to connect to IMAP4 server. socket = .socket() )rq)rOr:r:r;rn$sz IMAP4.socketcCs]d}|jddg|\}}|dr8||fS|j\}}|j|||S)aReturn most recent 'RECENT' responses if any exist, else prompt server for an update using the 'NOOP' command. (typ, [data]) = .recent() 'data' is None if no new messages, else list of RECENT responses, most recent last. ZRECENTrUNrT)_untagged_responsenoop)rOnametypdatr:r:r;recent0s   z IMAP4.recentcCs|j|dg|jS)zReturn data for response 'code' if received, or None. Old value for response 'code' is cleared. (code, [data]) = .response(code) N)rupper)rOcoder:r:r;responseAszIMAP4.responsecCsd}|sd}n|rE|d|d fd krKd|}qKnd}|r`t|}nd}tjt||_|j||||S) zAppend message to named mailbox. (typ, [data]) = .append(mailbox, flags, date_time, message) All args except `message' can be None. rINBOXrrT()z(%s)Nr)rr)r MapCRLFsubCRLFrC_simple_command)rOmailboxflags date_timemessagerr:r:r;appendOs z IMAP4.appendcCsk|j}t|j|_|jd|\}}|dkrX|j|dnd|_||fS)asAuthenticate command - requires response processing. 'mechanism' specifies which authentication mechanism is to be used - it must appear in .capabilities in the form AUTH=. 'authobject' must be a callable object: data = authobject(response) It will be called to process server continuation responses; the response argument it is passed will be a bytes. It should return bytes data that will be base64 encoded and sent to the server. It should return None if the client abort response '*' should be sent instead. rrUrTr r)r_AuthenticatorprocessrCrr<rB)rOZ mechanismZ authobjectmechrrr:r:r; authenticatefs   zIMAP4.authenticatecCs.d}|j|\}}|j|||S)zT(typ, [data]) = .capability() Fetch capabilities list from server.r)rr)rOrrrr:r:r; capabilityszIMAP4.capabilitycCs |jdS)zRCheckpoint mailbox on server. (typ, [data]) = .check() r)r)rOr:r:r;checksz IMAP4.checkc Cs0z|jd\}}Wdd|_X||fS)zClose currently selected mailbox. Deleted messages are removed from writable mailbox. This is the recommended command before 'LOGOUT'. (typ, [data]) = .close() rNr )rrB)rOrrr:r:r;r|s z IMAP4.closecCs|jd||S)zCopy 'message_set' messages onto end of 'new_mailbox'. (typ, [data]) = .copy(message_set, new_mailbox) r)r)rO message_setZ new_mailboxr:r:r;copysz IMAP4.copycCs|jd|S)zPCreate new mailbox. (typ, [data]) = .create(mailbox) r)r)rOrr:r:r;createsz IMAP4.createcCs|jd|S)zPDelete old mailbox. (typ, [data]) = .delete(mailbox) r)r)rOrr:r:r;deletesz IMAP4.deletecCs|jd||S)zDelete the ACLs (remove any rights) set for who on mailbox. (typ, [data]) = .deleteacl(mailbox, who) r)r)rOrwhor:r:r; deleteaclszIMAP4.deleteaclcCs.d}|j|\}}|j|||S)zPermanently remove deleted items from selected mailbox. Generates 'EXPUNGE' response for each deleted message. (typ, [data]) = .expunge() 'data' is list of 'EXPUNGE'd message numbers in order received. r)rr)rOrrrr:r:r;expunges z IMAP4.expungecCs4d}|j|||\}}|j|||S)a#Fetch (parts of) messages. (typ, [data, ...]) = .fetch(message_set, message_parts) 'message_parts' should be a string of selected parts enclosed in parentheses, eg: "(UID BODY[TEXT])". 'data' are tuples of message part envelope and data. r)rr)rOrZ message_partsrrrr:r:r;fetchs z IMAP4.fetchcCs+|jd|\}}|j||dS)zXGet the ACLs for a mailbox. (typ, [data]) = .getacl(mailbox) rZACL)rr)rOrrrr:r:r;getaclsz IMAP4.getaclcCs1|jd|||\}}|j||dS)za(typ, [data]) = .getannotation(mailbox, entry, attribute) Retrieve ANNOTATIONs.r ANNOTATION)rr)rOrentryZ attributerrr:r:r; getannotationszIMAP4.getannotationcCs+|jd|\}}|j||dS)zGet the quota root's resource usage and limits. Part of the IMAP4 QUOTA extension defined in rfc2087. (typ, [data]) = .getquota(root) rQUOTA)rr)rOrootrrr:r:r;getquotaszIMAP4.getquotacCs^|jd|\}}|j||d\}}|j||d\}}|||gfS)zGet the list of quota roots for the named mailbox. (typ, [[QUOTAROOT responses...], [QUOTA responses]]) = .getquotaroot(mailbox) r rZ QUOTAROOT)rr)rOrrrZquotaZ quotarootr:r:r; getquotarootszIMAP4.getquotarootz""*cCs4d}|j|||\}}|j|||S)zList mailbox names in directory matching pattern. (typ, [data]) = .list(directory='""', pattern='*') 'data' is list of LIST responses. r")rr)rO directorypatternrrrr:r:r;listsz IMAP4.listcCsY|jd||j|\}}|dkrF|j|dnd|_||fS)zIdentify client using plaintext password. (typ, [data]) = .login(user, password) NB: 'password' will be quoted. r#rUrTr r)r_quoter<rB)rOuserpasswordrrr:r:r;logins $  z IMAP4.logincCs&|||_|_|jd|jS)zr Force use of CRAM-MD5 authentication. (typ, [data]) = .login_cram_md5(user, password) zCRAM-MD5)rrr_CRAM_MD5_AUTH)rOrrr:r:r;login_cram_md5szIMAP4.login_cram_md5cCs]ddl}t|jtr0|jjdn|j}|jd|j||djS)z1 Authobject to use with CRAM-MD5 authentication. rNr[ Zmd5)hmac isinstancerstrencoderZHMACZ hexdigest)rOZ challengerpwdr:r:r;r(s $ zIMAP4._CRAM_MD5_AUTHc Csd|_y|jd\}}Wn,ddtjddg}}YnX|jd|jkr{d|jdfS||fS)z|Shutdown connection to server. (typ, [data]) = .logout() Returns server 'BYE' response. rNOz%s: %sNBYE)rBrsysexc_inforMrE)rOrrr:r:r;logout0s ) z IMAP4.logoutcCs4d}|j|||\}}|j|||S)zList 'subscribed' mailbox names in directory matching pattern. (typ, [data, ...]) = .lsub(directory='""', pattern='*') 'data' are tuples of message part envelope and data. r$)rr)rOrrrrrr:r:r;lsub@sz IMAP4.lsubcCs+|jd|\}}|j||dS)zShow my ACLs for a mailbox (i.e. the rights that I have on mailbox). (typ, [data]) = .myrights(mailbox) r!)rr)rOrrrr:r:r;myrightsKszIMAP4.myrightscCs.d}|j|\}}|j|||S)zb Returns IMAP namespaces ala rfc2342 (typ, [data, ...]) = .namespace() r%)rr)rOrrrr:r:r; namespaceSszIMAP4.namespacecCs/|jdkr"|j|jn|jdS)zFSend NOOP command. (typ, [data]) = .noop() rVr&)rA_dump_urrEr)rOr:r:r;r]sz IMAP4.noopcCs:d}|j|||||\}}|j||dS)zFetch truncated part of a message. (typ, [data, ...]) = .partial(message_num, message_part, start, length) 'data' is tuple of message part envelope and data. r'r)rr)rOZ message_numZ message_partstartZlengthrrrr:r:r;partialhs!z IMAP4.partialcCsd}|jd|S)zAssume authentication as "user". Allows an authorised administrator to proxy into any user's mailbox. (typ, [data]) = .proxyauth(user) r()r)rOrrr:r:r; proxyauthts zIMAP4.proxyauthcCs|jd||S)zkRename old mailbox name to new. (typ, [data]) = .rename(oldmailbox, newmailbox) r))r)rOZ oldmailboxZ newmailboxr:r:r;renamesz IMAP4.renamecGsXd}|r-|j|d||\}}n|j||\}}|j|||S)zSearch mailbox for matching messages. (typ, [data]) = .search(charset, criterion, ...) 'data' is space separated list of matching message numbers. r*CHARSET)rr)rOcharsetZcriteriarrrr:r:r;searchs !z IMAP4.searchrFcCsi|_||_|r!d}nd}|j||\}}|dkr^d|_||fSd|_d|jkr| r|jdkr|j|jn|jd|n||jjd d gfS) atSelect a mailbox. Flush all untagged responses. (typ, [data]) = .select(mailbox='INBOX', readonly=False) 'data' is count of messages in mailbox ('EXISTS' response). Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so other responses should be obtained via .response('FLAGS') etc. rr+rUr rz READ-ONLYrTz%s is not writableEXISTSN)rErGrrBrArr>get)rOrr>rrrr:r:r;selects       z IMAP4.selectcCs|jd|||S)zZSet a mailbox acl. (typ, [data]) = .setacl(mailbox, who, what) r,)r)rOrrZwhatr:r:r;setaclsz IMAP4.setaclcGs+|jd|\}}|j||dS)z_(typ, [data]) = .setannotation(mailbox[, entry, attribute]+) Set ANNOTATIONs.r-r)rr)rOargsrrr:r:r; setannotationszIMAP4.setannotationcCs.|jd||\}}|j||dS)ziSet the quota root's resource limits. (typ, [data]) = .setquota(root, limits) r.r)rr)rOrZlimitsrrr:r:r;setquotaszIMAP4.setquotacGs^d}|d|dfdkr-d|}n|j||||\}}|j|||S) zIMAP4rev1 extension SORT command. (typ, [data]) = .sort(sort_criteria, charset, search_criteria, ...) r/rrTrrz(%s)r)rr)rr)rOZ sort_criteriarsearch_criteriarrrr:r:r;sorts  z IMAP4.sortNcCsd}ts|jdn|jr9|jdn||jkrZ|jdn|dkrutj}n|j|\}}|dkr|j|j d|j |_ |j j d|_ d|_|j n|jd |j|||S) Nr0zSSL support missingzTLS session already establishedzTLS not supported by serverrUserver_hostnamerpTzCouldn't establish TLS session)HAVE_SSLr<rIr=rdssl_create_stdlib_contextr wrap_socketrqrPrrrsrcr)rO ssl_contextrrrr:r:r;starttlss$     zIMAP4.starttlscCs4d}|j|||\}}|j|||S)zpRequest named status conditions for mailbox. (typ, [data]) = .status(mailbox, names) r1)rr)rOrnamesrrrr:r:r;statussz IMAP4.statuscCsX|d|dfd kr'd|}n|jd|||\}}|j||dS) zAlters flag dispositions for messages in mailbox. (typ, [data]) = .store(message_set, command, flags) rrTrrz(%s)r2rr)rr)rr)rOrcommandrrrr:r:r;stores z IMAP4.storecCs|jd|S)zYSubscribe to new mailbox. (typ, [data]) = .subscribe(mailbox) r3)r)rOrr:r:r; subscribe szIMAP4.subscribecGs7d}|j||||\}}|j|||S)zIMAPrev1 extension THREAD command. (type, [data]) = .thread(threading_algorithm, charset, search_criteria, ...) r4)rr)rOZthreading_algorithmrrrrrr:r:r;threadsz IMAP4.threadcGs|j}|tkr.|jd|n|jt|krp|jd||jdjt|fnd}|j|||\}}|d kr|}nd}|j|||S) zExecute "command arg ..." with messages identified by UID, rather than message number. (typ, [data]) = .uid(command, arg1, arg2, ...) Returns response appropriate to 'command'. zUnknown IMAP4 UID command: %sz9command %s illegal in state %s, only allowed in states %sz, r5r*r/r4r)zSEARCHzSORTzTHREAD)rrhr<rBjoinrr)rOrrrrrr:r:r;uids      z IMAP4.uidcCs|jd|S)z_Unsubscribe from old mailbox. (typ, [data]) = .unsubscribe(mailbox) r6)r)rOrr:r:r; unsubscribe8szIMAP4.unsubscribecGs;|j}|tkr+|jft|.xatom(name, arg, ...) Returns response appropriate to extension command `name'. )rrhrBr)rOrrr:r:r;xatom@s  z IMAP4.xatomcCs|dkrd}n|j}|jdkr\|jd|t|j|d|fn||kr|||j|n |g|||jjd}|r:|j|djddndS)NrrTasciireplacer)rErr=decode)rOZbyer:r:r; _check_byedszIMAP4._check_byec Gs|jt|krKd|_|jd||jdjt|fnx*dD]"}||jkrR|j|=qRqRWd|jkr|j r|jdn|j}t |d}|d |}xO|D]G}|dkrqnt |t r t |d}n|d |}qW|j}|dk rd|_t |t |j kr`|}qd}|t d t|d}n|jd kr|jd |n|jd |y|j|tWn8tk r } z|jd | WYdd} ~ XnX|dkr|Sxx!|jr@|j|r |Sq W|rY||j}n|jd kr|jdt|ny|j||jtWn8tk r} z|jd | WYdd} ~ XnX|sPqqW|S)Nz9command %s illegal in state %s, only allowed in states %sz, rUrBADz READ-ONLYz#mailbox status changed to READ-ONLYr[ z {%s}z> %rzsocket error: %szwrite literal size %s)zOKzNOr)rBrhrCr<rrErGr>_new_tagbytesrrtype_commandrxrAr`_logr{rrNr=rbrDrF) rOrrrtagrzargrCZ literatorvalr:r:r;rjsh             &   &zIMAP4._commandcCs|dkr|jny|j|\}}Wn|jk ru}z|jd||fWYdd}~XnA|jk r}z|jd||fWYdd}~XnX|dkr|jn|dkr|jd|||fn||fS)Nrzcommand: %s => %srz%s command error: %s %s)r_get_tagged_responser=r<)rOrrrrzrr:r:r;_command_completes  +,   zIMAP4._command_completecCsk|j\}}|dgkr3|jdnt|dd}|j}t|j|_dS)Nz"no CAPABILITY response from serverrTr[r)rr<rrtuplesplitrd)rOrrr:r:r;rcs  zIMAP4._get_capabilitiescCs|j}|j|j|r|jjd}||jkrX|jd|n|jjd}t|d}|jjd}||gf|j| %r)matchrrAr`rgroups)rOZcresr:r:r;rOs&z IMAP4._matchcCs@|jtt|jd}|jd|_d|j|<|S)Nr[rT)rXrrrHrD)rOrr:r:r;r[s zIMAP4._new_tagcCs0|jdd}|jdd}d|dS)N\z\\"z\")r)rOrr:r:r;rcsz IMAP4._quotecGs|j||j||S)N)rr)rOrrr:r:r;rkszIMAP4._simple_commandcCsw|dkr||fS||jkr2|dgfS|jj|}|jdkrm|jd||fn||fS)Nrrzuntagged_responses[%s] => %s)rEpoprAr`)rOrrrrzr:r:r;rps   zIMAP4._untagged_responsecCsl|dkrtj}ntjdtj|}tjjd||dd|ftjjdS)Nz%M:%Sz %s.%02d %s d)timestrftime localtimerstderrwriteflush)rOrZsecsZtmr:r:r;r`~s  %z IMAP4._mesgcCsU|j}|sdSd}tdd|}|jd||j|fdS)Nz cSs3d|d|ddr+dj|dp.dfS)Nz%s: "%s"rrTz" "r?)r)xr:r:r;sz IMAP4._dump_ur..zuntagged responses dump:%s%s)itemsmapr`r)rOdictltr:r:r;rs  zIMAP4._dump_urcCsM|tjf|j|j<|jd7_|j|jkrId|_ndS)NrTr)rr_r^r])rOryr:r:r;rsz IMAP4._logc Cs|jdt|j|j|j}}xY|ry|j|j|WnYnX|d7}||jkr{d}n|d8}q0WdS)Nzlast %d IMAP4 interactions:rTr)r`rxr_r^r])rOinr:r:r;r s   zIMAP4.print_log)Or7r8r9__doc__rLr<r=r> IMAP4_PORTrRrKrmrorJrtrvr{rMrnrrrrrrr|rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrcrbrrrrrrrr`rrr r:r:r:r;rvs , *                                  M  P        c@sOeZdZdZdedddddZddZdedd ZdS) IMAP4_SSLa3IMAP4 client class over SSL connection Instantiate with: IMAP4_SSL([host[, port[, keyfile[, certfile[, ssl_context]]]]]) host - host's name (default: localhost); port - port number (default: standard IMAP4 SSL port); keyfile - PEM formatted file that contains your private key (default: None); certfile - PEM formatted certificate chain file (default: None); ssl_context - a SSLContext object that contains your certificate chain and private key (default: None) Note: if ssl_context is provided, then parameters keyfile or certfile should not be set otherwise ValueError is raised. for more documentation see the docstring of the parent class IMAP4. r?NcCs|dk r'|dk r'tdn|dk rN|dk rNtdn||_||_|dkrtjd|d|}n||_tj|||dS)Nz8ssl_context and keyfile arguments are mutually exclusivez9ssl_context and certfile arguments are mutually exclusivecertfilekeyfile) ValueErrorr'r&rrrrrR)rOrPrQr'r&rr:r:r;rRs     zIMAP4_SSL.__init__cCs(tj|}|jj|d|jS)Nr)rrorrrP)rOrqr:r:r;roszIMAP4_SSL._create_socketcCstj|||dS)zSetup connection to remote server on "host:port". (default: localhost:standard IMAP4 SSL port). This connection will be used by the routines: read, readline, send, shutdown. N)rrJ)rOrPrQr:r:r;rJszIMAP4_SSL.open)r7r8r9r#IMAP4_SSL_PORTrRrorJr:r:r:r;r%s  r%c@sdeZdZdZddZddddZddZd d Zd d Zd dZ dS)rzIMAP4 client class over a stream Instantiate with: IMAP4_stream(command) where "command" is a string that can be passed to subprocess.Popen() for more documentation see the docstring of the parent class IMAP4. cCs||_tj|dS)N)rrrR)rOrr:r:r;rRs zIMAP4_stream.__init__Nc Csd|_d|_d|_d|_tj|jdtdtjdtjdddd|_ |j j |_ |j j |_ dS)zSetup a stream connection. This connection will be used by the routines: read, readline, send, shutdown. NbufsizestdinstdoutshellTZ close_fds)rPrQrqrs subprocessPopenrrPIPErr+ writefiler,readfile)rOrPrQr:r:r;rJs    zIMAP4_stream.opencCs|jj|S)zRead 'size' bytes from remote.)r2rt)rOrur:r:r;rtszIMAP4_stream.readcCs |jjS)zRead line from remote.)r2rv)rOr:r:r;rvszIMAP4_stream.readlinecCs!|jj||jjdS)zSend data to remote.N)r1rr)rOrzr:r:r;r{szIMAP4_stream.sendcCs+|jj|jj|jjdS)z Close I/O established in "open".N)r2r|r1rwait)rOr:r:r;rMs  zIMAP4_stream.shutdown) r7r8r9r#rRrJrtrvr{rMr:r:r:r;rs     c@sFeZdZdZddZddZddZdd Zd S) rzcPrivate class to provide en/decoding for base64-based authentication conversation. cCs ||_dS)N)r)rOZmechinstr:r:r;rRsz_Authenticator.__init__cCs5|j|j|}|dkr(dS|j|S)Nr)rrr)rOrzZretr:r:r;rs z_Authenticator.processcCsd}t|tr'|jd}nxw|rt|dkre|dd}|dd}n |}d}tj|}|r*||dd}q*q*W|S)Nrr[0rTr)rrrrxbinasciiZ b2a_base64)rOinpZoupr r~r:r:r;rs  z_Authenticator.encodecCs|s dStj|S)Nr)r5Z a2b_base64)rOr6r:r:r;r7sz_Authenticator.decodeN)r7r8r9r#rRrrrr:r:r:r;rs    rz0 Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov DecrcCs)i|]\}}|d|jqS)rT)r).0r"rr:r:r; =s r8rTc Cs7tj|}|sdSt|jd}|jd}t|jd}t|jd}t|jd}t|jd}t|jd}t|jd } t|jd } | d | d } |d kr| } n||||||dddf } tj| | } tj| S)zParse an IMAP4 INTERNALDATE string. Return corresponding local time. The return value is a time.struct_time tuple or None if the string has wrong format. Nmonzonendayyearhourminseczonehzonem<-rTrrr) InternalDater Mon2numrrcalendarZtimegmrr)rrr9r:r;r<r=r>r?r@rAZzoneZttutcr:r:r;r?s$  !cCs\d}d}tt|}x7|rWt|d\}}|||d|}q!W|S)z-Convert integer to A-P string representation.rsABCDEFGHIJKLMNOPrT)rabsdivmod)ZnumrZAPmodr:r:r;r bs cCs2tj|}|sfSt|jdjS)z-Convert IMAP4 flags response to python tuple.r)Flagsr rrr)rrr:r:r;r oscCst|ttfr3tj|tjj}n6t|try |j }Wntt k rt j r|d}|d krt j t j|d}nt jt jf| }n t j }YnXtd|}tdt||dd}not|tr0|jdkr'tdn|}n9t|tr]|d|d fdkr]|Std d jt|j}|j|S)aConvert date_time to IMAP4 INTERNALDATE representation. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'. The date_time argument can be a number (int or float) representing seconds since epoch (as returned by time.time()), a 9-tuple representing local time, an instance of time.struct_time (as returned by time.localtime()), an aware datetime instance or a double-quoted string. In the last case, it is assumed to already be in the correct format. rTZsecondstzinfoNzdate_time must be awarerrzdate_time not of a known typez"%d-{}-%Y %H:%M:%S %z"rr)rr)rrfloatrZ fromtimestamprrGZ astimezonerZ tm_gmtoffrkrZdaylightrZmktimeZaltzonerrNr(rformatMonthsZmonthr)rZdtZgmtoffZdstZdeltaZfmtr:r:r;r zs0       % ) __main__zd:s:z-dz-sr?zIMAP password for %s on %s: Z localhostzJFrom: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)sdata...%(lf)sr Zlfrrz /tmp/xxx 1rz/tmp/yyyz /tmp/yyz 2rrz/tmpzyy*rrZSUBJECTZtestr1z(FLAGS INTERNALDATE RFC822)rFLAGSz (\Deleted)rrrr|rZ UIDVALIDITYrZALLrrcCsitjd||ftt||\}}tjd|||f|dkre|dn|S)Nz%s %sz %s => %s %srr)Mr`ri)cmdrrrr:r:r;runs  rYzPROTOCOL_VERSION = %szCAPABILITIES = %rz/tmp/zyy%z .*"([^"]+)"$rz%sz:(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)z All tests OK.z Tests failed.z8 If you would like to see debugging output, try: %s -d5 )Sr#rar5r}rWrYrnr.rrrFrrriorrr ImportError__all__rr@r$r)rerwrhrZrrLrDr[rrrrrrr%rrrrrR enumeraterErr r r r7ZgetoptZgetpassargvZoptlistrr<rZstream_commandZoptrrPZgetuserZUSERZPASSWDZ test_mesgZ test_seq1Z test_seq2rYrWrBr`rfrdrXZmlr rrpathrrprintr:r:r:r; s8 l                                         009,# # ) )%