o
    bt                    @   s\  d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	m
Z
 ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZmZmZmZ dd
lmZ ddlmZmZ ddlm Z m!Z!m"Z# ddl$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z6m7Z7 ddl8m9Z9m:Z:m;Z;m<Z= ddl>m?Z?m@Z@ ddlAmBZBmCZC ddlDmEZEmFZFmGZG ddlHmIZI g dZJeIK reL MdZNneO MdZNePQeRddZSdNddZTdd ZUeU ZVddd fddZWd d! ZXd"\ZYZZZ[d#Z\G d$d% d%Z]G d&d' d'Z^G d(d) d)e?j_e@j`ZaG d*d+ d+ejbZcG d,d- d-e?jde@j`ZeG d.d/ d/eeZfG d0d1 d1eaZgG d2d3 d3ZhG d4d5 d5eheeZiG d6d7 d7ejjZkG d8d9 d9e#Z"ee9G d:d; d;ZlG d<d= d=ehefZmG d>d? d?ekZndd@edddAdAfdBdCZoddlpZpdOdDdEZqdOdFdGZrG dHdI dIepjsZtG dJdK dKepjuZvdLdM Zwepxew dS )Pz/
Simple Mail Transfer Protocol implementation.
    N)	parseaddr)BytesIO)Type)implementer)cred)longversion)defererrorprotocolreactor)	_idnaText)ISSLTransportITLSTransport)CramMD5ClientAuthenticatorLOGINAuthenticatorLOGINCredentials)AddressErrorAUTHDeclinedErrorAuthenticationErrorAUTHRequiredErrorEHLORequiredErrorESMTPClientErrorSMTPAddressErrorSMTPBadRcptSMTPBadSenderSMTPClientErrorSMTPConnectErrorSMTPDeliveryError	SMTPErrorSMTPProtocolErrorSMTPServerErrorSMTPTimeoutErrorSMTPTLSErrorTLSRequiredError)IClientAuthenticationIMessageDeliveryIMessageDeliveryFactoryIMessageSMTP)basicpolicies)logutil)	iterbytesnativeStringnetworkString)platform)0r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   TLSErrorr#   r   r$   IMessager%   r&   r   r   r   PLAINAuthenticatorAddressUsersendmailSenderMixinESMTPESMTPClientESMTPSenderESMTPSenderFactorySMTP
SMTPClientSMTPFactory
SMTPSenderSMTPSenderFactoryidGenerator	messageid	quoteaddr
rfc822datextextStreamReaderxtextStreamWriterxtext_codecxtext_decodextext_encodeascii   i,     c                 C   s   | s|r	t  } nt  } |r9| d rt j }nt j }tt|d\}}|r1|tt|| 9 }t|d\}}nd\}}tdg d| d  | d g d	| d
 d
  | d | d | d | d ||f	 S )a  
    Format an RFC-2822 compliant date string.

    @param timeinfo: (optional) A sequence as returned by C{time.localtime()}
        or C{time.gmtime()}. Default is now.
    @param local: (optional) Indicates if the supplied time is local or
        universal time, or if no time is given, whether now should be local or
        universal time. Default is local, as suggested (SHOULD) by rfc-2822.

    @returns: A L{bytes} representing the time and date in RFC-2822 format.
       i  <   )r   r   z)%s, %02d %s %04d %02d:%02d:%02d %+03d%02d)MonTueWedThuFriSatSun      )JanFebMarAprMayJunJulAugSepOctNovDecrK   r            )	time	localtimegmtimealtzonetimezonedivmodabsintr.   )timeinfolocaltztzhrtzmintzsec rt   3/usr/lib/python3/dist-packages/twisted/mail/smtp.pyrC      s:   


rC   c                  c   s    d} 	 | V  | d7 } q)Nr   TrK   rt   )irt   rt   ru   r@      s   r@   c                   C   s   t tS N)next_genrt   rt   rt   ru   <lambda>   s    rz   c              	   C   sV   t dt  }t }td}| du rd} nd|  } d|||| | t	 
 S )z
    Return a globally unique random string in RFC 2822 Message-ID format

    <datetime.pid.random@host.dom.ain>

    Optional uniq string will be added to strengthen uniqueness if given.
    z%Y%m%d%H%M%SiN .z<{}.{}.{}{}.{}@{}>)rf   strftimerh   osgetpidrandom	randrangeformatDNSNAMEdecodeencode)uniqNdatetimepidrandrt   rt   ru   rA      s   
rA   c                 C   sd   t | trdt|  d S t | tr| d} t| }|dkr'dt|  d S d|d d d S )zq
    Turn an email address, possibly with realname part etc, into
    a form suitable for and SMTP envelope.
       <   >rI   NNrK   )
isinstancer3   bytesr   r   r   )addrresrt   rt   ru   rB      s   


rB   )COMMANDDATAAUTHs   [-A-Za-z0-9!\#$%&'*+/=?^_`{|}~]c                   @   sv   e Zd ZdZede d ejZeeZ	dddZ
edZdd	 Zd
efddZd
efddZd
efddZdS )r3   aF  Parse and hold an RFC 2821 address.

    Source routes are stipped and ignored, UUCP-style bang-paths
    and %-style routing are not parsed.

    @type domain: C{bytes}
    @ivar domain: The domain within which this address resides.

    @type local: C{bytes}
    @ivar local: The local ("user") portion of this address.
    s   ( # A string of
                           (?:"[^"]*" # quoted string
                           |\\. # backslash-escaped characted
                           |sL    # atom character
                           )+|.) # or any single characterNc                 C   s  t |tr|j}t |tr|j | _d S t |ts!t|d}|| _	t
td | j|}g }g }|r|d dkrL|d dkrEtd|dd }nv|d dkr|dd  }|s}|rp|d d	krp|dd  }|rp|d d	ksb|svtd
|dd  }nE|rtddg}n;t|d dkr| j|d s|d dkrtd|d d||f|s||d  n||d  |dd  }|s5d|| _d|| _| jdkr| jdkr|d u rt}|| _d S d S d S )NrI   r   r   r   zUnbalanced <>rK      @   :zMalformed source routez
Too many @       .zParse error at z of )r   r4   destr3   __dict__copyr   strr   addrstrlistfiltertstringsplitr   lenatomrematchappendjoinro   domainr   )selfr   defaultDomainatlro   r   rt   rt   ru   __init__  sT   


,
zAddress.__init__s   \\(.)c                 C   s   g }t |tst|d}td| j|}|D ],}|d dkr1|d dkr1||dd  qd|v r@|| j	d| q|| qd	
|S )
z6
        Remove RFC-2821 quotes from address.
        rI   Nr      "r   rK   \s   \1r   )r   r   r   r   r   r   r   r   	dequotebssubr   )r   r   r   r   trt   rt   ru   dequoteJ  s   

zAddress.dequotereturnc                 C      |   dS NrI   	__bytes__r   r   rt   rt   ru   __str___     zAddress.__str__c                 C   s"   | j s| jrd| j | jfS dS )Nr   r   )ro   r   r   r   rt   rt   ru   r   b  s   zAddress.__bytes__c                 C   s   d | j| jjtt| S )Nz	{}.{}({}))r   
__module__	__class____name__reprr   r   rt   rt   ru   __repr__h  s   zAddress.__repr__rw   )r   r   __qualname____doc__recompileatomXr   r   r   r   r   r   r   r   r   r   rt   rt   rt   ru   r3      s"    



