[Η @sNdZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddlmZddddd d d d d dddg ZdZdZdZdZdZejdejZGdddeZGdddeZGdddeZGdddeZGdd d eZGdd d eZGdd d eZ Gdd d eZ!Gdd d eZ"d dZ#d!d"Z$d#dZ%d$d%Z&d&d'Z'yddl(Z(Wne)k rd(Z*YnXd)Z*Gd*ddZ+e*raGd+d,d,e+Z,ej-d,nd-Z.Gd.d/d/e+Z/e0d0krJddlZd1d2Z1e1d3Z2e1d4j3d5Z4e5d6d7Z6x(ej7j8Z9e9 rPne6e9Z6qWe5d8e:e6e+d9Z;e;j<d:e;j=e2e4e6e;j>ndS);aSMTP/ESMTP client class. This should follow RFC 821 (SMTP), RFC 1869 (ESMTP), RFC 2554 (SMTP Authentication) and RFC 2487 (Secure SMTP over TLS). Notes: Please remember, when doing ESMTP, that the names of the SMTP service extensions are NOT the same thing as the option keywords for the RCPT and MAIL commands! Example: >>> import smtplib >>> s=smtplib.SMTP("localhost") >>> print(s.help()) This is Sendmail version 8.8.4 Topics: HELO EHLO MAIL RCPT DATA RSET NOOP QUIT HELP VRFY EXPN VERB ETRN DSN For more info use "HELP ". To report bugs in the implementation send email to sendmail-bugs@sendmail.org. For local information send email to Postmaster at your site. End of HELP info >>> s.putcmd("vrfy","someone@here") >>> s.getreply() (250, "Somebody OverHere ") >>> s.quit() N) body_encode)stderr SMTPExceptionSMTPServerDisconnectedSMTPResponseExceptionSMTPSenderRefusedSMTPRecipientsRefused SMTPDataErrorSMTPConnectError SMTPHeloErrorSMTPAuthenticationError quoteaddr quotedataSMTPiz s i z auth=(.*)c@seZdZdZdS)rz4Base class for all exceptions raised by this module.N)__name__ __module__ __qualname____doc__rr/usr/lib/python3.4/smtplib.pyrFs c@seZdZdZdS)rzNot connected to any SMTP server. This exception is raised when the server unexpectedly disconnects, or when an attempt is made to use the SMTP instance before connecting it to a server. N)rrrrrrrrrIs c@s"eZdZdZddZdS)ra2Base class for all exceptions that include an SMTP error code. These exceptions are generated in some instances when the SMTP server returns an error code. The error code is stored in the `smtp_code' attribute of the error, and the `smtp_error' attribute is set to the error message. cCs%||_||_||f|_dS)N) smtp_code smtp_errorargs)selfcodemsgrrr__init__Zs  zSMTPResponseException.__init__N)rrrrrrrrrrQs c@s"eZdZdZddZdS)rzSender address refused. In addition to the attributes set by on all SMTPResponseException exceptions, this sets `sender' to the string that the SMTP refused. cCs1||_||_||_|||f|_dS)N)rrsenderr)rrrrrrrrfs   zSMTPSenderRefused.__init__N)rrrrrrrrrr_s c@s"eZdZdZddZdS)rzAll recipient addresses refused. The errors for each recipient are accessible through the attribute 'recipients', which is a dictionary of exactly the same sort as SMTP.sendmail() returns. cCs||_|f|_dS)N) recipientsr)rrrrrrts zSMTPRecipientsRefused.__init__N)rrrrrrrrrrls c@seZdZdZdS)r z'The SMTP server didn't accept the data.N)rrrrrrrrr ys c@seZdZdZdS)r z&Error during connection establishment.N)rrrrrrrrr |s c@seZdZdZdS)r z"The server refused our HELO reply.N)rrrrrrrrr s c@seZdZdZdS)r zvAuthentication error. Most probably the server didn't accept the username/password combination provided. N)rrrrrrrrr s cCsStjj|\}}||fdkrK|jjdrC|Sd|Sd|S)zQuote a subset of the email addresses defined by RFC 821. Should be able to handle anything email.utils.parseaddr can handle. )r r )emailutils parseaddrstrip startswith) addrstring displaynameaddrrrrr s cCs2tjj|\}}||fdkr.|S|S)Nr )r r )r"r#r$)r'r(r)rrr _addr_onlysr*cCs"tjddtjdt|S)zQuote data for email. Double leading '.', and change Unix newline '\n', or Mac '\r' into Internet CRLF end-of-line. z(?m)^\.z..z(?:\r\n|\n|\r(?!\n)))resubCRLF)datarrrrs cCstjdd|S)Ns(?m)^\.s..)r+r,)Zbindatarrr_quote_periodssr/cCstjdt|S)Nz(?:\r\n|\n|\r(?!\n)))r+r,r-)r.rrr _fix_eolssr0FTc@seZdZdZdZdZdZdZdZdZ e Z ddde j dddZdd Zd d Zd d ZddZdddddZddZdddZddZdddZdddZdddZdd Zdd!d"Zd#d$Zd%d&Zd'd(Zgd)d*Zgd+d,Z d-d.Z!d/d0Z"e"Z#d1d2Z$d3d4Z%d5d6Z&dddd7d8Z'ggd9d:Z(ddgid;d<Z)d=d>Z*d?d@Z+dS)AraThis class manages a connection to an SMTP or ESMTP server. SMTP Objects: SMTP objects have the following attributes: helo_resp This is the message given by the server in response to the most recent HELO command. ehlo_resp This is the message given by the server in response to the most recent EHLO command. This is usually multiline. does_esmtp This is a True value _after you do an EHLO command_, if the server supports ESMTP. esmtp_features This is a dictionary, which, if the server supports ESMTP, will _after you do an EHLO command_, contain the names of the SMTP service extensions this server supports, and their parameters (if any). Note, all extension names are mapped to lower case in the dictionary. See each method's docstrings for details. In general, there is a method of the same name to perform each SMTP command. There is also a method called 'sendmail' that will do an entire mail transaction. rNehlor c Cs||_||_i|_||_|rc|j||\}}|dkrct||qcn|dk r{||_nhtj}d|kr||_nDd} ytj tj } Wntj k rYnXd| |_dS)aInitialize a new instance. If specified, `host' is the name of the remote host to which to connect. If specified, `port' specifies the port to which to connect. By default, smtplib.SMTP_PORT is used. If a host is specified the connect method is called, and if it returns anything other than a success code an SMTPConnectError is raised. If specified, `local_hostname` is used as the FQDN of the local host in the HELO/EHLO command. Otherwise, the local hostname is found using socket.getfqdn(). The `source_address` parameter takes a 2-tuple (host, port) for the socket to bind to as its source address before connecting. If the host is '' and port is 0, the OS default behavior will be used. N.z 127.0.0.1z[%s]) _hosttimeoutesmtp_featuressource_addressconnectr local_hostnamesocketZgetfqdnZ gethostbynameZ gethostnameZgaierror) rhostportr9r5r7rrZfqdnr)rrrrs&          z SMTP.__init__cCs|S)Nr)rrrr __enter__szSMTP.__enter__cGsbzPy7|jd\}}|dkr9t||nWntk rNYnXWd|jXdS)NZQUIT)docmdrrclose)rrrmessagerrr__exit__ s   z SMTP.__exit__cCs ||_dS)zSet the debug output level. A non-false value results in debug messages for connection and for all messages sent to and received from the server. N) debuglevel)rrCrrrset_debuglevelszSMTP.set_debuglevelcCsM|jdkr1td||f|jdtntj||f||jS)Nrz connect: tofile)rCprintr7rr:create_connection)rr;r<r5rrr _get_sockets  zSMTP._get_socket localhostc CsP|r||_n| r|jd|jdkr|jd}|dkr|d|||dd}}yt|}Wqtk rtdYqXqn|s|j}n|jdkrtd||fdt n|j |||j |_ d|_ |j\}}|jdkrFtd|dt n||fS)apConnect to a host on a given port. If the hostname ends with a colon (`:') followed by a number, and there is no port specified, that suffix will be stripped off and the number interpreted as the port number to use. Note: This method is automatically invoked by __init__, if a host is specified during instantiation. :rNznonnumeric portzconnect:rE)r7findrfindint ValueErrorOSError default_portrCrFrrHr5sockrEgetreply)rr;r<r7irrrrrr8&s(  % %   z SMTP.connectc Cs|jdkr+tdt|dtnt|dr|jrt|trd|jd}ny|jj |Wqt k r|j t dYqXn t ddS) zSend `s' to the server.rzsend:rErRasciizServer not connectedzplease run connect() firstN) rCrFreprrhasattrrR isinstancestrencodeZsendallrPr@r)rsrrrsendHs  z SMTP.sendcCsC|dkrd|tf}nd||tf}|j|dS)zSend a command to the server.r z%s%sz%s %s%sN)r-r\)rcmdrrYrrrputcmdWs z SMTP.putcmdcCsg}|jdkr-|jjd|_nxTy|jjtd}WnEtk r}z%|jtdt|WYdd}~XnX|s|jtdn|j dkrt dt |dt nt |tkr |jtd d n|j|d djd |dd }yt|}Wntk red}PYnX|d d dkr0Pq0q0Wdj|}|j dkrt d||fdt n||fS)aGet a reply from the server. Returns a tuple consisting of: - server response code (e.g. '250', or such, if all goes well) Note: returns -1 if it can't read response code. - server response string corresponding to response code (multiline responses are converted to a single, multiline string). Raises SMTPServerDisconnected if end-of-file is reached. NrbrKz Connection unexpectedly closed: zConnection unexpectedly closedrzreply:rEizLine too long.s -s zreply: retcode (%s); Msg: %s)rErRZmakefilereadline_MAXLINErPr@rrYrCrFrVrlenrappendr%rNrOjoin)rresplineerZerrcodeerrmsgrrrrS_s@  #     z SMTP.getreplycCs|j|||jS)z-Send a command, and return its response code.)r^rS)rr]rrrrr?sz SMTP.docmdcCs>|jd|p|j|j\}}||_||fS)zwSMTP 'helo' command. Hostname to send for this command defaults to the FQDN of the local host. helo)r^r9rS helo_resp)rnamerrrrrrms z SMTP.heloc Csi|_|j|j|p!|j|j\}}|d krnt|dkrn|jtdn||_|dkr||fSd|_ t |jt st t |j|jjdjd}|d=x|D]}tj|}|r8|jjddd |jdd|jd[A-Za-z0-9][A-Za-z0-9\-]*) ?featureNrc)r6r^ehlo_msgr9rSrfr@r ehlo_resp does_esmtprXbytesAssertionErrorrVdecodesplit OLDSTYLE_AUTHmatchgetgroupsr+grouplowerstringendr%) rrorrrieachZ auth_matchmrtZparamsrrrr1s4      ' 1" 'z SMTP.ehlocCs|j|jkS)z7Does the server support a given SMTP service extension?)rr6)rZoptrrrhas_extnsz SMTP.has_extncCs|jd||jdS)z;SMTP 'help' command. Returns help text from server.helprK)r^rS)rrrrrrsz SMTP.helpcCs |jdS)z&SMTP 'rset' command -- resets session.rset)r?)rrrrrsz SMTP.rsetc Cs'y|jWntk r"YnXdS)aInternal 'rset' command which ignores any SMTPServerDisconnected error. Used internally in the library, since the server disconnected error should appear to the application when the *next* command is issued, if we are doing an internal "safety" reset. N)rr)rrrr_rsets z SMTP._rsetcCs |jdS)z-SMTP 'noop' command -- doesn't do anything :>noop)r?)rrrrrsz SMTP.noopcCsUd}|r+|jr+ddj|}n|jddt||f|jS)z0SMTP 'mail' command -- begins mail xfer session.r rsmailz FROM:%s%s)rwrhr^r rS)rroptions optionlistrrrrs  z SMTP.mailcCsUd}|r+|jr+ddj|}n|jddt||f|jS)z;SMTP 'rcpt' command -- indicates 1 recipient for this mail.r rsrcptzTO:%s%s)rwrhr^r rS)rZreciprrrrrrs  z SMTP.rcptcCs$|jd|j\}}|jdkrJtd||fdtn|dkrht||nt|trt|j d}nt |}|d dt kr|t }n|d t }|j ||j\}}|jdkrtd||fdtn||fSdS) aSMTP 'DATA' command -- sends message data to server. Automatically quotes lines beginning with a period per rfc821. Raises SMTPDataError if there is an unexpected reply to the DATA command; the return value from this method is the final response code received when the all data is sent. If msg is a string, lone ' ' and ' ' characters are converted to ' ' characters. If msg is bytes, it is transmitted as is. r.rzdata:rEibrUN.) r^rSrCrFrr rXrYr0rZr/bCRLFr\)rrrreplqrrrr.s"     z SMTP.datacCs |jdt||jS)z5SMTP 'verify' command -- checks for address validity.vrfy)r^r*rS)raddressrrrverifysz SMTP.verifycCs |jdt||jS)z.SMTP 'expn' command -- expands a mailing list.expn)r^r*rS)rrrrrr&sz SMTP.expncCs|jdkr|jdkrd|jdko?dkns|j\}}d|komdknst||qqndS)abCall self.ehlo() and/or self.helo() if needed. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. This method may raise the following exceptions: SMTPHeloError The server didn't reply properly to the helo greeting. Nri+)rnrvr1rmr )rrrirrrehlo_or_helo_if_needed-s &zSMTP.ehlo_or_helo_if_neededc sdd}dd}d}d}d}|j|jdsRtd n|jdj|||g}fd d |D} | std nx2| D]*} | |kr|jd |\} } | dkr|j|| ||\} } qn| |kr>|jd |d|||\} } n| |kr|jd d|t|jdddf\} } | dkr|jt|jddd\} } qn| dkr| | fSqWt| | dS)aALog in on an SMTP server that requires authentication. The arguments are: - user: The user name to authenticate with. - password: The password for the authentication. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. This method will return normally if the authentication was successful. This method may raise the following exceptions: SMTPHeloError The server didn't reply properly to the helo greeting. SMTPAuthenticationError The server didn't accept the username/ password combination. SMTPException No suitable authentication method was found. cSsTtj|}|dtj|jd|dj}t|jdddS)NrsrUZmd5eolr )base64Z decodebyteshmacZHMACrZZ hexdigest encode_base64)Z challengeuserpasswordZresponserrrencode_cram_md5Tsz#SMTP.login..encode_cram_md5cSs)d||f}t|jdddS)NZ%s%srUrr )rrZ)rrr[rrr encode_plainZsz SMTP.login..encode_plainZPLAINzCRAM-MD5ZLOGINrrz,SMTP AUTH extension not supported by server.cs"g|]}|kr|qSrr).0rr)advertised_authlistrr qs zSMTP.login..z(No suitable authentication method found.ZAUTHiNrsz%s %srUrr N)rr) rrrr6r{r?rrZr ) rrrrrZ AUTH_PLAINZ AUTH_CRAM_MD5Z AUTH_LOGINZpreferred_authsZauthlistZ authmethodrrir)rrlogin>s:      '  #  . 0 z SMTP.logincCs:|j|jds(tdn|jd\}}|dkr!ts^tdn|dk r|dk rtdn|dk r|dk rtdn|dkrtjd |d |}n|j |j d |j |_ d|_ d|_ d|_i|_d |_nt||||fS) aPuts the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports TLS, this will encrypt the rest of the SMTP session. If you provide the keyfile and certfile parameters, the identity of the SMTP server and client can be checked. This, however, depends on whether the socket module really checks the certificates. This method may raise the following exceptions: SMTPHeloError The server didn't reply properly to the helo greeting. starttlsz+STARTTLS extension not supported by server.ZSTARTTLSr2z&No SSL support included in this PythonNz4context and keyfile arguments are mutually exclusivez5context and certfile arguments are mutually exclusivecertfilekeyfileserver_hostnamer)rrrr? _have_ssl RuntimeErrorrOssl_create_stdlib_context wrap_socketrRr4rErnrvr6rwr)rrrcontextriZreplyrrrrs.         z SMTP.starttlsc Cs |jg}t|tr7t|jd}n|jr|jdri|jdt|nx|D]}|j|qpWn|j ||\}} |dkr|dkr|j n |j t || |ni} t|tr|g}nxv|D]n} |j | |\}} |dkrW|dkrW|| f| | >> import smtplib >>> s=smtplib.SMTP("localhost") >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"] >>> msg = '''\ ... From: Me@my.org ... Subject: testin'... ... ... This is a test ''' >>> s.sendmail("me@my.org",tolist,msg) { "three@three.org" : ( 550 ,"User unknown" ) } >>> s.quit() In the above example, the message was accepted for delivery to three of the four addresses, and one was rejected, with the error code 550. If all addresses are accepted, then the method will return an empty dictionary. rUsizezsize=%drpi)rrXrYr0rZrwrrgrfrr@rrrrr.r ) r from_addrto_addrsr mail_options rcpt_optionsZ esmtp_optsZoptionrriZsenderrsrrrrsendmailsF=                z SMTP.sendmailc Csd|jd}|dkr$d}n't|dkr?d}n td|dkr|d|kru||dn ||d}n|dkrd d ||d ||d ||d fD}dd tjj|D}ntj|} | d =| d=tj8} tj j | } | j | dd| j } WdQX|j ||| ||S)aConverts message to a bytestring and passes it to sendmail. The arguments are as for sendmail, except that msg is an email.message.Message object. If from_addr is None or to_addrs is None, these arguments are taken from the headers of the Message as described in RFC 2822 (a ValueError is raised if there is more than one set of 'Resent-' headers). Regardless of the values of from_addr and to_addr, any Bcc field (or Resent-Bcc field, when the Message is a resent) of the Message object won't be transmitted. The Message object is then serialized using email.generator.BytesGenerator and sendmail is called to transmit the message. z Resent-DateNr rKzResent-z0message has more than one 'Resent-' header blockZSenderFromcSs"g|]}|dk r|qS)Nr)rfrrrrNs z%SMTP.send_message..ToZBccZCccSsg|]}|dqS)rKr)rarrrrQs z Resent-Bcclinesepz )Zget_allrfrOr"r#Z getaddressescopyioBytesIOZ generatorZBytesGeneratorZflattengetvaluer) rrrrrrZresentZ header_prefixZ addr_fieldsZmsg_copyZbytesmsggZflatmsgrrr send_message(s.       "zSMTP.send_messagecCsH|jr|jjnd|_|jr;|jjnd|_dS)z(Close the connection to the SMTP server.N)rEr@rR)rrrrr@]s    z SMTP.closecCs?|jd}d|_|_i|_d|_|j|S)zTerminate the SMTP session.quitNF)r?rvrnr6rwr@)rZresrrrrfs    z SMTP.quit),rrrrrCrErnrurvrw SMTP_PORTrQr:_GLOBAL_DEFAULT_TIMEOUTrr=rBrDrHr8r\r^rSr?rmr1rrrrrrrr.rrrrrrrrr@rrrrrrsT  +  "  2 3        P3f4 c @sOeZdZdZeZdddddejddddZddZ dS) SMTP_SSLa This is a subclass derived from SMTP that connects over an SSL encrypted socket (to use this class you need a socket module that was compiled with SSL support). If host is not specified, '' (the local host) is used. If port is omitted, the standard SMTP-over-SSL port (465) is used. local_hostname and source_address have the same meaning as they do in the SMTP class. keyfile and certfile are also optional - they can contain a PEM formatted private key and certificate chain file for the SSL connection. context also optional, can contain a SSLContext, and is an alternative to keyfile and certfile; If it is specified both keyfile and certfile must be None. r rNc Cs|dk r'|dk r'tdn|dk rN|dk rNtdn||_||_|dkrtjd|d|}n||_tj||||||dS)Nz4context and keyfile arguments are mutually exclusivez5context and certfile arguments are mutually exclusiverr)rOrrrrrrr) rr;r<r9rrr5r7rrrrrs     zSMTP_SSL.__init__cCsh|jdkr+td||fdtntj||f||j}|jj|d|j}|S)Nrzconnect:rEr) rCrFrr:rGr7rrr4)rr;r<r5Z new_socketrrrrHs  zSMTP_SSL._get_socket) rrrr SMTP_SSL_PORTrQr:rrrHrrrrrrs  ric@sIeZdZdZdZdeddddZdddd d ZdS) LMTPaLMTP - Local Mail Transfer Protocol The LMTP protocol, which is very similar to ESMTP, is heavily based on the standard SMTP client. It's common to use Unix sockets for LMTP, so our connect() method must support that as well as a regular host:port server. local_hostname and source_address have the same meaning as they do in the SMTP class. To specify a Unix socket, you must use an absolute path as the host, starting with a '/'. Authentication is supported, using the regular SMTP mechanism. When using a Unix socket, LMTP generally don't support or require any authentication, but your mileage might vary.Zlhlor NcCs#tj|||d|d|dS)zInitialize a new instance.r9r7N)rr)rr;r<r9r7rrrrsz LMTP.__init__rIrc Cs|ddkr)tj|||d|Sy8tjtjtj|_d|_|jj|Wn\tk r|jdkrt d|dt n|jr|jj nd|_YnX|j \}}|jdkrt d|dt n||fS)z=Connect to the LMTP daemon, on either a Unix or a TCP socket.r/r7Nz connect fail:rEzconnect:) rr8r:ZAF_UNIXZ SOCK_STREAMrRrErPrCrFrr@rS)rr;r<r7rrrrrr8s"    z LMTP.connect)rrrrru LMTP_PORTrr8rrrrrs  r__main__cCs4tjj|dtjjtjjjS)Nz: )sysstdoutwriteflushstdinrdr%)promptrrrrs rrr,zEnter message, end with ^D:r zMessage length is %drIrK)?rr:rr+Z email.utilsr"Z email.messageZemail.generatorrrrZemail.base64mimerrrr__all__rrr-rrecompileIr|rPrrrrrr r r r r r*rr/r0r ImportErrorrrrrgrrrrZfromaddrr{ZtoaddrsrFrrrdrjrfZserverrDrrrrrr!s                   ,/