o w[eR@s$dZdZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z m Z m Z ddlmZzddlZdZWn eyKdZYnwgdZd ZdZd Zd Zd Zd Ziddddddddddddddddddddddddddd dd!dd"dd#did$dd%dd&dd'dd(dd)dd*dd+dd,dd-dd.dd/dd0dd1dd2dd3dd4dddddddddd5Zed6Zed7Zed8Zed9ejZ ed:Z!ed;Z"ed<Z#ed=ejZ$d9Z%d=Z&Gd>d?d?Z'erGd@dAdAe'Z(e)dAGdBdCdCe'Z*GdDdEdEZ+dF,dGZ-dHdIe.e-dJdDZ/dKdLZ0dMdNZ1dOdPZ2dQdRZ3e4dSkrddl5Z5ddl6Z6ze55ej7dJddT\Z8Z9Wne5j:y}Z;z dU\Z8Z9WYdZ;[;ndZ;[;wwdZe;Zqe=dWkre;Z.*))?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~dZAddZBddZCddZDddZEddZFddZGddZHddZIdddZJddZKddZLddZMddZNddZOddZP dddZQddZRddZSddZTd 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@ eZdZdS)z IMAP4.errorN__name__ __module__ __qualname__rArA/usr/lib/python3.10/imaplib.pyerror rCc@r<)z IMAP4.abortNr=rArArArBabortrDrEc@r<)zIMAP4.readonlyNr=rArArArBreadonlyrDrFNc Cst|_d|_d|_i|_i|_d|_d|_d|_d|_ | | |||z| WdSt yDz|WtyCYww)NrrGFr)Debugdebugstateliteraltagged_commandsuntagged_responsescontinuation_response is_readonlytagnum_tls_established _mode_asciiopen_connect ExceptionshutdownOSErrorselfhostporttimeoutrArArB__init__s,   zIMAP4.__init__cCs0d|_d|_tttj|_tttj|_dS)NFascii) utf8_enabled _encodingrecompile_LiteralASCIILiteral_Untagged_statusUntagged_statusrYrArArBrRszIMAP4._mode_asciicCs(d|_d|_tt|_tt|_dS)NTutf-8)r_r`rarbrcrerfrgrhrArArB _mode_utf8s zIMAP4._mode_utf8cCsttdd|_td|jdtj|_ d|_d|_ i|_ |j dkr4| d t | d |j||_d |jvrBd |_nd |jvrKd|_n||j| |j dkrd| d|jftD] }||jvrnqf||_dS|d)Niis(?Ps"\d+) (?P[A-Z]+) (?P.*)T rzimaplib version %sznew IMAP4 connection, tag=%sPREAUTHrOKrzCAPABILITIES: %rzserver not IMAP4 compliant)r randomrandinttagprerarbrdtagre _cmd_log_len _cmd_log_idx_cmd_logrI_mesg __version__ _get_responsewelcomerMrJrC_get_capabilities capabilitiesAllowedVersionsPROTOCOL_VERSION)rYversionrArArBrTs>        zIMAP4._connectcCs"|tvr t||Std|)NzUnknown IMAP4 command: '%s')CommandsgetattrlowerAttributeError)rYattrrArArB __getattr__ s zIMAP4.__getattr__cCs|SNrArhrArArB __enter__szIMAP4.__enter__cGs2|jdkrdSz|WdStyYdSw)Nr)rJlogoutrW)rYargsrArArB__exit__s  zIMAP4.__exit__cCs`|dur |s td|jsdn|j}td||j|j||jf}|dur+t||St|S)Nz0Non-blocking socket (timeout=0) is not supportedz imaplib.open) ValueErrorrZsysauditr[socketcreate_connection)rYr\rZaddressrArArB_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)rZr[rsockmakefilefilerXrArArBrS0s z IMAP4.opencC |j|SzRead 'size' bytes from remote.)rreadrYsizerArArBr< z IMAP4.readcCs.|jtd}t|tkr|dt|S)Read line from remote.rlzgot more than %d bytes)rreadline_MAXLINElenrCrYlinerArArBrAs zIMAP4.readlinecCstd|||j|dS)Send data to remote.z imaplib.sendN)rrrsendallrYdatarArArBsendIsz IMAP4.sendc Cs|jz;z |jtjWn!ty0}z|jtjkr&t |dddkr&WYd}~n d}~wwW|jdSW|jdS|jw) Close I/O established in "open".winerrorri&'N) rcloserrVr SHUT_RDWRrWerrnoENOTCONNr)rYexcrArArBrVOs   zIMAP4.shutdowncCs|jS)zfReturn socket instance used to connect to IMAP4 server. socket = .socket() )rrhrArArBr_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. RECENTrnN)_untagged_responsenooprYnametypdatrArArBrecentks   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)rYcoderArArBresponse|szIMAP4.responsecCsxd}|sd}|r|d|dfdkrd|}nd}|r t|}nd}tt|}|jr1d|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_rK_simple_command)rYmailboxflags date_timemessagerrKrArArBappends    z IMAP4.appendcCsP|}t|j|_|d|\}}|dkr!||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. rrnrrireplacer)r_AuthenticatorprocessrKrrCdecoderJ)rY mechanism authobjectmechrrrArArB authenticates zIMAP4.authenticatecC d}||\}}||||S)zT(typ, [data]) = .capability() Fetch capabilities list from server.rrrrrArArB capabilityszIMAP4.capabilitycCs |dS)zRCheckpoint mailbox on server. (typ, [data]) = .check() rrrhrArArBchecks z IMAP4.checkcC(z|d\}}Wd|_||fSd|_w)zClose currently selected mailbox. Deleted messages are removed from writable mailbox. This is the recommended command before 'LOGOUT'. (typ, [data]) = .close() rrrrJrYrrrArArBrs z IMAP4.closecC|d||S)zCopy 'message_set' messages onto end of 'new_mailbox'. (typ, [data]) = .copy(message_set, new_mailbox) rr)rY message_set new_mailboxrArArBcopyz IMAP4.copycC |d|S)zPCreate new mailbox. (typ, [data]) = .create(mailbox) rrrYrrArArBcreate z IMAP4.createcCr)zPDelete old mailbox. (typ, [data]) = .delete(mailbox) rrrrArArBdeleterz IMAP4.deletecCr)zDelete the ACLs (remove any rights) set for who on mailbox. (typ, [data]) = .deleteacl(mailbox, who) rr)rYrwhorArArB deleteaclrzIMAP4.deleteaclcCsHd|jvr td|d|\}}|dkr d|vr |||fS)zlSend an RFC5161 enable string to the server. (typ, [data]) = .enable(capability) rzServer does not support ENABLErnz UTF8=ACCEPT)r|rrCrrrj)rYrrrrArArBenables  z IMAP4.enablecCr)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. rrrrArArBexpunge s z IMAP4.expungecC$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)rYr message_partsrrrrArArBfetchs z IMAP4.fetchcC|d|\}}|||dS)zXGet the ACLs for a mailbox. (typ, [data]) = .getacl(mailbox) r ACLrrYrrrrArArBgetacl(z IMAP4.getaclcCs"|d|||\}}|||dS)za(typ, [data]) = .getannotation(mailbox, entry, attribute) Retrieve ANNOTATIONs.r! ANNOTATIONr)rYrentry attributerrrArArB getannotation1szIMAP4.getannotationcCr)zGet the quota root's resource usage and limits. Part of the IMAP4 QUOTA extension defined in rfc2087. (typ, [data]) = .getquota(root) r"QUOTAr)rYrootrrrArArBgetquota9szIMAP4.getquotacCs@|d|\}}|||d\}}|||d\}}|||gfS)zGet the list of quota roots for the named mailbox. (typ, [[QUOTAROOT responses...], [QUOTA responses]]) = .getquotaroot(mailbox) r#r QUOTAROOTr)rYrrrquota quotarootrArArB getquotarootDs zIMAP4.getquotaroot""*cCr)zList mailbox names in directory matching pattern. (typ, [data]) = .list(directory='""', pattern='*') 'data' is list of LIST responses. r%rrY directorypatternrrrrArArBlistOz IMAP4.listcCs<|d|||\}}|dkr||dd|_||fS)zIdentify client using plaintext password. (typ, [data]) = .login(user, password) NB: 'password' will be quoted. r&rnrr)r_quoterCrJ)rYuserpasswordrrrArArBlogin[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)rYrrrArArBlogin_cram_md5iszIMAP4.login_cram_md5cCsBddl}t|jtr|jdn|j}|jd|||dS)z1 Authobject to use with CRAM-MD5 authentication. rNri md5)hmac isinstancerstrencoderHMAC hexdigest)rY challenger pwdrArArBrrs zIMAP4._CRAM_MD5_AUTHcCs$d|_|d\}}|||fS)z|Shutdown connection to server. (typ, [data]) = .logout() Returns server 'BYE' response. r)rJrrVrrArArBrzsz IMAP4.logoutcCr)zList 'subscribed' mailbox names in directory matching pattern. (typ, [data, ...]) = .lsub(directory='""', pattern='*') 'data' are tuples of message part envelope and data. r'rrrArArBlsubrz IMAP4.lsubcCs|d|\}}|||dS)zShow my ACLs for a mailbox (i.e. the rights that I have on mailbox). (typ, [data]) = .myrights(mailbox) r$rrrArArBmyrightsrzIMAP4.myrightscCr)zb Returns IMAP namespaces ala rfc2342 (typ, [data, ...]) = .namespace() r)rrrArArB namespaceszIMAP4.namespacecCs" |jdkr ||j|dS)zFSend NOOP command. (typ, [data]) = .noop() Tror*)rI_dump_urrMrrhrArArBrs   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)rY message_num message_partstartlengthrrrrArArBpartialsz 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)rYrrrArArB proxyauths zIMAP4.proxyauthcCr)zkRename old mailbox name to new. (typ, [data]) = .rename(oldmailbox, newmailbox) r-r)rY oldmailbox newmailboxrArArBrenamerz IMAP4.renamecGsXd}|r|jr td|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_rrCrr)rYcharsetcriteriarrrrArArBsearchs z IMAP4.searchrFcCsi|_||_|r d}nd}|||\}}|dkr d|_||fSd|_d|jvr=|s= |jdkr6||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/rnrr READ-ONLYTrlz%s is not writableEXISTSN)rMrOrrJrIrrFget)rYrrFrrrrArArBselects$    z IMAP4.selectcCs|d|||S)zZSet a mailbox acl. (typ, [data]) = .setacl(mailbox, who, what) r0r)rYrrwhatrArArBsetaclsz IMAP4.setaclcGs$|jdg|R\}}|||dS)z_(typ, [data]) = .setannotation(mailbox[, entry, attribute]+) Set ANNOTATIONs.r1rr)rYrrrrArArB setannotation szIMAP4.setannotationcCs |d||\}}|||dS)ziSet the quota root's resource limits. (typ, [data]) = .setquota(root, limits) r2rr)rYrlimitsrrrArArBsetquotaszIMAP4.setquotacGsHd}|d|dfdkrd|}|j|||g|R\}}||||S)zIMAP4rev1 extension SORT command. (typ, [data]) = .sort(sort_criteria, charset, search_criteria, ...) r3rrrrr)rY sort_criteriarsearch_criteriarrrrArArBsorts z IMAP4.sortcCsd}ts |d|jr|d||jvr|d|dur#t}||\}}|dkrG|j|j |j d|_ |j d|_ d|_| n|d ||||S) Nr4zSSL support missingzTLS session already establishedzTLS not supported by serverrnserver_hostnamerTzCouldn't establish TLS session)HAVE_SSLrCrQrEr|ssl_create_stdlib_contextr wrap_socketrrZrrr{r)rY ssl_contextrrrrArArBstarttls)s&      zIMAP4.starttlscCr)zpRequest named status conditions for mailbox. (typ, [data]) = .status(mailbox, names) r5r)rYrnamesrrrrArArBstatus@sz IMAP4.statuscCs>|d|dfdkrd|}|d|||\}}|||dS)zAlters flag dispositions for messages in mailbox. (typ, [data]) = .store(message_set, command, flags) rrrrr6rr)rYrcommandrrrrArArBstoreLsz IMAP4.storecCr)zYSubscribe to new mailbox. (typ, [data]) = .subscribe(mailbox) r7rrrArArB subscribeWrzIMAP4.subscribecGs,d}|j|||g|R\}}||||S)zIMAPrev1 extension THREAD command. (type, [data]) = .thread(threading_algorithm, charset, search_criteria, ...) r8r)rYthreading_algorithmrr,rrrrArArBthread_sz IMAP4.threadc Gs|}|tvr|d||jt|vr&|d||jdt|fd}|j||g|R\}}|dvr;|}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, r9)r.r3r8r)rrrCrJjoinrr)rYr8rrrrrArArBuidis z IMAP4.uidcCr)z_Unsubscribe from old mailbox. (typ, [data]) = .unsubscribe(mailbox) r:rrrArArB unsubscriberzIMAP4.unsubscribecCr)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() r;rr)rYrrrArArBunselects  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'. )rrrJrrYrrrArArBxatoms  z IMAP4.xatomc Csf|durd}|j} |jdkr|d|t||d|f||vr,|||dS|g||<dS)NTz#untagged_responses[%s] %s += ["%r"]rG)rMrIrwrr$r)rYrrurrArArB_append_untaggeds zIMAP4._append_untaggedcCs,|jd}|r||d|jddS)NBYErr)rMr$rErr`)rYbyerArArB _check_byes zIMAP4._check_byec Gs|jt|vrd|_|d||jdt|fdD] }||jvr'|j|=qd|jvr5|js5|d|}t ||j }|d|}|D]}|durNqGt |t rYt ||j }|d|}qG|j}|durd|_t |t |jurv|}nd}|t dt||j } |jd kr|d |n|d |z ||tWnty} z|d | d} ~ ww|dur|S |r|j|r|S|s|r||j} |jd kr|d t|z |||tWnty} z|d | d} ~ ww|s |Sq)Nr=r>rnNOBADr"z#mailbox status changed to READ-ONLY z {%s}Tz> %rzsocket error: %srlzwrite literal size %s)rJrrKrCr?rMrOrF_new_tagbytesr`r r type_commandrrIrw_logrrrWrEryrLrN) rYrrrtagrargrK literatorvalrArArBrTs~              zIMAP4._commandc Cs|dk}|s |z |j||d\}}Wn+|jy+}z |d||fd}~w|jy@}z |d||fd}~ww|sG||dkrU|d|||f||fS)Nr) expect_byezcommand: %s => %srNz%s command error: %s %s)rK_get_tagged_responserErC)rYrrVrrrrYrArArB_command_completes"zIMAP4._command_completecCsJ|\}}|dgkr|dt|d|j}|}t||_dS)Nz"no CAPABILITY response from serverr)rrCr r`rtuplesplitr|rrArArBr{#s   zIMAP4._get_capabilitiescCs|}||j|r8|jd}||jvr|d||jd}t||j}|jd}||gf|j|<nd}|t |sM||j |rM|jd}|jdurh|t |ra|jd|_ dS|d||jd}t||j}|jd}|durd}|r|d|}||j |rt|jd } |jd kr|d |||}||||f|}||j |s||||d vr|t|r|jd}t||j}|||jd |jdkr|dvr|d||f|S)NrVzunexpected tagged response: %rrSrdata2zunexpected response: %rrErOrTrPzread literal size %srLrl)rMrNrIz%s response: %r) _get_line_matchrsmogrouprLrEr r`Untagged_responserg ContinuationrNreintrIrwrrH Response_code)rYresprVrrdat2rrrArArBry,sR                  zIMAP4._get_responsec Cs |j|}|dur|j|=|S|r#d}|j|d}|dur#||fS|z|Wn|jyE}z |jdkr@|d}~wwq)NrlrI)rLrMpoprKryrErI print_log)rYrVrZresultrrJrYrArArBr[|s*   zIMAP4._get_tagged_responsecCsj|}|s |d|ds|d||dd} |jdkr,|d||S|d||S)Nzsocket error: EOFr z#socket error: unterminated line: %rTrPz< %r)rrEendswithrIrwrUrrArArBr`s    zIMAP4._get_linecCsF|||_ |jdur|jdkr|d|j|jf|jduS)NTrFz matched %r => %r)matchrbrIrwrgroups)rYcresrArArBras  z IMAP4._matchcCs2|jtt|j|j}|jd|_d|j|<|S)Nrl)rrrRr rPr`rL)rYrVrArArBrQs  zIMAP4._new_tagcCs$|dd}|dd}d|dS)N\z\\"z\")r)rYrWrArArBrs   z IMAP4._quotecGs|||j|g|RSr)r\rTrCrArArBrszIMAP4._simple_commandcCsV|dkr||fS||jvr|dgfS|j|} |jdkr'|d||f||fS)NrMTrFzuntagged_responses[%s] => %s)rMrjrIrw)rYrrrrrArArBrs    zIMAP4._untagged_responseTcCsN|durt}tdt|}tjd||dd|ftjdS)Nz%M:%Sz %s.%02d %s d)timestrftime localtimerstderrwriteflush)rYrrsecstmrArArBrws z IMAP4._mesgcCs2|sdSdd|D}|dd|dS)Ncss"|] \}}|d|VqdS)z: NrA).0keyvaluerArArB sz!IMAP4._dump_ur..zuntagged responses dump:z )itemsrwr?)rYuntagged_resp_dictrrArArBrs zIMAP4._dump_urcCs<|tf|j|j<|jd7_|j|jkrd|_dSdS)Nrlr)rvrvrurtrrArArBrUs   z IMAP4._logcCsn|dt|j|j|j}}|r5z |j|j|WnY|d7}||jkr-d}|d8}|sdSdS)Nzlast %d IMAP4 interactions:rlr)rwrrvrurt)rYinrArArBrks  zIMAP4.print_log)rr)rFr)F)Ur>r?r@__doc__rUrCrErF IMAP4_PORTr]rRrjrTrrrrrSrrrrVrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr!r%r'r(r*r-r5r7r9r:r<r@rArBrDrHrKrTr\r{ryr[r`rarQrrrrwrrUrkrArArArBrs/*                      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. rGNcCs|dur |dur td|dur|durtd|dus |dur+ddl}|dtd||_||_|durr?r@rIMAP4_SSL_PORTr]rrSrArArArBrs rc@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)r8rr])rYr8rArArBr]IszIMAP4_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)rZr[rr subprocessPopenr8rPIPErr writefilerreadfilerXrArArBrSNs zIMAP4_stream.opencCrr)rrrrArArBr^rzIMAP4_stream.readcCs |jS)r)rrrhrArArBrcs zIMAP4_stream.readlinecCs|j||jdS)rN)rrzr{rrArArBrhs zIMAP4_stream.sendcCs"|j|j|jdS)rN)rrrrwaitrhrArArBrVns  zIMAP4_stream.shutdown)NNN) r>r?r@rr]rSrrrrVrArArArBr=s  rc@s0eZdZdZddZddZddZdd Zd S) rzcPrivate class to provide en/decoding for base64-based authentication conversation. cCs ||_dSr)r)rYmechinstrArArBr]|s z_Authenticator.__init__cCs&|||}|durdS||S)N*)rrr )rYrretrArArBrs z_Authenticator.processcCspd}t|tr |d}|r6t|dkr!|dd}|dd}n|}d}t|}|r4||dd}|s|S)NrEri0r)r r r rbinascii b2a_base64)rYinpoupterArArBr s      z_Authenticator.encodecCs|sdSt|S)NrE)r a2b_base64)rYrrArArBrs z_Authenticator.decodeN)r>r?r@rr]rr rrArArArBrvs  rz0 Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov DecrcCsi|] \}}||dqS)rl)r )r~rrrrArArB srrlc Cst|}|s dSt|d}|d}t|d}t|d}t|d}t|d}t|d}t|d } t|d } | d | d } |d krU| } ||||||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) InternalDateroMon2numrcrfcalendartimegmrvrx)rhrbrrrrrrrrrzonettutcrArArBrs$   rcCsBd}d}tt|}|rt|d\}}|||d|}|s |S)z-Convert integer to A-P string representation.rEsABCDEFGHIJKLMNOPrl)rfabsdivmod)numrYAPmodrArArBr s r cCs$t|}|s dSt|dS)z-Convert IMAP4 flags response to python tuple.rAr)Flagsror]rcr^)rhrbrArArBr s r cCst|ttfrt|tj}npt|tr[z|j }Wn,t yGt j rA|d}|dkr7t t |d}t jt jf| }nt j }Ynwt|d}t|dddt|i}n&t|trl|jduritd|}nt|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)secondsNtzinfozdate_time must be awarer)rtrtzdate_time not of a known typez"%d-{}-%Y %H:%M:%S %z")r rffloatr fromtimestamprr astimezoner] tm_gmtoffrrvdaylightrxmktimealtzonerrrr formatMonthsmonthrw)rdtgmtoffdstdeltafmtrArArBr s:        r __main__zd:s:)rArAz-dz-s)rGzIMAP password for %s on %s: localhostzJFrom: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)sdata...%(lf)s )rlfr)r) /tmp/xxx 1)r)rz/tmp/yyy)r /tmp/yyz 2rr)r)z/tmpzyy*)r%r)r!)NSUBJECTtest)r)1z(FLAGS INTERNALDATE RFC822))r9)rFLAGSz (\Deleted))rrA)rrA)rrA)rrA)r%rA)r) UIDVALIDITY)r@)r.ALL)r)r#)rrAcCsLtd||ftt||\}}td|||f|dkr$|d|S)Nz%s %sz %s => %s %srMr)Mrwr)cmdrrrrArArBrunAs rrzPROTOCOL_VERSION = %szCAPABILITIES = %rr)z/tmp/zyy%z .*"([^"]+)"$rrr@z%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 )Urrxrrrprarrrrvrrrriorr1r0 ImportError__all__rrHrrr}rrrbrerrrdrerrgrdrgrcrfrrrrrr^r enumeraterrr r r r>getoptgetpassargvoptlistrrCrYstream_commandoptrfrZgetuserUSERPASSWD test_mesg test_seq1 test_seq2rrrJrwr~r|rmlrorbrcpathrr@printrArArArBsH         !"#$ 0     69 ,#  )