4r3   c                   @   s<   e Zd ZdZdd Zdd ZdefddZdefd	d
Z	dS )r4   zu
    Hold information about and SMTP message recipient,
    including information on where the message came from
    c                 C   s^   z|j }W n ty   d }Y nw t||| _|| _|| _t|tr'|| _d S t||| _d S rw   )hostAttributeErrorr3   r   helor
   r   orig)r   destinationr   r
   r   r   rt   rt   ru   r   t  s   


zUser.__init__c                 C   s   | j | jd| jdS )z
        Helper for pickle.

        protocol isn't picklabe, but we want User to be, so skip it in
        the pickle.
        N)r   r   r
   r   )r   r   r   r   rt   rt   ru   __getstate__  s
   zUser.__getstate__r   c                 C   r   r   r   r   rt   rt   ru   r     r   zUser.__str__c                 C   s
   t | jS rw   )r   r   r   rt   rt   ru   r        
zUser.__bytes__N)
r   r   r   r   r   r   r   r   r   r   rt   rt   rt   ru   r4   n  s    r4   c                   @   s  e Zd ZdZdZdZdZdZdZdZ	dLddZ
edd Zejd	d Zd
d Zdd Zdd ZdMddZdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#e d$ Zed%e d& e d' ejejB Z ed(e d& e d' ejejB Z!d)d* Z"dNd-d.Z#d/d0 Z$d1d2 Z%dOd4d5Z&d6d7 Z'd8d9 Z(d:d; Z)d<d= Z*d>d? Z+d@dA Z,e,Z-dBdC Z.dDdE Z/dFdG Z0dHdI Z1dJdK Z2dS )Pr;   zp
    SMTP server-side protocol.

    @ivar host: The hostname of this mail server.
    @type host: L{bytes}
    X  NTc                 C   s.   t | _d | _d | _g | _|| _|| _t| _d S rw   )	r   mode_from_helo_todeliverydeliveryFactoryr   r   )r   r   r   rt   rt   ru   r     s   
zSMTP.__init__c                 C   s   | j S rw   )_hostr   rt   rt   ru   r     s   z	SMTP.hostc                 C   s"   t |tst|d}|| _d S r   )r   r   r   r   r   )r   toSetrt   rt   ru   r     s   

c                 C   s$   | j d }| d| | j  d S )Ns'    Timeout. Try talking faster next time!i  )r   sendCode	transportloseConnection)r   msgrt   rt   ru   timeoutConnection  s   
zSMTP.timeoutConnectionc                 C   s
   | j d S )Ns    NO UCE NO UBE NO RELAY PROBES)r   r   rt   rt   ru   greeting  r   zSMTP.greetingc                 C   sZ   | j  }z|j}W n ty   t|}Y nw d |f| _| d|   | | j	 d S N   )
r   getPeerr   r   r   r   r   r   
setTimeouttimeout)r   peerr   rt   rt   ru   connectionMade  s   


zSMTP.connectionMader   c                 C   sf   |  }|dd }|dd D ]}| td|f |  q| td|f |r-|d p.d  dS )z3
        Send an SMTP code with a message.
        r   Nz%3.3d-z%3.3d r   r   )
splitlinessendLiner.   )r   codemessagelineslastlinelinert   rt   ru   r     s   zSMTP.sendCodec                 C   s   |    t| d| j |S )Nstate_)resetTimeoutgetattrr   r   r   rt   rt   ru   lineReceived  s   zSMTP.lineReceivedc                 C   s`   |  }|d d}|r*| |d p| j}t|dkr$||d  d S |d d S |   d S )NrK   r   rV   r   )stripr   lookupMethod
do_UNKNOWNr   sendSyntaxError)r   r   partsmethodrt   rt   ru   state_COMMAND  s   zSMTP.state_COMMANDc                 C      |  dd d S )N  s   Error: bad syntaxr   r   rt   rt   ru   r        zSMTP.sendSyntaxErrorc                 C   s&   t |ts	t|}t| d|  dS )z

        @param command: The command to get from this class.
        @type command: L{str}
        @return: The function which executes this command.
        do_N)r   r   r-   r   upper)r   commandrt   rt   ru   r     s   
zSMTP.lookupMethodc                 C   s8   | j tu r| jD ]}|  qt| _ | `| dd d S )Nr   s   Line too long)r   r   _SMTP__messagesconnectionLostr   r   )r   r   r   rt   rt   ru   lineLengthExceeded
  s   


zSMTP.lineLengthExceededc                 C   r   )Nr   s   Command not implementedr   r   restrt   rt   ru   r     r   zSMTP.do_UNKNOWNc                 C   sx   | j  }z|j}W n ty   t|}Y nw t|ts"|d}||f| _d | _	g | _
| d| jd | d  d S )Nidna       Hello s   , nice to meet you)r   r   r   r   r   r   r   r   r   r   r   r   )r   r  r   r   rt   rt   ru   do_HELO  s   




zSMTP.do_HELOc                 C   s   |  dd | j  d S )N   s   See you later)r   r   r   r   rt   rt   ru   do_QUIT$  s   zSMTP.do_QUITs   ("[^"]*"|\\.|s	   |[@.,:])+s>   \s*FROM:\s*(?P<path><> # Empty <>
                          |<s&   > # <addr>
                          |sq    # addr
                          )\s*(\s(?P<opts>.*))? # Optional WS + ESMTP options
                          $s   \s*TO:\s*(?P<path><c              
   C   s   | j r| dd d S g | _| j|}|s| dd d S zt|d| j}W n tyF } z| dt	t
| W Y d }~d S d }~ww t| j| j|}|| j| j d S )N  s#   Only one sender per message, please     Syntax errorpath)  )r   r   r   mail_rer   r3   groupr   r   r.   r   r   maybeDeferredvalidateFromr   addCallbacks_cbFromValidate_ebFromValidate)r   r  mr   e	validatedrt   rt   ru   do_MAILD  s"   zSMTP.do_MAILr     Sender address acceptedc                 C   s   || _ | || d S rw   )r   r   )r   	fromEmailr   r   rt   rt   ru   r  X  s   zSMTP._cbFromValidatec                 C   s|   | tr| |jjdt|jj d t|jj  d S | t	r0| |jjt|jj d S t
|d | dd d S )Ns&   Cannot receive from specified address    : zSMTP sender validation failure  3   Requested action aborted: local error in processing)checkr   r   valuer   rB   r   r.   respr    r*   errr   failurert   rt   ru   r  \  s   



	zSMTP._ebFromValidatec              
   C   s   | j s| dd d S | j|}|s| dd d S zt|d| j| | j }W n tyF } z| dtt	| W Y d }~d S d }~ww t
| j|}|j| j| j|fd d S )Nr  s!   Must have sender before recipientr	  r
  r  r  )callbackArgs)r   r   rcpt_rer   r4   r  r   r   r.   r   r   r  
