e fN@sOdZdgZddlZddlZddlZddlZddlmZmZddl m Z ddl m Z ddl m Z ddl mZdd lmZejZd Zejd Zd d ZddddZddZddZGdddZGdddZGdddeZGdddeZdS)z8Basic message object for the email package object model.MessageN)BytesIOStringIO)utils)errors)compat32)charset)decode_bz; z[ \(\)<>@,;:\\"/\[\]\?=]cCsJt|jd\}}}|s4|jdfS|j|jfS)N;)str partitionstrip)paramasepbr2/opt/alt/python34/lib64/python3.4/email/message.py _splitparamsrTc Cs|dk rt|dkrt|trf|d7}tj|d|d|d}d||fSy|jdWn?tk r|d7}tj|dd }d||fSYnX|stj|rd |tj |fSd||fSn|SdS) a~Convenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. If value is a three tuple (charset, language, value), it will be encoded according to RFC2231 rules. If it contains non-ascii characters it will likewise be encoded according to RFC2231 rules, using the utf-8 charset and a null language. Nr*z%s=%sasciizutf-8z%s="%s") len isinstancetuplerZencode_rfc2231encodeUnicodeEncodeError tspecialssearchquote)rvaluer!rrr _formatparam(s  !  r#cCsOdt|}g}x2|dddkrJ|dd}|jd}xR|dkr|jdd||jdd|dr|jd|d}qQW|dkrt|}n|d|}d|kr$|jd}|d|jjd||ddj}n|j|j||d}qW|S)Nr rr"z\"r=)r findcountrindexr lowerappend)sZplistendfirrr _parseparamJs ;  ;r/cCsBt|tr1|d|dtj|dfStj|SdS)Nrrr)rrrunquote)r"rrr _unquotevalue^s"r1c@seZdZdZeddZddZdddd d Zd d Zddd dZ ddZ ddZ ddZ ddZ ddddZdddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zdd1d2Zd3d4Zd5d6Zdd7d8Zd9d:Zd;d<Z d=d>Z!d?d@Z"dAdBZ#dCdDZ$dEdFZ%dGdHZ&ddIdJdKdLZ'ddIdJdMdNZ(dOdJddPddQdRZ)dIdJdSdTZ*dOdJdUdVZ+ddWdXZ,ddYdZZ-d[d\Z.dd]d^Z/dd_d`Z0ddal1m2Z2dS)braBasic message object. A message object is defined as something that has a bunch of RFC 2822 headers and a payload. It may optionally have an envelope header (a.k.a. Unix-From or From_ header). If the message is a container (i.e. a multipart or a message/rfc822), then the payload is a list of Message objects, otherwise it is a string. Message objects implement part of the `mapping' interface, which assumes there is exactly one occurrence of the header per message. Some headers do in fact appear multiple times (e.g. Received) and for those headers, you must use the explicit API to set or get all the headers. Not all of the mapping methods are implemented. cCsS||_g|_d|_d|_d|_d|_|_g|_d|_dS)Nz text/plain) policy_headers _unixfrom_payload_charsetZpreambleZepiloguedefects _default_type)selfr2rrr__init__ys      zMessage.__init__cCs |jS)z9Return the entire formatted message as a string. ) as_string)r9rrr__str__szMessage.__str__FrNcCsoddlm}|dkr%|jn|}t}||ddd|d|}|j|d||jS) aReturn the entire formatted message as a string. Optional 'unixfrom', when true, means include the Unix From_ envelope header. For backward compatibility reasons, if maxheaderlen is not specified it defaults to 0, so you must override it explicitly if you want a different maxheaderlen. 'policy' is passed to the Generator instance used to serialize the mesasge; if it is not specified the policy associated with the message instance is used. If the message object contains binary data that is not encoded according to RFC standards, the non-compliant data will be replaced by unicode "unknown character" code points. r) GeneratorN mangle_from_F maxheaderlenr2unixfrom)email.generatorr=r2rflattengetvalue)r9r@r?r2r=fpgrrrr;s   zMessage.as_stringcCs |jS)z?Return the entire formatted message as a bytes object. )as_bytes)r9rrr __bytes__szMessage.__bytes__cCsiddlm}|dkr%|jn|}t}||ddd|}|j|d||jS)aJReturn the entire formatted message as a bytes object. Optional 'unixfrom', when true, means include the Unix From_ envelope header. 'policy' is passed to the BytesGenerator instance used to serialize the message; if not specified the policy associated with the message instance is used. r)BytesGeneratorNr>Fr2r@)rArHr2rrBrC)r9r@r2rHrDrErrrrFs  zMessage.as_bytescCst|jtS)z6Return True if the message consists of multiple parts.)rr5list)r9rrr is_multipartszMessage.is_multipartcCs ||_dS)N)r4)r9r@rrr set_unixfromszMessage.set_unixfromcCs|jS)N)r4)r9rrr get_unixfromszMessage.get_unixfromc CsW|jdkr|g|_n5y|jj|Wntk rRtdYnXdS)zAdd the given payload to the current payload. The current payload will always be a list of objects after this method is called. If you want to set the payload to a scalar object, use set_payload() instead. Nz=Attach is not valid on a message with a non-multipart payload)r5r*AttributeError TypeError)r9payloadrrrattachs  zMessage.attachc CsT|jr7|rdS|dkr)|jS|j|Sn|dk rrt|jt rrtdt|jn|j}t|jddj}t|trat j |r|j dd}|s^y"|j |j ddd}Wqtk r|j dd}YqXq^qa|ray|j d}Wq^tk rZ|j d }Yq^Xqan|sk|S|d krtj|S|d krtd j|j\}}x!|D]}|jj||qW|S|dkr=t|} t} y$tj | | dd| jSWq=tjk r9|SYq=Xnt|trP|S|S)aZReturn a reference to the payload. The payload will either be a list object or a string. If you mutate the list object, you modify the message's payload in place. Optional i returns that index into the payload. Optional decode is a flag indicating whether the payload should be decoded or not, according to the Content-Transfer-Encoding header (default is False). When True and the message is not a multipart, the payload will be decoded if this header's value is `quoted-printable' or `base64'. If some other encoding is used, or the header is missing, or if the payload has bogus data (i.e. bogus base64 or uuencoded data), the payload is returned as-is. If the message is a multipart and the decode flag is True, then None is returned. NzExpected list, got %szcontent-transfer-encodingrrsurrogateescaperreplacezraw-unicode-escapezquoted-printablebase64 x-uuencodeuuencodeuuex-uuequietT)rUrVrWrX)rJr5rrIrNtyper getr)rZ_has_surrogatesrdecode get_param LookupError UnicodeErrorquopriZ decodestringr join splitlinesr2Z handle_defectruurCError) r9r.r\rOcteZbpayloadr"r7ZdefectZin_fileZout_filerrr get_payloadsV"   "     !     zMessage.get_payloadcCst|dr[|dkr(||_dSt|tsFt|}n|j|j}nt|dr|jdd|_n ||_|dk r|j|ndS)zSet the payload to the given value. Optional charset sets the message's default character set. See set_charset() for details. rNr\rrQ)hasattrr5rCharsetroutput_charsetr\ set_charset)r9rOrrrr set_payload0s    zMessage.set_payloadcCs|dkr&|jdd|_dSt|tsDt|}n||_d|krl|jddnd|kr|jddd|jn|jd|j||jkr|j|j|_nd|kr|j }y||Wqt k r|j}|r\y|j dd }Wq\t k rX|j |j }Yq\Xn|j||_|jd|YqXndS) aSet the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. If charset is None, the charset parameter will be removed from the Content-Type field. Anything else will generate a TypeError. The message will be assumed to be of type text/* encoded with charset.input_charset. It will be converted to charset.output_charset and encoded properly, if needed, when generating the plain text representation of the message. MIME headers (MIME-Version, Content-Type, Content-Transfer-Encoding) will be added as needed. Nrz MIME-Versionz1.0z Content-Typez text/plainzContent-Transfer-EncodingrrQ) del_paramr6rrh add_headerZget_output_charset set_paramZ body_encoder5Zget_body_encodingrNrr_ri)r9rrerOrrrrjDs8           zMessage.set_charsetcCs|jS)zKReturn the Charset instance associated with the message's payload. )r6)r9rrr get_charsetsszMessage.get_charsetcCs t|jS)z9Return the total number of headers, including duplicates.)rr3)r9rrr__len__{szMessage.__len__cCs |j|S)a-Get a header value. Return None if the header is missing instead of raising an exception. Note that if the header appeared multiple times, exactly which occurrence gets returned is undefined. Use get_all() to get all the values matching a header field name. )r[)r9namerrr __getitem__s zMessage.__getitem__cCs|jj|}|r|j}d}x`|jD]R\}}|j|kr4|d7}||krtdj||qq4q4Wn|jj|jj||dS)zSet the value of a header. Note: this does not overwrite an existing header with the same field name. Use __delitem__() first to delete any existing headers. rrz/There may be at most {} {} headers in a messageN)r2Zheader_max_countr)r3 ValueErrorformatr*header_store_parse)r9rqvalZ max_countZlnamefoundkvrrr __setitem__s    zMessage.__setitem__cCsa|j}g}x?|jD]4\}}|j|kr|j||fqqW||_dS)zwDelete all occurrences of a header, if present. Does not raise an exception if the header is missing. N)r)r3r*)r9rq newheadersrxryrrr __delitem__s  zMessage.__delitem__cCs |jdd|jDkS)NcSs"g|]\}}|jqSr)r)).0rxryrrr s z(Message.__contains__..)r)r3)r9rqrrr __contains__szMessage.__contains__ccs#x|jD]\}}|Vq WdS)N)r3)r9Zfieldr"rrr__iter__szMessage.__iter__cCsdd|jDS)a.Return a list of all the message's header field names. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. cSsg|]\}}|qSrr)r}rxryrrrr~s z Message.keys..)r3)r9rrrkeyssz Message.keyscsfddjDS)a)Return a list of all the message's header values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. cs+g|]!\}}jj||qSr)r2header_fetch_parse)r}rxry)r9rrr~s z"Message.values..)r3)r9r)r9rvaluesszMessage.valuescsfddjDS)a'Get all the message's header fields and values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. cs1g|]'\}}|jj||fqSr)r2r)r}rxry)r9rrr~s z!Message.items..)r3)r9r)r9ritemssz Message.itemscCsO|j}x<|jD]1\}}|j|kr|jj||SqW|S)z~Get a header value. Like __getitem__() but return failobj instead of None when the field is missing. )r)r3r2r)r9rqfailobjrxryrrrr[s  z Message.getcCs|jj||fdS)zStore name and value in the model without modification. This is an "internal" API, intended only for use by a parser. N)r3r*)r9rqr"rrrset_rawszMessage.set_rawcCst|jjS)zReturn the (name, value) header pairs without modification. This is an "internal" API, intended only for use by a generator. )iterr3copy)r9rrr raw_itemsszMessage.raw_itemscCskg}|j}xH|jD]=\}}|j|kr|j|jj||qqW|sg|S|S)aQReturn a list of all the values for the named field. These will be sorted in the order they appeared in the original message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no such fields exist, failobj is returned (defaults to None). )r)r3r*r2r)r9rqrrrxryrrrget_alls  #zMessage.get_allcKsg}xd|jD]V\}}|dkrG|j|jddq|jt|jdd|qW|dk r|jd|ntj|||Wtj|}|S)Nr%rr) rr[r/rr rsr*rZ decode_params) r9rheaderrr"paramsprqrvrrr_get_params_preserveqs       zMessage._get_params_preservez content-typeTcCsJt}|j||}||kr+|S|rBdd|DS|SdS)amReturn the message's Content-Type parameters, as a list. The elements of the returned list are 2-tuples of key/value pairs, as split on the `=' sign. The left hand side of the `=' is the key, while the right hand side is the value. If there is no `=' sign in the parameter the value is the empty string. The value is as described in the get_param() method. Optional failobj is the object to return if there is no Content-Type header. Optional header is the header to search instead of Content-Type. If unquote is True, the value is unquoted. cSs(g|]\}}|t|fqSr)r1)r}rxryrrrr~s z&Message.get_params..N)rr)r9rrr0rrrrr get_paramss  zMessage.get_paramscCsf||kr|SxO|j||D];\}}|j|jkr#|rWt|S|Sq#q#W|S)aReturn the parameter value if found in the Content-Type header. Optional failobj is the object to return if there is no Content-Type header, or the Content-Type header has no such parameter. Optional header is the header to search instead of Content-Type. Parameter keys are always compared case insensitively. The return value can either be a string, or a 3-tuple if the parameter was RFC 2231 encoded. When it's a 3-tuple, the elements of the value are of the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and LANGUAGE can be None, in which case you should consider VALUE to be encoded in the us-ascii charset. You can usually ignore LANGUAGE. The parameter value (either the returned string, or the VALUE item in the 3-tuple) is always unquoted, unless unquote is set to False. If your application doesn't care whether the parameter was RFC 2231 encoded, it can turn the return value into a string as follows: rawparam = msg.get_param('foo') param = email.utils.collapse_rfc2231_value(rawparam) )rr)r1)r9rrrr0rxryrrrr]s   zMessage.get_paramz Content-Typerc Cst|t r(|r(|||f}n||krO|jdkrOd}n|j|}|j|d|s|st|||}qJtj|t|||g}nd}x|jd|d|D]u\} } d} | j|jkrt|||} nt| | |} |s1| }qtj|| g}qW||j|kr|rx|j ||q||=|||Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is False. Optional header specifies an alternative to the Content-Type header. Nrrr0)rr)r#rrar[)r9rrrZ new_ctyperryrrrrls % zMessage.del_paramcCs|jddkstn|jdkrD|d=d|dt}|jd|}||kr+|Stj|jS)zReturn the boundary associated with the payload if present. The boundary is extracted from the Content-Type header's `boundary' parameter, and it is unquoted. boundary)rr]rrrstrip)r9rrrrrr get_boundary7s   zMessage.get_boundarycCst}|j|d}||kr9tjdng}d}xY|D]Q\}}|jdkr|jdd|fd}qL|j||fqLW|s|jdd|fng}x|jD]\} } | jdkrmg} xG|D]?\} } | dkr$| j| q| jd| | fqWtj| } |j|j j | | q|j| | fqW||_d S) aSet the boundary parameter in Content-Type to 'boundary'. This is subtly different than deleting the Content-Type header and adding a new one with a new boundary parameter via add_header(). The main difference is that using the set_boundary() method preserves the order of the Content-Type header in the original message. HeaderParseError is raised if the message has no Content-Type header. z content-typezNo Content-Type header foundFrz"%s"Trz%s=%sN) rrrZHeaderParseErrorr)r*r3rrar2ru)r9rrrZ newparamsZfoundpZpkZpvr{hryrrxrvrrr set_boundaryDs2    zMessage.set_boundarycCst}|jd|}||kr+|St|tr|dpGd}y&|djd}t||}Wqttfk r|d}YqXny|jdWntk r|SYnX|jS)zReturn the charset parameter of the Content-Type header. The returned string is always coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned. rrzus-asciirzraw-unicode-escape) rr]rrrr r^r_r))r9rrrZpcharsetrFrrrget_content_charsetrs     zMessage.get_content_charsetcsfdd|jDS)aReturn a list containing the charset(s) used in this message. The returned list of items describes the Content-Type headers' charset parameter for this message and all the subparts in its payload. Each item will either be a string (the value of the charset parameter in the Content-Type header of that part) or the value of the 'failobj' parameter (defaults to None), if the part does not have a main MIME type of "text", or the charset is not defined. The list will contain one string for each part of the message, plus one for the container message (i.e. self), so that a non-multipart message will still return a list of length 1. csg|]}|jqSr)r)r}part)rrrr~s z(Message.get_charsets..)walk)r9rr)rr get_charsetsszMessage.get_charsets)r)3__name__ __module__ __qualname____doc__rr:r<r;rGrFrJrKrLrPrfrkrjrorprrrzr|rrrrrr[rrrrmrrrrrrrrr]rnrlrrrrrrZemail.iteratorsrrrrrrjs`       Z /            !2  .c@s4eZdZddZddZddZdS) _IsAttachmentcCs ||_dS)N)r")r9r"rrrr:sz_IsAttachment.__init__cCs|jS)N)r")r9rrr__call__sz_IsAttachment.__call__cCstjdtdd|jS)Nz6is_attachment will be a method, not a property, in 3.5 stacklevel)warningswarnDeprecationWarningr")r9rrr__bool__s z_IsAttachment.__bool__N)rrrr:rrrrrrrs   rc@s!eZdZdddZeddZddZd.d d Zd/d0d1d2hZddZ ddZ ddddZ ddddZ ddZ dddZdddZddd Zd!dd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-ZdS)3MIMEPartNcCs9|dkr%ddlm}|}ntj||dS)Nr)default)Z email.policyrrr:)r9r2rrrrr:s  zMIMEPart.__init__cCs:|jd}|dkr!dn |jdk}t|S)Nzcontent-dispositionF attachment)r[Zcontent_dispositionr)r9Zc_dresultrrr is_attachments!zMIMEPart.is_attachmentc csu|jrdS|jjd\}}|dkr^||krZ|j||fVndS|dkrndS|dkrx)|jD]}|j||DdHqWdSd|kr|jd|fVnd}|jd}|rx1|jD] }|d|kr|}PqqWn|dkrM|j}|rD|dnd}n|dk rq|j||DdHndS)Nrtext multipartrelatedstartz content-idr)rrrr( iter_parts _find_bodyr]rf) r9rpreferencelistmaintypesubtypeZsubpart candidaterZsubpartsrrrrs6          zMIMEPart._find_bodyrhtmlplaincCsdt|}d}xK|j||D]7\}}||kr%|}|}|dkr\Pq\q%q%W|S)aReturn best candidate mime part for display as 'body' of message. Do a depth first search, starting with self, looking for the first part matching each of the items in preferencelist, and return the part corresponding to the first item that has a match, or None if no items have a match. If 'related' is not included in preferencelist, consider the root part of any multipart/related encountered as a candidate match. Ignore parts with 'Content-Disposition: attachment'. Nr)rr)r9rZ best_prioZbodyZpriorrrrget_bodys    zMIMEPart.get_bodyrr alternativec csd|jjd\}}|dks3|dkr7dS|j}|dkr|dkr|jd}|rd}g}x9|D]1}|jd|krd }q|j|qW|r|DdHdSn|jd |DdHdSg}xo|D]g}|jjd\}}||f|jkrW|j rW||krW|j|qn|VqWdS) aReturn an iterator over the non-main parts of a multipart. Skip the first of each occurrence of text/plain, text/html, multipart/related, or multipart/alternative in the multipart (unless they have a 'Content-Disposition: attachment' header) and include all remaining subparts in the returned iterator. When applied to a multipart/related, return all parts except the root part. Return an empty iterator when applied to a multipart/alternative or a non-multipart. rrrNrrFz content-idTr) rrrfr]r[r*pop _body_typesr) r9rrrrrwZ attachmentsrseenrrriter_attachmentss6         zMIMEPart.iter_attachmentsccs(|jdkr$|jDdHndS)z~Return an iterator over all immediate subparts of a multipart. Return an empty iterator for a non-multipart. rN)rrf)r9rrrr#szMIMEPart.iter_partscontent_managercOs.|dkr|jj}n|j|||S)N)r2r get_content)r9rargskwrrrr+s zMIMEPart.get_contentcOs2|dkr|jj}n|j|||dS)N)r2r set_content)r9rrrrrrr0s zMIMEPart.set_contentc Cs>|jdkrU|j}||f}||krUtdj||qUng}g}xU|jD]J\}}|jjdr|j||fqk|j||fqkW|rt|d|j } || _|j | _ | g|_ n g|_ ||_d||d<|dk r:|j d|ndS)NrzCannot convert {} to {}zcontent-r2z multipart/z Content-Typer) rrrsrtr3r) startswithr*rZr2r5rn) r9rZdisallowed_subtypesrZexisting_subtypeZ keep_headersZ part_headersrqr"rrrr_make_multipart5s,         zMIMEPart._make_multipartcCs|jdd|dS)Nrrmixed)z alternativer)r)r9rrrr make_relatedPszMIMEPart.make_relatedcCs|jdd|dS)Nrr)zmixed)r)r9rrrrmake_alternativeSszMIMEPart.make_alternativecCs|jdf|dS)Nr)r)r9rrrr make_mixedVszMIMEPart.make_mixed_dispcOs|jdks$|j|kr;t|d|nt|d|j}|j|||rd|kr||d.)r3r5)r9rrr clear_contentpszMIMEPart.clear_content)relatedrr)textr)rr) multipartr)rz alternative)rrrr:propertyrrrrrrrrrrrrrrrrrrrrrrrs,    .      rcs"eZdZfddZS) EmailMessagecs0tj||d|kr,d|ds2       "  ?