a DOgx+@sdZdZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z m Z m Z ddlmZzddlZdZWneydZYn0gdZd ZdZd Zd Zd Zd Zddddddddddddddddddddddddddddddddddddddddddd*ZedZedZedZedejZ edZ!edZ"edZ#edejZ$dZ%dZ&GdddZ'erGddde'Z(e)dGd d!d!e'Z*Gd"d#d#Z+d$,d%Z-d&d'e.e-d(dDZ/d)d*Z0d+d,Z1d-d.Z2d/d0Z3e4d1krddl5Z5ddl6Z6ze55ej7d(dd2\Z8Z9Wn0e5j:yjZ;zd3\Z8Z9WYdZ;[;n dZ;[;00dZe;Zne=d5krte;Zd?d@dAddeCffdBdCdDdEdFdGdHdIdJfZDdKdLdMdNd@dddeCffdIdOfZEdPdQZFze<r\e*e<ZGne'e?ZGeGjHdRkr|eDd(dZDeGIdSeGjJeGIdTeGjKfeDD]\ZLZ9eFeLe9qeFdUdVD]qeFdZd[d\eSdXd]fqeTd^Wn.eTd_eseTd`ej7dYn0dS)azIMAP4 client. Based on RFC 2060. Public class: IMAP4 Public variable: Debug Public functions: Internaldate2tuple Int2AP ParseFlags Time2Internaldate z2.58N)datetimetimezone timedelta)DEFAULT_BUFFER_SIZETF)IMAP4 IMAP4_streamInternaldate2tupleInt2AP ParseFlagsTime2Internaldate i)Z IMAP4REV1ri@B)AUTHSELECTED)NONAUTH)rrrLOGOUT)r)r)*APPEND AUTHENTICATE CAPABILITYCHECKCLOSECOPYCREATEDELETE DELETEACLENABLEEXAMINEEXPUNGEFETCHGETACL GETANNOTATIONGETQUOTA GETQUOTAROOTMYRIGHTSLISTLOGINrLSUBZMOVE NAMESPACENOOPPARTIAL PROXYAUTHRENAMESEARCHSELECTSETACL SETANNOTATIONSETQUOTASORTSTARTTLSSTATUSSTORE SUBSCRIBETHREADUID UNSUBSCRIBEUNSELECTs\+( (?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 fd d Z d d Z ddZ ddZ ddZ ddZddZddZded fddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2d3Zd4d5Zd6d7Zd8d9Z d:d;Z!dd?Z#d@dAZ$dBdCZ%dDdEZ&dFdGZ'dHdIZ(ddLdMZ)dNdOZ*dPdQZ+dRdSZ,dTdUZ-ddVdWZ.dXdYZ/dZd[Z0d\d]Z1d^d_Z2d`daZ3dbdcZ4dddeZ5ddhdiZ6djdkZ7dldmZ8dndoZ9dpdqZ:ddrdsZ;dtduZdzd{Z?d|d}Z@d~dZAddZBddZCddZDddZEddZFddZGddZHddZIdddZJddZKddZLddZMddZNddZOddZPdddZQddZRddZSddZTd S)raIMAP4 client class. Instantiate with: IMAP4([host[, port[, timeout=None]]]) host - host's name (default: localhost); port - port number (default: standard IMAP4 port). timeout - socket timeout (default: None) If timeout is not given or is None, the global default socket timeout is used 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@s eZdZdS)z IMAP4.errorN__name__ __module__ __qualname__r>r>/usr/lib64/python3.9/imaplib.pyerrorr@c@s eZdZdS)z IMAP4.abortNr:r>r>r>r?abortrArBc@s eZdZdS)zIMAP4.readonlyNr:r>r>r>r?readonlyrArCNc Cst|_d|_d|_i|_i|_d|_d|_d|_d|_ | | |||z | Wn4t yz |WntyYn0Yn0dS)NrrDFr)Debugdebugstateliteraltagged_commandsuntagged_responsescontinuation_response is_readonlytagnum_tls_established _mode_asciiopen_connect ExceptionshutdownOSErrorselfhostporttimeoutr>r>r?__init__s&    zIMAP4.__init__cCs0d|_d|_tttj|_tttj|_dS)NFascii) utf8_enabled _encodingrecompile_LiteralASCIILiteral_Untagged_statusUntagged_statusrVr>r>r?rOszIMAP4._mode_asciicCs(d|_d|_tt|_tt|_dS)NTutf-8)r\r]r^r_r`rbrcrdrer>r>r? _mode_utf8s zIMAP4._mode_utf8cCsttdd|_td|jdtj|_d|_d|_ i|_ |j dkrf| dt | d |j||_d |jvrd |_nd |jvrd |_n ||j||j dkr| d|jftD]}||jvrq||_dS|ddS)Niis(?Ps"\d+) (?P[A-Z]+) (?P.*) rzimaplib version %sznew IMAP4 connection, tag=%sZPREAUTHrOKrzCAPABILITIES: %rzserver not IMAP4 compliant)r randomrandinttagprer^r_ratagre _cmd_log_len _cmd_log_idx_cmd_logrF_mesg __version__ _get_responseZwelcomerJrGr@_get_capabilities capabilitiesAllowedVersionsPROTOCOL_VERSION)rVversionr>r>r?rQs:       zIMAP4._connectcCs&|tvrt||Std|dS)NzUnknown IMAP4 command: '%s')CommandsgetattrlowerAttributeError)rVattrr>r>r? __getattr__ szIMAP4.__getattr__cCs|SNr>rer>r>r? __enter__szIMAP4.__enter__cGs2|jdkrdSz |Wnty,Yn0dS)Nr)rGlogoutrT)rVargsr>r>r?__exit__s    zIMAP4.__exit__cCs`|dur|std|jsdn|j}td||j|j||jf}|durVt||St|S)Nz0Non-blocking socket (timeout=0) is not supportedz imaplib.open) ValueErrorrWsysauditrXsocketcreate_connection)rVrYrWaddressr>r>r?_create_socket#s   zIMAP4._create_socketcCs*||_||_|||_|jd|_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)rWrXrsockmakefilefilerUr>r>r?rP0s z IMAP4.opencCs |j|SzRead 'size' bytes from remote.)rreadrVsizer>r>r?r<sz IMAP4.readcCs.|jtd}t|tkr*|dt|S)Read line from remote.rizgot more than %d bytes)rreadline_MAXLINElenr@rVliner>r>r?rAs zIMAP4.readlinecCstd|||j|dS)Send data to remote.z imaplib.sendN)rrrsendallrVdatar>r>r?sendIsz IMAP4.sendc Cs|jzdz|jtjWnBty`}z*|jtjkrLt |dddkrLWYd}~n d}~00W|jn |j0dS) Close I/O established in "open".winerrorri&'N) rcloserrSr SHUT_RDWRrTerrnoZENOTCONNr|)rVexcr>r>r?rSOs  zIMAP4.shutdowncCs|jS)zfReturn socket instance used to connect to IMAP4 server. socket = .socket() )rrer>r>r?r_sz IMAP4.socketcCsBd}|ddg|\}}|dr(||fS|\}}||||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. ZRECENTrjN)_untagged_responsenooprVnametypdatr>r>r?recentks  z IMAP4.recentcCs||dg|S)zReturn data for response 'code' if received, or None. Old value for response 'code' is cleared. (code, [data]) = .response(code) N)rupper)rVcoder>r>r?response|szIMAP4.responsecCsxd}|s d}|r.|d|dfdkr2d|}nd}|r@t|}nd}tt|}|jrbd|d }||_|||||S) zAppend message to named mailbox. (typ, [data]) = .append(mailbox, flags, date_time, message) All args except `message' can be None. rINBOXrr()(%s)NsUTF8 ())r MapCRLFsubCRLFr\rH_simple_command)rVmailboxflags date_timemessagerrHr>r>r?appends    z IMAP4.appendcCsP|}t|j|_|d|\}}|dkrB||dddd|_||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. rrjrrfreplacer)r_AuthenticatorprocessrHrr@decoderG)rVZ mechanismZ authobjectmechrrr>r>r? authenticates zIMAP4.authenticatecCs d}||\}}||||S)zT(typ, [data]) = .capability() Fetch capabilities list from server.rrrrr>r>r? capabilityszIMAP4.capabilitycCs |dS)zRCheckpoint mailbox on server. (typ, [data]) = .check() rrrer>r>r?checksz IMAP4.checkcCs*z|d\}}Wd|_nd|_0||fS)zClose currently selected mailbox. Deleted messages are removed from writable mailbox. This is the recommended command before 'LOGOUT'. (typ, [data]) = .close() rrrrGrVrrr>r>r?rsz IMAP4.closecCs|d||S)zCopy 'message_set' messages onto end of 'new_mailbox'. (typ, [data]) = .copy(message_set, new_mailbox) rr)rV message_setZ new_mailboxr>r>r?copysz IMAP4.copycCs |d|S)zPCreate new mailbox. (typ, [data]) = .create(mailbox) rrrVrr>r>r?createsz IMAP4.createcCs |d|S)zPDelete old mailbox. (typ, [data]) = .delete(mailbox) rrrr>r>r?deletesz IMAP4.deletecCs|d||S)zDelete the ACLs (remove any rights) set for who on mailbox. (typ, [data]) = .deleteacl(mailbox, who) rr)rVrwhor>r>r? deleteaclszIMAP4.deleteaclcCsHd|jvrtd|d|\}}|dkr@d|vr@|||fS)zlSend an RFC5161 enable string to the server. (typ, [data]) = .enable(capability) rzServer does not support ENABLErjz UTF8=ACCEPT)rwrr@rrrg)rVrrrr>r>r?enables   z IMAP4.enablecCs d}||\}}||||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. rrrr>r>r?expunge s z IMAP4.expungecCs$d}||||\}}||||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. rr)rVrZ message_partsrrrr>r>r?fetchs z IMAP4.fetchcCs|d|\}}|||dS)zXGet the ACLs for a mailbox. (typ, [data]) = .getacl(mailbox) rZACLrrVrrrr>r>r?getacl(sz IMAP4.getaclcCs"|d|||\}}|||dS)za(typ, [data]) = .getannotation(mailbox, entry, attribute) Retrieve ANNOTATIONs.r ANNOTATIONr)rVrentryZ attributerrr>r>r? getannotation1szIMAP4.getannotationcCs|d|\}}|||dS)zGet the quota root's resource usage and limits. Part of the IMAP4 QUOTA extension defined in rfc2087. (typ, [data]) = .getquota(root) r!QUOTAr)rVrootrrr>r>r?getquota9szIMAP4.getquotacCs@|d|\}}|||d\}}|||d\}}|||gfS)zGet the list of quota roots for the named mailbox. (typ, [[QUOTAROOT responses...], [QUOTA responses]]) = .getquotaroot(mailbox) r"rZ QUOTAROOTr)rVrrrZquotaZ quotarootr>r>r? getquotarootDszIMAP4.getquotaroot""*cCs$d}||||\}}||||S)zList mailbox names in directory matching pattern. (typ, [data]) = .list(directory='""', pattern='*') 'data' is list of LIST responses. r$rrVZ directorypatternrrrr>r>r?listOsz IMAP4.listcCs<|d|||\}}|dkr.||dd|_||fS)zIdentify client using plaintext password. (typ, [data]) = .login(user, password) NB: 'password' will be quoted. r%rjrr)r_quoter@rG)rVuserpasswordrrr>r>r?login[s z IMAP4.logincCs|||_|_|d|jS)zr Force use of CRAM-MD5 authentication. (typ, [data]) = .login_cram_md5(user, password) zCRAM-MD5)rrr_CRAM_MD5_AUTH)rVrrr>r>r?login_cram_md5iszIMAP4.login_cram_md5cCsBddl}t|jtr |jdn|j}|jd|||dS)z1 Authobject to use with CRAM-MD5 authentication. rNrf md5)hmac isinstancerstrencoderHMAC hexdigest)rVZ challengerpwdr>r>r?rrs zIMAP4._CRAM_MD5_AUTHcCs$d|_|d\}}|||fS)z|Shutdown connection to server. (typ, [data]) = .logout() Returns server 'BYE' response. r)rGrrSrr>r>r?rzsz IMAP4.logoutcCs$d}||||\}}||||S)zList 'subscribed' mailbox names in directory matching pattern. (typ, [data, ...]) = .lsub(directory='""', pattern='*') 'data' are tuples of message part envelope and data. r&rrr>r>r?lsubsz IMAP4.lsubcCs|d|\}}|||dS)zShow my ACLs for a mailbox (i.e. the rights that I have on mailbox). (typ, [data]) = .myrights(mailbox) r#rrr>r>r?myrightsszIMAP4.myrightscCs d}||\}}||||S)zb Returns IMAP namespaces ala rfc2342 (typ, [data, ...]) = .namespace() r'rrr>r>r? namespaceszIMAP4.namespacecCs |jdkr||j|dS)zFSend NOOP command. (typ, [data]) = .noop() rkr()rF_dump_urrJrrer>r>r?rs  z IMAP4.noopcCs(d}||||||\}}|||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)rr)rVZ message_numZ message_partstartlengthrrrr>r>r?partialsz IMAP4.partialcCsd}|d|S)zAssume authentication as "user". Allows an authorised administrator to proxy into any user's mailbox. (typ, [data]) = .proxyauth(user) r*r)rVrrr>r>r? proxyauths zIMAP4.proxyauthcCs|d||S)zkRename old mailbox name to new. (typ, [data]) = .rename(oldmailbox, newmailbox) r+r)rVZ oldmailboxZ newmailboxr>r>r?renamesz IMAP4.renamecGsXd}|r4|jrtd|j|d|g|R\}}n|j|g|R\}}||||S)zSearch mailbox for matching messages. (typ, [data]) = .search(charset, criterion, ...) 'data' is space separated list of matching message numbers. If UTF8 is enabled, charset MUST be None. r,z'Non-None charset not valid in UTF8 modeCHARSET)r\rr@rr)rVcharsetZcriteriarrrr>r>r?searchs z IMAP4.searchrFcCsi|_||_|rd}nd}|||\}}|dkr@d|_||fSd|_d|jvrx|sx|jdkrj||j|d|||jd 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-rjrr READ-ONLYriz%s is not writableEXISTSN)rJrLrrGrFrrCget)rVrrCrrrr>r>r?selects"    z IMAP4.selectcCs|d|||S)zZSet a mailbox acl. (typ, [data]) = .setacl(mailbox, who, what) r.r)rVrrZwhatr>r>r?setaclsz IMAP4.setaclcGs$|jdg|R\}}|||dS)z_(typ, [data]) = .setannotation(mailbox[, entry, attribute]+) Set ANNOTATIONs.r/rr)rVrrrr>r>r? setannotation szIMAP4.setannotationcCs |d||\}}|||dS)ziSet the quota root's resource limits. (typ, [data]) = .setquota(root, limits) r0rr)rVrZlimitsrrr>r>r?setquotaszIMAP4.setquotacGsHd}|d|dfdkr d|}|j|||g|R\}}||||S)zIMAP4rev1 extension SORT command. (typ, [data]) = .sort(sort_criteria, charset, search_criteria, ...) r1rrrrr)rVZ sort_criteriarsearch_criteriarrrr>r>r?sorts z IMAP4.sortcCsd}ts|d|jr"|d||jvr6|d|durFt}||\}}|dkr|j|j |j d|_ |j d|_ d|_| n |d ||||S) Nr2zSSL support missingzTLS session already establishedzTLS not supported by serverrjZserver_hostnamerTzCouldn't establish TLS session)HAVE_SSLr@rNrBrwssl_create_stdlib_contextr wrap_socketrrWrrrvr)rV ssl_contextrrrr>r>r?starttls)s&      zIMAP4.starttlscCs$d}||||\}}||||S)zpRequest named status conditions for mailbox. (typ, [data]) = .status(mailbox, names) r3r)rVrnamesrrrr>r>r?status@sz IMAP4.statuscCs>|d|dfdkrd|}|d|||\}}|||dS)zAlters flag dispositions for messages in mailbox. (typ, [data]) = .store(message_set, command, flags) rrrrr4rr)rVrcommandrrrr>r>r?storeLsz IMAP4.storecCs |d|S)zYSubscribe to new mailbox. (typ, [data]) = .subscribe(mailbox) r5rrr>r>r? subscribeWszIMAP4.subscribecGs,d}|j|||g|R\}}||||S)zIMAPrev1 extension THREAD command. (type, [data]) = .thread(threading_algorithm, charset, search_criteria, ...) r6r)rVZthreading_algorithmrrrrrr>r>r?thread_sz IMAP4.threadc Gs|}|tvr|d||jt|vrL|d||jdt|fd}|j||g|R\}}|dvrv|}nd}||||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: %s9command %s illegal in state %s, only allowed in states %s, r7)r,r1r6r)rr{r@rGjoinrr)rVrrrrrr>r>r?uidis z IMAP4.uidcCs |d|S)z_Unsubscribe from old mailbox. (typ, [data]) = .unsubscribe(mailbox) r8rrr>r>r? unsubscribeszIMAP4.unsubscribecCs*z|d\}}Wd|_nd|_0||fS)aMFree server's resources associated with the selected mailbox and returns the server to the authenticated state. This command performs the same actions as CLOSE, except that no messages are permanently removed from the currently selected mailbox. (typ, [data]) = .unselect() r9rr)rVrrr>r>r?unselects zIMAP4.unselectcGs.|}|tvr|jft|<|j|g|RS)aAllow simple extension commands notified by server in CAPABILITY response. Assumes command is legal in current state. (typ, [data]) = .xatom(name, arg, ...) Returns response appropriate to extension command `name'. )rr{rGrrVrrr>r>r?xatoms  z IMAP4.xatomc Csb|dur d}|j}|jdkr<|d|t||d|f||vrT|||n |g||<dS)NrAz#untagged_responses[%s] %s += ["%r"]rD)rJrFrsrrr)rVrrurr>r>r?_append_untaggeds zIMAP4._append_untaggedcCs,|jd}|r(||d|jddS)NBYErr)rJrrBrr])rVbyer>r>r? _check_byes zIMAP4._check_byec Gs6|jt|vr4d|_|d||jdt|fdD]}||jvr8|j|=q8d|jvrj|jsj|d|}t ||j }|d|}|D]0}|durqt |t rt ||j }|d|}q|j}|dur d|_t |t |jur|}nd}|t dt||j }|jdkr&|d |n|d |z||tWn4tyz} z|d | WYd} ~ n d} ~ 00|dur|S|r|j|r|Sq|r||j}|jdkr|d t|z|||tWn4ty"} z|d | WYd} ~ n d} ~ 00|sq2q|S) NrrrjNOBADrz#mailbox status changed to READ-ONLY z {%s}z> %rzsocket error: %szwrite literal size %s)rGr{rHr@rrJrLrC_new_tagbytesr]rrtype_commandrrFrs_logrrrTrBrurIrK) rVrrrtagrargrHZ literatorvalr>r>r?r+sj            $      $zIMAP4._commandc Cs|dk}|s|z|j||d\}}Wnn|jyb}z|d||fWYd}~n@d}~0|jy}z|d||fWYd}~n d}~00|s||dkr|d|||f||fS)Nr) expect_byezcommand: %s => %sr%z%s command error: %s %s)r"_get_tagged_responserBr@)rVrr-rrrr/r>r>r?_command_completes&(zIMAP4._command_completecCsJ|\}}|dgkr |dt|d|j}|}t||_dS)Nz"no CAPABILITY response from serverr)rr@rr]rtuplesplitrwrr>r>r?rv#s    zIMAP4._get_capabilitiescCs|}||j|rr|jd}||jvr:|d||jd}t||j}|jd}||gf|j|<nd}|t |s||j |r|jd}|jdur|t |r|jd|_ dS|d||jd}t||j}|jd}|durd}|r|d|}||j |rvt|jd }|jd krP|d |||}||||f|}q||||d vr|t|r|jd}t||j}|||jd|jd kr|dvr|d||f|S)Nr-zunexpected tagged response: %rr*rZdata2zunexpected response: %rrAr&rr'zread literal size %sr#ri)r$r%r z%s response: %r) _get_line_matchromogrouprIrBrr]Untagged_responserd ContinuationrKrbintrFrsrr Response_code)rVrespr-rrZdat2rrr>r>r?ru,sL                  zIMAP4._get_responsec Cs|j|}|dur|j|=|S|rDd}|j|d}|durD||fS|z |Wq|jy}z |jdkr||WYd}~qd}~00qdS)Nr ri)rIrJpopr"rurBrF print_log)rVr-r0resultrr!r/r>r>r?r1|s    zIMAP4._get_tagged_responsecCsf|}|s|d|ds.|d||dd}|jdkrT|d|n|d||S)Nzsocket error: EOFr z#socket error: unterminated line: %rr'z< %r)rrBendswithrFrsr,rr>r>r?r5s    zIMAP4._get_linecCsD|||_|jdur:|jdkr:|d|j|jf|jduS)Nrz matched %r => %r)matchr7rFrsrgroups)rVZcresr>r>r?r6s z IMAP4._matchcCs2|jtt|j|j}|jd|_d|j|<|S)Nri)rnr)rrMr]rI)rVr-r>r>r?r(s  zIMAP4._new_tagcCs$|dd}|dd}d|dS)N\z\\"z\")r)rVr.r>r>r?rs  z IMAP4._quotecGs|||j|g|RSr)r2r+rr>r>r?rszIMAP4._simple_commandcCsT|dkr||fS||jvr$|dgfS|j|}|jdkrL|d||f||fS)Nr$rzuntagged_responses[%s] => %s)rJr>rFrs)rVrrrrr>r>r?rs    zIMAP4._untagged_responsecCsN|durt}tdt|}tjd||dd|ftjdS)Nz%M:%Sz %s.%02d %s d)timestrftime localtimerstderrwriteflush)rVrEZsecsZtmr>r>r?rss z IMAP4._mesgcCs>|}|sdSd}tdd|}|d|||fdS)Nz cSs*d|d|ddr"d|dp$dfS)Nz%s: "%s"rriz" "rD)r)xr>r>r?rAz IMAP4._dump_ur..zuntagged responses dump:%s%s)itemsmaprsr)rVdictltr>r>r?rs zIMAP4._dump_urcCs8|tf|j|j<|jd7_|j|jkr4d|_dS)Nrir)rIrrrqrprr>r>r?r,s z IMAP4._logcCsl|dt|j|j|j}}|rhz|j|j|Wn Yn0|d7}||jkr^d}|d8}q"dS)Nzlast %d IMAP4 interactions:rir)rsrrrrqrp)rVinr>r>r?r?s zIMAP4.print_log)rr)rr)rF)N)F)N)Ur;r<r=__doc__rRr@rBrC IMAP4_PORTrZrOrgrQrrrrrPrrrrSrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"r+r2rvrur1r5r6r(rrrrsrr,r?r>r>r>r?rs/*                     M P !  rc@s>eZdZdZdeddddfddZddZdedfdd ZdS) IMAP4_SSLaIMAP4 client class over SSL connection Instantiate with: IMAP4_SSL([host[, port[, keyfile[, certfile[, ssl_context[, timeout=None]]]]]]) 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. timeout - socket timeout (default: None) If timeout is not given or is None, the global default socket timeout is used for more documentation see the docstring of the parent class IMAP4. rDNcCs|dur|durtd|dur0|dur0td|dus@|durVddl}|dtd||_||_|durxtj||d}||_t ||||dS)Nz8ssl_context and keyfile arguments are mutually exclusivez9ssl_context and certfile arguments are mutually exclusiverzEkeyfile and certfile are deprecated, use a custom ssl_context instead)certfilekeyfile) rwarningswarnDeprecationWarningr]r\r r r rrZ)rVrWrXr]r\r rYr^r>r>r?rZs"zIMAP4_SSL.__init__cCst||}|jj||jdS)Nr)rrr r rW)rVrYrr>r>r?r.s zIMAP4_SSL._create_socketcCst||||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)rrPrUr>r>r?rP3szIMAP4_SSL.open)r;r<r=rXIMAP4_SSL_PORTrZrrPr>r>r>r?rZs  rZc@sBeZdZdZddZdddZddZd d Zd d Zd dZ dS)rzIMAP4 client class over a stream Instantiate with: IMAP4_stream(command) "command" - a string that can be passed to subprocess.Popen() for more documentation see the docstring of the parent class IMAP4. cCs||_t|dSr)rrrZ)rVrr>r>r?rZJszIMAP4_stream.__init__NcCsNd|_d|_d|_d|_tj|jttjtjddd|_ |j j |_ |j j |_ dS)zSetup a stream connection. This connection will be used by the routines: read, readline, send, shutdown. NT)bufsizestdinstdoutshell close_fds)rWrXrr subprocessPopenrrPIPErrc writefilerdreadfilerUr>r>r?rPOs zIMAP4_stream.opencCs |j|Sr)rkrrr>r>r?r_szIMAP4_stream.readcCs |jS)r)rkrrer>r>r?rdszIMAP4_stream.readlinecCs|j||jdS)rN)rjrMrNrr>r>r?ris zIMAP4_stream.sendcCs"|j|j|jdS)rN)rkrrjrwaitrer>r>r?rSos  zIMAP4_stream.shutdown)NNN) r;r<r=rXrZrPrrrrSr>r>r>r?r>s  rc@s0eZdZdZddZddZddZdd Zd S) rzcPrivate class to provide en/decoding for base64-based authentication conversation. cCs ||_dSr)r)rVZmechinstr>r>r?rZ}sz_Authenticator.__init__cCs&|||}|durdS||S)N*)rrr)rVrretr>r>r?rsz_Authenticator.processcCsnd}t|tr|d}|rjt|dkrB|dd}|dd}n|}d}t|}|r||dd}q|S)NrArf0r)rrrrbinasciiZ b2a_base64)rVinpZouprUer>r>r?rs      z_Authenticator.encodecCs|sdSt|S)NrA)rpZ a2b_base64)rVrqr>r>r?rsz_Authenticator.decodeN)r;r<r=rXrZrrrr>r>r>r?rws rz0 Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov DecrcCsi|]\}}||dqS)ri)r).0rWrEr>r>r? rArtric Cst|}|sdSt|d}|d}t|d}t|d}t|d}t|d}t|d}t|d } t|d } | d | d } |d kr| } ||||||d d d f } t| | } t| 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<-r) InternalDaterCMon2numr8r;calendarZtimegmrIrK)r=r7rurvrwrxryrzr{r|r}zonettutcr>r>r?rs$  rcCs@d}d}tt|}|rr>r?r s  r cCs$t|}|sdSt|dS)z-Convert IMAP4 flags response to python tuple.r>r)FlagsrCr3r8r4)r=r7r>r>r?r s r cCst|ttfr"t|tj}nt|trz |j }WnXt yt j r|d}|dkrnt t |d}t jt jf| }nt j }Yn0t|d}t|dddt|i}nLt|tr|jdurtd|}n*t|tr|d|dfd kr|Std d t|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. r)ZsecondsNtzinfozdate_time must be awarer)rGrGzdate_time not of a known typez"%d-{}-%Y %H:%M:%S %z")rr;floatrZ fromtimestamprrZ astimezoner3 tm_gmtoffr~rIdaylightrKmktimealtzonerrrrformatMonthsZmonthrJ)rZdtZgmtoffdstZdeltafmtr>r>r?r s2        r __main__zd:s:)r>r>z-dz-s)rDzIMAP password for %s on %s: localhostzJFrom: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)sdata...%(lf)s )rZlfr)r) /tmp/xxx 1)r)rz/tmp/yyy)r /tmp/yyz 2rr)r)z/tmpzyy*)rr)r)NZSUBJECTtest)r)1z(FLAGS INTERNALDATE RFC822))r)rFLAGSz (\Deleted))rr>)rr>)rr>)rr>)rr>)r)Z UIDVALIDITY)r)r,ZALL)r)r)rr>cCsLtd||ftt||\}}td|||f|dkrH|d|S)Nz%s %sz %s => %s %sr$r)Mrsr|)cmdrrrr>r>r?runBs rrzPROTOCOL_VERSION = %szCAPABILITIES = %rr)z/tmp/zyy%z .*"([^"]+)"$rrrrz%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 )UrXrtrprrlr^rrgrrIrrrriorr r  ImportError__all__rrErYrarxrr{r_r:rrrarbrr<r9rdr`rcrrZrrrr4r enumeraterrr r r r;getoptZgetpassargvZoptlistrr@r/Zstream_commandoptr;rWZgetuserZUSERZPASSWDZ test_mesgZ test_seq1Z test_seq2rrrGrsryrwrmlrCr7r8pathrrprintr>r>r>r?sLH    0     6 9, #  )