validateTor  _cbToValidate_ebToValidate)r   r  r  userr  drt   rt   ru   do_RCPTm  s    zSMTP.do_RCPT   Recipient address acceptedc                 C   s,   |d u r|}| j ||f | || d S rw   )r   r   r   )r   tor(  r   r   rt   rt   ru   r&    s   zSMTP._cbToValidatec                 C   sB   | ttr| |jjt|jj d S t	| | dd d S )Nr  r  )
r  r   r    r   r  r   r.   r  r*   r   r!  rt   rt   ru   r'    s   
zSMTP._ebToValidatec              	   C   s>   |D ]}z|   W q ty   td t  Y qw d S )Nz(msg raised exception from connectionLost)r   BaseExceptionr*   r   r   )r   msgsr   rt   rt   ru   _disconnect  s   
zSMTP._disconnectc                 C   s\  | j d u s| js| dd d S t| _| j| j }}| j}d | _ g | _d | _g }|D ]]\}}z| }| |||g}	|	rA||	 |	| W q* t
yk }
 z| |
j|
j t| _| | W Y d }
~
 d S d }
~
w ty   t  | dd t| _| | Y  d S w || _d | _| _| dd | jrd}t||d	d
 |D f  d S d S )Nr  s'   Must have valid receiver and originator&  s   Internal server errorr   b  s   Continuez-Receiving message for delivery: from=%s to=%sc                 S   s   g | ]\}}t |qS rt   )r   ).0ufrt   rt   ru   
<listcomp>  s    z SMTP.do_DATA.<locals>.<listcomp>)r   r   r   r   r   r   
datafailedreceivedHeaderr   r   r    r   r  r   r/  r-  r*   r   r   _SMTP__inheader_SMTP__inbodynoisyr   )r   r  r   origin
recipientsr.  r(  msgFuncr   rcvdhdrr  fmtrt   rt   ru   do_DATA  sJ   


 zSMTP.do_DATAc              	   C   sz   | j tu r,z| jD ]}z|  W q	 ty   t  Y q	w | `W n	 ty+   Y nw | jr6|   d | _| 	d  d S rw   )
r   r   r   r   r-  r*   r   r   	_onLogoutr   )r   reasonr   rt   rt   ru   r     s    

zSMTP.connectionLostc                 C   s   d | _ g | _| dd d S )Nr  s   I remember nothing.)r   r   r   r   rt   rt   ru   do_RSET  s   zSMTP.do_RSETc              
   C   s4  |d d dkrC|dkr=t | _| jr| | jj| jj d S | js(| d d S tj	dd | jD dd
| j | `d S |dd  }| jrHd S z1| jsg| jsgd|v rWd| _n|rg| jD ]}|d	 q\d| _|sld| _| jD ]}|| qoW d S  ty } z|| _| jD ]}|  qW Y d }~d S d }~ww )
NrK   r   zthrown awayc                 S   s   g | ]}|  qS rt   )eomReceived)r2  r  rt   rt   ru   r5    s    z)SMTP.dataLineReceived.<locals>.<listcomp>T)consumeErrorsr   r   )r   r   r6  r   r   r  r   _messageHandledr   DeferredListaddCallbackr8  r9  r   r    r   )r   r   r   r  rt   rt   ru   dataLineReceived  sL   





zSMTP.dataLineReceivedc                 C   sz   d}|D ]\}}|s|d7 }t | q|r5d}t|}|dkr+|d| d| d7 }| dt| d S | dd	 d S )
Nr   rK   zCould not send e-mailz (z failures out of z recipients)r0  r  s   Delivery in progress)r*   r   r   r   r.   )r   
resultListfailuressuccessresultr   	resultLenrt   rt   ru   rF    s   
zSMTP._messageHandledc                 C   sZ   |\}}}t |tr|| _d| _nt |trd| _|| _nt|j d|| _d| _dS )zR
        Save the state resulting from a successful anonymous cred login.
        Nz is not a supported interface)	
issubclassr&   r   r   r%   RuntimeErrorr   rA  
challenger)r   rM  ifaceavatarlogoutrt   rt   ru   _cbAnonymousAuthentication  s   



zSMTP._cbAnonymousAuthenticationc                    s   j durj  _jdurtjj S jrDjtj	
 dtt}fdd}|j|  fdd}|| |S t)a  
        Validate the address from which the message originates.

        @type helo: C{(bytes, bytes)}
        @param helo: The argument to the HELO command and the client's IP
        address.

        @type origin: C{Address}
        @param origin: The address the message is from

        @rtype: C{Deferred} or C{Address}
        @return: C{origin} or a C{Deferred} whose callback will be
        passed C{origin}.

        @raise SMTPBadSender: Raised of messages from this address are
        not to be accepted.
        Nc                    sB   |  tjjrt }n|  tjjrt dd}n| S t|S )z
                Translate cred exceptions into SMTP exceptions so that the
                protocol code which invokes C{validateFrom} can properly report
                the failure.
                z#Unauthenticated senders not allowed)r  )r  r   r	   UnauthorizedLoginr   UnhandledCredentialsr   fail)r   exc)r;  rt   ru   ebAuthenticationE  s   

z+SMTP.validateFrom.<locals>.ebAuthenticationc                    s     S )zE
                Re-attempt from address validation.
                )r  )ignoredr   r;  r   rt   ru   continueValidationW  s   z-SMTP.validateFrom.<locals>.continueValidation)r   getMessageDeliveryr   r   r  r  portalloginr   credentials	Anonymousr&   r%   r  rU  rH  r   )r   r   r;  rM  rZ  r]  rt   r\  ru   r  !  s"   


zSMTP.validateFromc                 C   s   | j dur| j |S t|)a  
        Validate the address for which the message is destined.

        @type user: L{User}
        @param user: The address to validate.

        @rtype: no-argument callable
        @return: A C{Deferred} which becomes, or a callable which
        takes no arguments and returns an object implementing C{IMessage}.
        This will be called and the returned object used to deliver the
        message when it arrives.

        @raise SMTPBadRcpt: Raised if messages to the address are
        not to be accepted.
        N)r   r%  r   r   r(  rt   rt   ru   r%  b  s   
zSMTP.validateToc           	      C   s   | j d ur| j |||S d}|d rd|d  }t| j j}d|d  d |d  d | d }d	|| jjtf }d
d	t
t|t f }d| d | d | S )Nr   r   s    helo=s   from s    ([rK      ]   )s   by %s with %s (%s)s
   for %s; %s s
   Received: s   
	)r   r7  r.   r   getHostr   r   r   r   r   mapr   rC   )	r   r   r;  r<  heloStrr   from_byfor_rt   rt   ru   r7  v  s   
$zSMTP.receivedHeaderr   )r   )r  r  )Nr  r+  )3r   r   r   r   r   r_  r:  r   r   rA  r   propertyr   setterr   r   r   r   r   r   r   r   r   r   r  r  r   qstringr   r   Ir   r  r$  r  r  r  r*  r&  r'  r/  r@  r   rC  rI  
state_DATArF  rU  r  r%  r7  rt   rt   rt   ru   r;     s    
	



	


(*Ar;   c                   @   s2   e Zd ZdZeZdZeZdZ	dddZ
dd ZdS )	r=   z
    Factory for SMTP.
    r   Nc                 C   
   || _ d S rw   )r_  )r   r_  rt   rt   ru   r     r   zSMTPFactory.__init__c                 C   s"   t j| |}| j|_| j|_|S rw   )r
   ServerFactorybuildProtocolr_  r   r   r   r   prt   rt   ru   rt    s   zSMTPFactory.buildProtocolrw   )r   r   r   r   r   r   r   r;   r
   r_  r   rt  rt   rt   rt   ru   r=     s    
r=   c                   @   s   e Zd ZdZdZdZd3ddZdd Zd	d
 Ze	j
fddZdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 ZdS )4r<   a  
    SMTP client for sending emails.

    After the client has connected to the SMTP server, it repeatedly calls
    L{SMTPClient.getMailFrom}, L{SMTPClient.getMailTo} and
    L{SMTPClient.getMailData} and uses this information to send an email.
    It then calls L{SMTPClient.getMailFrom} again; if it returns L{None}, the
    client will disconnect, otherwise it will continue as normal i.e. call
    L{SMTPClient.getMailTo} and L{SMTPClient.getMailData} and send a new email.
    TN
   c                 C   sL   t |tr
|d}|pd| _g | _g | _d | _g | _d| _t	
|| _d S )NrI   r   r   )r   r   r   identitytoAddressesResultsuccessAddressesr   r  r   r+   LineLogr*   )r   rx  logsizert   rt   ru   r     s   


zSMTPClient.__init__c                 C   s(   | j r| jd|  tj| | d S )Ns   >>> )debugr*   r   r(   LineReceiverr   r   rt   rt   ru   r     s   zSMTPClient.sendLinec                 C   s(   |  | j dg| _| j| _| j| _d S r   )r   r   	_expectedsmtpState_helo_okresponsesmtpConnectionFailed_failresponser   rt   rt   ru   r     s   zSMTPClient.connectionMadec                 C   s   |  d d| _dS )z,
        We are no longer connected
        N)r   mailFiler   rB  rt   rt   ru   r     s   

zSMTPClient.connectionLostc                 C   s   |  tdd| j  d S )Nr   s(   Timeout waiting for SMTP server response)	sendErrorr!   r*   r   r   rt   rt   ru   r     s
   zSMTPClient.timeoutConnectionc              
   C   s   |    | jr| jd|  d }zt|d d | _W n ty5   | tdd| | j	  Y d S w |dd dkr@d S | j
|dd   |dd d	krTd S | j| jv rf| | jd
| j
}n| | jd
| j
}d| _g | _
|S )Ns   <<< rc   r   z#Invalid response from SMTP server: r   rK      0rd      -   
)r   r}  r*   r   rm   r   
ValueErrorr  r   r   r  r  r  r   r  )r   r   whyrt   rt   ru   r     s6   zSMTPClient.lineReceivedc                 C   s   |  t||| j  d S rw   )r  r   r*   r   r   r   r  rt   rt   ru   r     s   zSMTPClient.smtpConnectionFailedc                 C   s4   |dk r|  t||| j  d S | || d S )Nr   )r  r   r*   r   smtpState_msgSentr  rt   rt   ru   smtpTransferFailed  s   zSMTPClient.smtpTransferFailedc                 C   s"   |  d| j  t| _| j| _d S )Ns   HELO )r   rx  SUCCESSr  smtpState_fromr  r  rt   rt   ru   r  	  s   zSMTPClient.smtpState_heloc                 C   sP   |   | _| j| _| jd ur"| dt| j  dg| _| j| _d S | 	  d S )Ns
   MAIL FROM:r  )
getMailFromr   r  r  r   rB   r  smtpState_tor  _disconnectFromServerr  rt   rt   ru   r    s   

zSMTPClient.smtpState_fromc                 C   s   | j   d S rw   )r   r   r  rt   rt   ru   smtpState_disconnect  r   zSMTPClient.smtpState_disconnectc                 C   s@   t |  | _g | _g | _| j| _tdd| _d | _	| ddS )Nr     r   )
iter	getMailTotoAddressesry  rz  smtpState_toOrDatar  ranger  lastAddressr  rt   rt   ru   r    s   zSMTPClient.smtpState_toc                 C   s   | j d ur| j| j ||f |tv r| j| j  zt| j| _ W n" tyD   | jr<| d dg| _	| j
| _Y d S | |d Y S w | dt| j   d S )Ns   DATAr1  zNo recipients accepteds   RCPT TO:)r  ry  r   r  rz  rx   r  StopIterationr   r  smtpState_datar  r  rB   r  rt   rt   ru   r  %  s   

zSMTPClient.smtpState_toOrDatac                    sJ   t  }|   j j} fdd}| j| t _	 j
 _d S )Nc                    s     | j d S rw   )r  r  )r   r   rt   ru   
ebTransfer:  r   z-SMTPClient.smtpState_data.<locals>.ebTransfer)r(   
FileSenderbeginFileTransfergetMailDatar   transformChunkr  finishedFileTransferr  r  r  r  )r   r   r  sr)  r  rt   r   ru   r  6  s   zSMTPClient.smtpState_datac                 C   sN   | j d ur| ||t| j| j| j g | _d | _ | d t| _| j	| _
d S )Ns   RSET)r   sentMailr   rz  ry  r*   r   r  r  r  r  r  rt   rt   ru   r  A  s   

zSMTPClient.smtpState_msgSentc                 C   s   |    |ddddS )a
  
        Perform the necessary local to network newline conversion and escape
        leading periods.

        This method also resets the idle timeout so that as long as process is
        being made sending the message body, the client will not time out.
        r  s   
   
.s   
..)r   replace)r   chunkrt   rt   ru   r  P  s   zSMTPClient.transformChunkc                 C   s    |dkrd}nd}|  | d S )Nr  r  r   )r   )r   lastsentr   rt   rt   ru   r  [  s   zSMTPClient.finishedFileTransferc                 C      t )z<
        Return the email address the mail is from.
        NotImplementedErrorr   rt   rt   ru   r  d     zSMTPClient.getMailFromc                 C   r  )z5
        Return a list of emails to send to.
        r  r   rt   rt   ru   r  j  r  zSMTPClient.getMailToc                 C   r  )z
        Return file-like object containing data of message to be sent.

        Lines in the file should be delimited by '\n'.
        r  r   rt   rt   ru   r  p  s   zSMTPClient.getMailDatac                 C   s,   t |tr|js|   dS | dd dS )a2  
        If an error occurs before a mail message is sent sendError will be
        called.  This base class method sends a QUIT if the error is
        non-fatal and disconnects the connection.

        @param exc: The SMTPClientError (or child class) raised
        @type exc: C{SMTPClientError}
        r   N)r   r   isFatalr  r  r   rY  rt   rt   ru   r  x  s   	zSMTPClient.sendErrorc                 C   r  )a  
        Called when an attempt to send an email is completed.

        If some addresses were accepted, code and resp are the response
        to the DATA command. If no addresses were accepted, code is -1
        and resp is an informative message.

        @param code: the code returned by the SMTP Server
        @param resp: The string response returned from the SMTP Server
        @param numOk: the number of addresses accepted by the remote host.
        @param addresses: is a list of tuples (address, code, resp) listing
                          the response to each RCPT command.
        @param log: is the SMTP session log
        r  )r   r   r  numOk	addressesr*   rt   rt   ru   r    s   zSMTPClient.sentMailc                 C   s"   t dd| _| j| _| d d S )Nr   r  s   QUIT)r  r  r  r  r   r   rt   rt   ru   r    s   z SMTPClient._disconnectFromServer)rw  )r   r   r   r   r}  r   r   r   r   r
   connectionDoner   r   r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rt   rt   rt   ru   r<     s6    
*		r<   c                   @   s   e Zd ZdZdZdZdZdZdZd0ddZ	dd Z
d	d
 Zd1ddZd1ddZd1ddZd1ddZd1ddZd1ddZd1ddZdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ ZdS )2r8   a  
    A client for sending emails over ESMTP.

    @ivar heloFallback: Whether or not to fall back to plain SMTP if the C{EHLO}
        command is not recognised by the server. If L{requireAuthentication} is
        C{True}, or L{requireTransportSecurity} is C{True} and the connection is
        not over TLS, this fallback flag will not be honored.
    @type heloFallback: L{bool}

    @ivar requireAuthentication: If C{True}, refuse to proceed if authentication
        cannot be performed. Overrides L{heloFallback}.
    @type requireAuthentication: L{bool}

    @ivar requireTransportSecurity: If C{True}, refuse to proceed if the
        transport cannot be secured. If the transport layer is not already
        secured via TLS, this will override L{heloFallback}.
    @type requireAuthentication: L{bool}

    @ivar context: The context factory to use for STARTTLS, if desired.
    @type context: L{IOpenSSLClientConnectionCreator}

    @ivar _tlsMode: Whether or not the connection is over TLS.
    @type _tlsMode: L{bool}
    TFNc                 O   s.   t j| g|R i | g | _|| _|| _d S rw   )r<   r   authenticatorssecretcontext)r   r  contextFactoryargskwrt   rt   ru   r     s   
zESMTPClient.__init__c                 C   s2   |dkrt jdtdd | jS td| jj|f )NtlsModeStlsMode attribute of twisted.mail.smtp.ESMTPClient is deprecated since Twisted 13.0rV   category
stacklevelz%s instance has no attribute %r)warningswarnDeprecationWarning_tlsModer   r   r   )r   namert   rt   ru   __getattr__  s   zESMTPClient.__getattr__c                 C   s0   |dkrt jdtdd || _d S || j|< d S )Nr  r  rV   r  )r  r  r  r  r   )r   r  r  rt   rt   ru   __setattr__  s   
zESMTPClient.__setattr__r   c                 C      |  tdd| j  dS )a  
        Fail because authentication is required, but the server does not support
        ESMTP, which is required for authentication.

        @param code: The server status code from the most recently received
            server message.
        @type code: L{int}

        @param resp: The server status response from the most recently received
            server message.
        @type resp: L{bytes}
          s,   Server does not support ESMTP AuthenticationN)r  r   r*   r   r  rt   rt   ru   esmtpEHLORequired  s
   zESMTPClient.esmtpEHLORequiredc                 C   sP   g }| j D ]}||   qdd| }| tdd| | j  dS )a  
        Fail because authentication is required, but the server does not support
        any schemes we support.

        @param code: The server status code from the most recently received
            server message.
        @type code: L{int}

        @param resp: The server status response from the most recently received
            server message.
        @type resp: L{bytes}
        s   [%s]s   , r  s8   Server does not support Client Authentication schemes %sN)	r  r   getNamer   r   r  r   r*   r   )r   r   r  tmpaauthrt   rt   ru   esmtpAUTHRequired  s   
zESMTPClient.esmtpAUTHRequiredc                 C   r  )a`  
        Fail because TLS is required and the server does not support it.

        @param code: The server status code from the most recently received
            server message.
        @type code: L{int}

        @param resp: The server status response from the most recently received
            server message.
        @type resp: L{bytes}
        r  s:   Server does not support secure communication via TLS / SSLN)r  r#   r*   r   r  rt   rt   ru   esmtpTLSRequired  s   zESMTPClient.esmtpTLSRequiredc                 C   s   |  t|d| j  dS )a[  
        Fail because the TLS handshake wasn't able to be completed.

        @param code: The server status code from the most recently received
            server message.
        @type code: L{int}

        @param resp: The server status response from the most recently received
            server message.
        @type resp: L{bytes}
        s(   Could not complete the SSL/TLS handshakeN)r  r0   r*   r   r  rt   rt   ru   esmtpTLSFailed&  s
   zESMTPClient.esmtpTLSFailedc                 C      |  t||| j  dS )aM  
        Fail because the authentication was rejected.

        @param code: The server status code from the most recently received
            server message.
        @type code: L{int}

        @param resp: The server status response from the most recently received
            server message.
        @type resp: L{bytes}
        N)r  r   r*   r   r  rt   rt   ru   esmtpAUTHDeclined8     zESMTPClient.esmtpAUTHDeclinedc                 C   r  )ab  
        Fail because the server sent a malformed authentication challenge.

        @param code: The server status code from the most recently received
            server message.
        @type code: L{int}

        @param resp: The server status response from the most recently received
            server message.
        @type resp: L{bytes}
        r	  sR   Login failed because the SMTP Server returned a malformed Authentication ChallengeNr  r   r*   r   r  rt   rt   ru   esmtpAUTHMalformedChallengeF  s   z'ESMTPClient.esmtpAUTHMalformedChallengec                 C   r  )aP  
        Fail because of some other authentication error.

        @param code: The server status code from the most recently received
            server message.
        @type code: L{int}

        @param resp: The server status response from the most recently received
            server message.
        @type resp: L{bytes}
        Nr  r  rt   rt   ru   esmtpAUTHServerError[  r  z ESMTPClient.esmtpAUTHServerErrorc                 C   s   | j | dS )a  
        Registers an Authenticator with the ESMTPClient. The ESMTPClient will
        attempt to login to the SMTP Server in the order the Authenticators are
        registered. The most secure Authentication mechanism should be
        registered first.

        @param auth: The Authentication mechanism to register
        @type auth: L{IClientAuthentication} implementor

        @return: L{None}
        N)r  r   )r   r  rt   rt   ru   registerAuthenticatori  s   z!ESMTPClient.registerAuthenticatorc                 C   s$   t | j| _t|  | j| _dS )zp
        Called when a connection has been made, and triggers sending an C{EHLO}
        to the server.
        N)r   
providedByr   r  r<   r   esmtpState_ehlor  r   rt   rt   ru   r   w  s   
zESMTPClient.connectionMadec                 C   sT   t | _| j| _| j| _| jrd}n| j}| jr | j	s |s | j
| _| d| j  dS )a  
        Send an C{EHLO} to the server.

        If L{heloFallback} is C{True}, and there is no requirement for TLS or
        authentication, the client will fall back to basic SMTP.

        @param code: The server status code from the most recently received
            server message.
        @type code: L{int}

        @param resp: The server status response from the most recently received
            server message.
        @type resp: L{bytes}

        @return: L{None}
        Fs   EHLO N)r  r  esmtpState_serverConfigr  r  r  r  requireTransportSecurityheloFallbackrequireAuthenticationr  r   rx  )r   r   r  needTLSrt   rt   ru   r    s   zESMTPClient.esmtpState_ehloc                 C   sZ   i }|  D ]}|dd}t|dkr|d ||d < qd||d < q| ||| dS )z
        Handle a positive response to the I{EHLO} command by parsing the
        capabilities in the server's response and then taking the most
        appropriate next step towards entering a mail transaction.
        NrK   r   )r   r   r   tryTLS)r   r   r  itemsr   r  rt   rt   ru   r    s   z#ESMTPClient.esmtpState_serverConfigc                 C   sn   | j }| jo	d|v }| j}|s|s|s| ||| dS |r1dg| _| j| _| j| _| 	d dS | 
  dS )a  
        Take a necessary step towards being able to begin a mail transaction.

        The step may be to ask the server to being a TLS session.  If TLS is
        already in use or not necessary and not available then the step may be
        to authenticate with the server.  If TLS is necessary and not available,
        fail the mail transmission attempt.

        This is an internal helper method.

        @param code: The server status code from the most recently received
            server message.
        @type code: L{int}

        @param resp: The server status response from the most recently received
            server message.
        @type resp: L{bytes}

        @param items: A mapping of ESMTP extensions offered by the server.  Keys
            are extension identifiers and values are the associated values.
        @type items: L{dict} mapping L{bytes} to L{bytes}

        @return: L{None}
           STARTTLSr   N)r  r  r  authenticater  esmtpState_starttlsr  r  r  r   r  )r   r   r  r  hasTLScanTLSmustTLSrt   rt   ru   r    s   %zESMTPClient.tryTLSc                 C   sN   z| j | j d| _W n ty   t  | d Y nw | || dS )z
        Handle a positive response to the I{STARTTLS} command by starting a new
        TLS session on C{self.transport}.

        Upon success, re-handshake with the server to discover what capabilities
        it has when TLS is in use.
        Tr  N)	r   startTLSr  r  r-  r*   r   r  r  r  rt   rt   ru   r    s   
zESMTPClient.esmtpState_starttlsc           
      C   s   | j rk|drk|d  }i }|D ]}d|| < q| jD ]L}|  }||v rj|| _|dkrT| j| _| j	| _
dg| _t| j| j d}	| d||	f   d S dg| _| j| _| j| _
| d|   d S q| jrt|   d S | || d S )N   AUTHrK      PLAIN   s
   AUTH %s %sN  s   AUTH )r  getr   r   r  r  	_authinfor  r  _esmtpState_plainAuthr  r  base64	b64encodechallengeResponser   esmtpState_challenger  r  r  )
r   r   r  r  schemes
tmpSchemesr  r  r  	challengert   rt   ru   r    s6   
	zESMTPClient.authenticatec                 C   s@   | j | _| j| _dg| _t| j| j	d}| 
d|  d S )Nr  rV   s   AUTH PLAIN )r  r  r  r  r  r  r  r  r  r  r   )r   r   r  r  rt   rt   ru   r    s
   z!ESMTPClient._esmtpState_plainAuthc                 C   s   |  | j| d S rw   )_authResponser  r  rt   rt   ru   r  $  s   z ESMTPClient.esmtpState_challengec                 C   s|   | j | _zt|}W n tjy#   | d | j| _| j| _Y d S w |	| j
|}ddg| _| j| _| t| d S )N   *r  r  )r  r  r  	b64decodebinasciiErrorr   r  r  r  r  r  smtpState_maybeAuthenticatedr  )r   r  r  r  rt   rt   ru   r  '  s   

zESMTPClient._authResponsec                 C   s.   |dkr| ` | || dS | | j | dS )z
        Called to handle the next message from the server after sending a
        response to a SASL challenge.  The server response might be another
        challenge or it might indicate authentication has succeeded.
        r  N)r  r  r  r  rt   rt   ru   r  6  s   z(ESMTPClient.smtpState_maybeAuthenticatedrw   )r   N)r   r   r   r   r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  rt   rt   rt   ru   r8     s8    







	 3'r8   c                   @   s~   e Zd ZdZdZdZdZdddZdd Zdd Z	d	d
 Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd ZdS )r7   NFc                 C   s,   t |  |d u ri }|| _d| _|| _d S )NF)r;   r   challengersauthenticatedctx)r   chalr  rt   rt   ru   r   L  s   

zESMTP.__init__c                 C   s.   t |  t| j| _| jo| jd u| _d S rw   )r;   r   r   r  r   canStartTLSr  r   rt   rt   ru   r   T  s   
zESMTP.connectionMadec                 C   s   t | d S )Ns    ESMTP)r;   r   r   rt   rt   ru   r   Y  r   zESMTP.greetingc                 C   s*   dt | j i}| jr| jsd|d< |S )z
        SMTP service extensions

        @return: the SMTP service extensions that are supported.
        @rtype: L{dict} with L{bytes} keys and a value of either L{None} or a
            L{list} of L{bytes}.
        r  Nr  )r   r  keysr  
startedTLS)r   extrt   rt   ru   
extensions\  s   zESMTP.extensionsc                 C   s4   t |}t| |}|d u rt| d|  d }|S )Next_)r-   r;   r   r   r   )r   r   r  rt   rt   ru   r   i  s
   zESMTP.lookupMethodc                 C   sT   g }|    D ]\}}|d ur|r||d d|  q|| qd|S )N    r  )r  r  r   r   )r   rcvrt   rt   ru   listExtensionsq  s   
zESMTP.listExtensionsc                 C   s\   | j  j}t|ts|d}||f| _d | _g | _| 	d| jd | d | 
   d S )Nr  r  r  s   , nice to meet you
)r   r   r   r   r   r   r   r   r   r   r  )r   r  r   rt   rt   ru   do_EHLO}  s$   


zESMTP.do_EHLOc                 C   sV   | j r| dd d S | jr#| jr#| dd | j| j d| _ d S | dd d S )Nr  s   TLS already negotiatedr   s   Begin TLS negotiation nowT  s   TLS not available)r   r   r  r  r   r  r   rt   rt   ru   ext_STARTTLS  s   
zESMTP.ext_STARTTLSc                 C   s   | j r| dd d S |d d}| j|d  dd  }|s)| dd d S t| _|| _t	|dkr>|
  |d }nd }| | d S )	Nr  s   Already authenticatedrK   r   c                   S   s   d S rw   rt   rt   rt   rt   ru   rz     s    z ESMTP.ext_AUTH.<locals>.<lambda>i  s    Unrecognized authentication type)r  r   r   r  r  r   r   r   rQ  r   getChallenge
state_AUTH)r   r  r   r  rt   rt   ru   ext_AUTH  s   
zESMTP.ext_AUTHc                 C   s   t | |}d| _|S )zz
        Save the state resulting from a successful cred login and mark this
        connection as authenticated.
        T)r;   rU  r  )r   	loginInforM  rt   rt   ru   _cbAuthenticated  s   zESMTP._cbAuthenticatedc                 C   s@   d| _ |tjjr| dd dS t|d | dd dS )a  
        Handle cred login errors by translating them to the SMTP authenticate
        failed.  Translate all other errors into a generic SMTP error code and
        log the failure for inspection.  Stop all errors from propagating.

        @param reason: Reason for failure.
        Ni  s   Authentication failedzSMTP authentication failurer  r  )r  r  r   r	   rV  r   r*   r   r  rt   rt   ru   _ebAuthenticated  s
   zESMTP._ebAuthenticatedc              	      s4   j du r dd t _dS |du r& j }t|} d| dS |dkr8 dd d _t _dS zt|}W n t	t
jfyX    dd d _t _Y dS w  j|  j rv j }t|} d| dS t _ j  jdtt}| j | fd	d
 | j dS )a+  
        Handle one step of challenge/response authentication.

        @param response: The text of a response. If None, this
        function has been called as a result of an AUTH command with
        no initial response. A response of '*' aborts authentication,
        as per RFC 2554.
        Nr
  s    Temporary authentication failurer  r  r	  s   Authentication aborteds'   Syntax error in parameters or argumentsc                    s     ddS )Nr  s   Authentication successful.r   )ignr   rt   ru   rz     s    z"ESMTP.state_AUTH.<locals>.<lambda>)r_  r   r   r   rQ  r  r  r  r  	TypeErrorr  r  setResponsemoreChallengesr`  r&   r%   rH  r  
addErrbackr  )r   responser  encodeduncodedcodedrM  rt   r   ru   r    sJ   
	






zESMTP.state_AUTHr   )r   r   r   r  r  r   r  r   r   r   r  r   r  r	  r  r  r  r  r  rt   rt   rt   ru   r7   E  s"    

	r7   c                   @   s<   e Zd ZdZdZdd Zdd Zdd Zd	d
 Zdd Z	dS )r6   zi
    Utility class for sending emails easily.

    Use with SMTPSenderFactory or ESMTPSenderFactory.
    r   c                 C   s   | j sd| _ t| jjS d S NrK   )doner   factoryr  r   rt   rt   ru   r    s   zSenderMixin.getMailFromc                 C      | j jS rw   )r  toEmailr   rt   rt   ru   r       zSenderMixin.getMailToc                 C   r  rw   )r  filer   rt   rt   ru   r    r   zSenderMixin.getMailDatac                 C   sT   t | | | jjdks|js&|jdkr|jdk s(d| j_| jj| d S d S d S )Nr   i  r   T)	r<   r  r  retriesretryr   sendFinishedrM  errbackr  rt   rt   ru   r    s   zSenderMixin.sendErrorc                 C   s   d| j _|tvrBg }|D ]\}}}	|tvr'||d td|f  d |	  q||  t||d||}
| j j	|
 d S | j j
||f d S )NTr  z%03dr  r  )r  r$  r  r   r.   r   r   r   rM  r%  callback)r   r   r  r  r  r*   errlogr   acodearesprY  rt   rt   ru   r  !  s   zSenderMixin.sentMailN)
r   r   r   r   r  r  r  r  r  r  rt   rt   rt   ru   r6     s    r6   c                   @   s   e Zd ZdZdS )r>   z|
    SMTP protocol that sends a single email based on information it
    gets from its factory, a L{SMTPSenderFactory}.
    N)r   r   r   r   rt   rt   rt   ru   r>   4  s    r>   c                   @   s`   e Zd ZU dZeZeZee	 e
d< dddZdd Zd	d
 Zdd Zdd Zdd Zdd ZdS )r?   a  
    Utility factory for sending emails easily.

    @type currentProtocol: L{SMTPSender}
    @ivar currentProtocol: The current running protocol returned by
        L{buildProtocol}.

    @type sendFinished: C{bool}
    @ivar sendFinished: When the value is set to True, it means the message has
        been sent or there has been an unrecoverable error or the sending has
        been cancelled. The default value is False.
    r
   re   Nc           	      C   s   t |tsJ t |tr|dg}n!t |tr|g}ng }|D ]}t |ts,|d}|| q |}t|| _t|| _	|| _
|| _|| _| j| j d| _d| _| | _|| _dS )ao  
        @param fromEmail: The RFC 2821 address from which to send this
        message.

        @param toEmail: A sequence of RFC 2821 addresses to which to
        send this message.

        @param file: A file-like object containing the message to send.

        @param deferred: A Deferred to callback or errback when sending
        of this message completes.
        @type deferred: L{defer.Deferred}

        @param retries: The number of times to retry delivery of this
        message.

        @param timeout: Period, in seconds, for which to wait for
        server responses, or None to wait forever.
        rI   FN)r   rm   r   r   r   r   r3   r  r   nEmailsr  r!  rM  addBoth_removeDeferredr$  currentProtocolr"  r   )	r   r  r  r!  deferredr"  r   toEmailFinal_emailrt   rt   ru   r   L  s*   






zSMTPSenderFactory.__init__c                 C   s   | ` |S rw   )rM  r   rM  rt   rt   ru   r,  {  s   z!SMTPSenderFactory._removeDeferredc                 C      |  || d S rw   _processConnectionErrorr   	connectorr   rt   rt   ru   clientConnectionFailed  r   z(SMTPSenderFactory.clientConnectionFailedc                 C   r2  rw   r3  r5  rt   rt   ru   clientConnectionLost  r   z&SMTPSenderFactory.clientConnectionLostc                 C   s   d | _ | jdk r(| js(td| j   | jdd |  |  jd7  _d S | js@|t	j
r7tdd|_| j|j d S d S )Nr   z&SMTP Client retrying server. Retry: %srK   r   zUnable to connect to server.)r-  r"  r$  r*   r   r!  seekconnectr  r	   ConnectionDoner   r  rM  r%  r5  rt   rt   ru   r4    s   z)SMTPSenderFactory._processConnectionErrorc                 C   s>   |  | j| jd d }| |_| j|_|| _| j| j |S )NrV   )	r
   r   r*  r  r   r-  rM  r+  _removeProtocolru  rt   rt   ru   rt    s   zSMTPSenderFactory.buildProtocolc                 C   s   | j rd| _ |S )z
        Remove the protocol created in C{buildProtocol}.

        @param result: The result/error passed to the callback/errback of
            L{defer.Deferred}.

        @return: The C{result} untouched.
        N)r-  r1  rt   rt   ru   r<    s   	z!SMTPSenderFactory._removeProtocol)re   N)r   r   r   r   r   r   r>   r
   r   r<   __annotations__r   r,  r7  r8  r4  rt  r<  rt   rt   rt   ru   r?   ;  s   
 
/r?   c                   @   s   e Zd ZdZdd ZdS )r   a&  
    L{LOGINCredentials} generates challenges for I{LOGIN} authentication.

    For interoperability with Outlook, the challenge generated does not exactly
    match the one defined in the
    U{draft specification<http://sepp.oetiker.ch/sasl-2.1.19-ds/draft-murchison-sasl-login-00.txt>}.
    c                 C   s   t |  ddg| _d S )Ns	   Password:s	   Username:)_lcredentialsr   
challengesr   rt   rt   ru   r     s   
zLOGINCredentials.__init__N)r   r   r   r   r   rt   rt   rt   ru   r     s    r   c                   @   s&   e Zd Zdd Zdd Zd	ddZdS )
r2   c                 C   rr  rw   r(  rc  rt   rt   ru   r     r   zPLAINAuthenticator.__init__c                 C   s   dS )Nr  rt   r   rt   rt   ru   r    s   zPLAINAuthenticator.getNamerK   c                 C   s2   |dkr| j d | j  d | S d| j  d | S )NrK       r@  )r   r  r  rt   rt   ru   r    s   z$PLAINAuthenticator.challengeResponseN)rK   )r   r   r   r   r  r  rt   rt   rt   ru   r2     s    r2   c                   @   s.   e Zd ZdZdZd	ddZdd Zdd ZdS )
r9   TNc                 O   sR   d| _ || _|dd | _|d u r|  }tj| ||g|R i | |   d S )Nr   hostname)r  usernamepop	_hostname_getContextFactoryr8   r   _registerAuthenticators)r   rC  r  r  r  r  rt   rt   ru   r     s   zESMTPSender.__init__c                 C   s4   |  t| j |  t| j |  t| j d S rw   )r  r   rC  r   r2   r   rt   rt   ru   rG    s   z#ESMTPSender._registerAuthenticatorsc                 C   sR   | j d ur| j S | jd u rd S zddlm} W n
 ty!   Y d S w || j}|S )Nr   )optionsForClientTLS)r  rE  twisted.internet.sslrH  ImportError)r   rH  r  rt   rt   ru   rF    s   


zESMTPSender._getContextFactoryrw   )r   r   r   r  r  r   rG  rF  rt   rt   rt   ru   r9     s    
r9   c                   @   s4   e Zd ZdZeZ							d
ddZdd	 ZdS )r:   z
    Utility factory for sending emails easily.

    @type currentProtocol: L{ESMTPSender}
    @ivar currentProtocol: The current running protocol as made by
        L{buildProtocol}.
    re   NFTc              	   C   sD   t | |||||| || _|| _|	| _|
| _|| _|| _|| _d S rw   )	r?   r   rC  password_contextFactory_heloFallback_requireAuthentication_requireTransportSecurityrE  )r   rC  rK  r  r  r!  r.  r"  r   r  r  r  r  rB  rt   rt   ru   r     s   
zESMTPSenderFactory.__init__c                 C   sh   | j | j| j| j| j| jd d | jd}| j|_| j	|_
| j|_| |_| j|_|| _| j| j |S )a)  
        Build an L{ESMTPSender} protocol configured with C{heloFallback},
        C{requireAuthentication}, and C{requireTransportSecurity} as specified
        in L{__init__}.

        This sets L{currentProtocol} on the factory, as well as returning it.

        @rtype: L{ESMTPSender}
        rV   )rB  )r
   rC  rK  rL  r   r*  rE  rM  r  rN  r  rO  r  r  r   r-  rM  r+  r<  ru  rt   rt   ru   rt    s    
z ESMTPSenderFactory.buildProtocol)re   NNFTTN)r   r   r   r   r9   r
   r   rt  rt   rt   rt   ru   r:     s    

r:      Fc                    s   t |dstt|} fdd}t|}t|tr!|d}t|tr+|d}| }t|ts6t|}t	||||||d|	|
|d
|durMt
|_|| | |S )aR
  
    Send an email.

    This interface is intended to be a replacement for L{smtplib.SMTP.sendmail}
    and related methods. To maintain backwards compatibility, it will fall back
    to plain SMTP, if ESMTP support is not available. If ESMTP support is
    available, it will attempt to provide encryption via STARTTLS and
    authentication if a secret is provided.

    @param smtphost: The host the message should be sent to.
    @type smtphost: L{bytes}

    @param from_addr: The (envelope) address sending this mail.
    @type from_addr: L{bytes}

    @param to_addrs: A list of addresses to send this mail to.  A string will
        be treated as a list of one address.
    @type to_addrs: L{list} of L{bytes} or L{bytes}

    @param msg: The message, including headers, either as a file or a string.
        File-like objects need to support read() and close(). Lines must be
        delimited by '\n'. If you pass something that doesn't look like a file,
        we try to convert it to a string (so you should be able to pass an
        L{email.message} directly, but doing the conversion with
        L{email.generator} manually will give you more control over the process).

    @param senderDomainName: Name by which to identify. If None, try to pick
        something sane (but this depends on external configuration and may not
        succeed).
    @type senderDomainName: L{bytes}

    @param port: Remote port to which to connect.
    @type port: L{int}

    @param username: The username to use, if wanting to authenticate.
    @type username: L{bytes} or L{unicode}

    @param password: The secret to use, if wanting to authenticate. If you do
        not specify this, SMTP authentication will not occur.
    @type password: L{bytes} or L{unicode}

    @param requireTransportSecurity: Whether or not STARTTLS is required.
    @type requireTransportSecurity: L{bool}

    @param requireAuthentication: Whether or not authentication is required.
    @type requireAuthentication: L{bool}

    @param reactor: The L{reactor} used to make the TCP connection.

    @rtype: L{Deferred}
    @returns: A cancellable L{Deferred}, its callback will be called if a
        message is sent to ANY address, the errback if no message is sent. When
        the C{cancel} method is called, it will stop retrying and disconnect
        the connection immediately.

        The callback will be called with a tuple (numOk, addresses) where numOk
        is the number of successful recipient addresses and addresses is a list
        of tuples (address, code, resp) giving the response to the RCPT command
        for each address.
    readc                    s(   d_ jrjj  dS    dS )z
        Cancel the L{twisted.mail.smtp.sendmail} call, tell the factory not to
        retry and disconnect the connection.

        @param d: The L{defer.Deferred} to be cancelled.
        TN)r$  r-  r   abortConnection
disconnect)r)  r6  r  rt   ru   cancel  s   zsendmail.<locals>.cancelzutf-8T)r  r  r  rB  N)hasattrr   r   r   Deferredr   r   r   r   r:   r.   r   
connectTCP)smtphost	from_addrto_addrsr   senderDomainNameportr   rC  rK  r  r  rU  r)  tlsHostnamert   rT  ru   r5   2  s6   
I






r5   c                 C   st   g }t | D ]*}t|}|dks|dks|dk s|dkr(|td|d q|t|f qd|t| fS )N+=!   ~   02Xr   )r,   ordr   r.   r   r   r   )r  errorsr  chort   rt   ru   rH     s    rH   c              
   C   s   g }d}|t | k r`| ||d  dkrFz|ttt| |d |d  d W n ty@   |t| ||d   Y nw |d7 }n|t| ||d  d |d7 }|t | k s
d|t | fS )z
    Decode the xtext-encoded string C{s}.

    @param s: String to decode.
    @param errors: codec error handling scheme.
    @return: The decoded string.
    r   rK      +rc      rI   r{   )	r   r   chrrm   r   r  rd  r   r   )r  re  r  rv   rt   rt   ru   rG     s   ,
 
rG   c                   @      e Zd ZdddZdS )rD   strictc                 C      t |S rw   )rG   r   r  re  rt   rt   ru   r     r   zxtextStreamReader.decodeNrl  r   r   r   r   rt   rt   rt   ru   rD         rD   c                   @   rk  )rE   rl  c                 C   rm  rw   )rH   rn  rt   rt   ru   r     r   zxtextStreamWriter.decodeNro  rp  rt   rt   rt   ru   rE     rq  rE   c                 C   s   | dkr
t tttfS d S )Nxtext)rH   rG   rD   rE   )r  rt   rt   ru   rF     s   rF   r  rw   )yr   r  r  r~   r   r   socketrf   r  email.utilsr   ior   typingr   zope.interfacer   twistedr   twisted.copyrightr   twisted.internetr   r	   r
   r   twisted.internet._idnar   twisted.internet.interfacesr   r   twisted.mail._credr   r   r   r>  twisted.mail._exceptr   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r0   r#   twisted.mail.interfacesr$   r%   r&   r'   r1   twisted.protocolsr(   r)   twisted.pythonr*   r+   twisted.python.compatr,   r-   r.   twisted.python.runtimer/   __all__isMacOSXgethostnamer   r   getfqdndictfromkeysr  r  rC   r@   ry   rA   rB   r   r   r   r   r3   r4   LineOnlyReceiverTimeoutMixinr;   rs  r=   r~  r<   r8   r7   r6   r>   ClientFactoryr?   r2   r9   r:   r5   codecsrH   rG   StreamReaderrD   StreamWriterrE   rF   registerrt   rt   rt   ru   <module>   s   P6
<
s(   r     ) 88q&H
{

