home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / SMTPLIB.PY < prev    next >
Encoding:
Python Source  |  2000-09-28  |  18.5 KB  |  536 lines

  1. #! /usr/bin/env python
  2.  
  3. '''SMTP/ESMTP client class.
  4.  
  5. This should follow RFC 821 (SMTP) and RFC 1869 (ESMTP).
  6.  
  7. Notes:
  8.  
  9. Please remember, when doing ESMTP, that the names of the SMTP service
  10. extensions are NOT the same thing as the option keywords for the RCPT
  11. and MAIL commands!
  12.  
  13. Example:
  14.  
  15.   >>> import smtplib
  16.   >>> s=smtplib.SMTP("localhost")
  17.   >>> print s.help()
  18.   This is Sendmail version 8.8.4
  19.   Topics:
  20.       HELO    EHLO    MAIL    RCPT    DATA
  21.       RSET    NOOP    QUIT    HELP    VRFY
  22.       EXPN    VERB    ETRN    DSN
  23.   For more info use "HELP <topic>".
  24.   To report bugs in the implementation send email to
  25.       sendmail-bugs@sendmail.org.
  26.   For local information send email to Postmaster at your site.
  27.   End of HELP info
  28.   >>> s.putcmd("vrfy","someone@here")
  29.   >>> s.getreply()
  30.   (250, "Somebody OverHere <somebody@here.my.org>")
  31.   >>> s.quit()
  32. '''
  33.  
  34. # Author: The Dragon De Monsyne <dragondm@integral.org>
  35. # ESMTP support, test code and doc fixes added by
  36. #     Eric S. Raymond <esr@thyrsus.com>
  37. # Better RFC 821 compliance (MAIL and RCPT, and CRLF in data)
  38. #     by Carey Evans <c.evans@clear.net.nz>, for picky mail servers.
  39. #    
  40. # This was modified from the Python 1.5 library HTTP lib.
  41.  
  42. import socket
  43. import string
  44. import re
  45. import rfc822
  46. import types
  47.  
  48. SMTP_PORT = 25
  49. CRLF="\r\n"
  50.  
  51. # Exception classes used by this module. 
  52. class SMTPException(Exception):
  53.     """Base class for all exceptions raised by this module."""
  54.  
  55. class SMTPServerDisconnected(SMTPException):
  56.     """Not connected to any SMTP server.
  57.  
  58.     This exception is raised when the server unexpectedly disconnects,
  59.     or when an attempt is made to use the SMTP instance before
  60.     connecting it to a server.
  61.     """
  62.  
  63. class SMTPResponseException(SMTPException):
  64.     """Base class for all exceptions that include an SMTP error code.
  65.  
  66.     These exceptions are generated in some instances when the SMTP
  67.     server returns an error code.  The error code is stored in the
  68.     `smtp_code' attribute of the error, and the `smtp_error' attribute
  69.     is set to the error message.
  70.     """
  71.  
  72.     def __init__(self, code, msg):
  73.         self.smtp_code = code
  74.         self.smtp_error = msg
  75.         self.args = (code, msg)
  76.  
  77. class SMTPSenderRefused(SMTPResponseException):
  78.     """Sender address refused.
  79.     In addition to the attributes set by on all SMTPResponseException
  80.     exceptions, this sets `sender' to the string that the SMTP refused.
  81.     """
  82.  
  83.     def __init__(self, code, msg, sender):
  84.         self.smtp_code = code
  85.         self.smtp_error = msg
  86.         self.sender = sender
  87.         self.args = (code, msg, sender)
  88.  
  89. class SMTPRecipientsRefused(SMTPException):
  90.     """All recipient addresses refused.
  91.     The errors for each recipient are accessible through the attribute
  92.     'recipients', which is a dictionary of exactly the same sort as 
  93.     SMTP.sendmail() returns.  
  94.     """
  95.  
  96.     def __init__(self, recipients):
  97.         self.recipients = recipients
  98.         self.args = ( recipients,)
  99.  
  100.  
  101. class SMTPDataError(SMTPResponseException):
  102.     """The SMTP server didn't accept the data."""
  103.  
  104. class SMTPConnectError(SMTPResponseException):
  105.     """Error during connection establishment."""
  106.  
  107. class SMTPHeloError(SMTPResponseException):
  108.     """The server refused our HELO reply."""
  109.  
  110.  
  111. def quoteaddr(addr):
  112.     """Quote a subset of the email addresses defined by RFC 821.
  113.  
  114.     Should be able to handle anything rfc822.parseaddr can handle.
  115.     """
  116.     m=None
  117.     try:
  118.         m=rfc822.parseaddr(addr)[1]
  119.     except AttributeError:
  120.         pass
  121.     if not m:
  122.         #something weird here.. punt -ddm
  123.         return addr
  124.     else:
  125.         return "<%s>" % m
  126.  
  127. def quotedata(data):
  128.     """Quote data for email.
  129.  
  130.     Double leading '.', and change Unix newline '\\n', or Mac '\\r' into
  131.     Internet CRLF end-of-line.
  132.     """
  133.     return re.sub(r'(?m)^\.', '..',
  134.         re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data))
  135.  
  136.  
  137. class SMTP:
  138.     """This class manages a connection to an SMTP or ESMTP server.
  139.     SMTP Objects:
  140.         SMTP objects have the following attributes:    
  141.             helo_resp 
  142.                 This is the message given by the server in response to the 
  143.                 most recent HELO command.
  144.                 
  145.             ehlo_resp
  146.                 This is the message given by the server in response to the 
  147.                 most recent EHLO command. This is usually multiline.
  148.  
  149.             does_esmtp 
  150.                 This is a True value _after you do an EHLO command_, if the
  151.                 server supports ESMTP.
  152.  
  153.             esmtp_features 
  154.                 This is a dictionary, which, if the server supports ESMTP,
  155.                 will _after you do an EHLO command_, contain the names of the
  156.                 SMTP service extensions this server supports, and their
  157.                 parameters (if any).
  158.  
  159.                 Note, all extension names are mapped to lower case in the 
  160.                 dictionary. 
  161.  
  162.         See each method's docstrings for details.  In general, there is a
  163.         method of the same name to perform each SMTP command.  There is also a
  164.         method called 'sendmail' that will do an entire mail transaction.
  165.         """
  166.     debuglevel = 0
  167.     file = None
  168.     helo_resp = None
  169.     ehlo_resp = None
  170.     does_esmtp = 0
  171.  
  172.     def __init__(self, host = '', port = 0):
  173.         """Initialize a new instance.
  174.  
  175.         If specified, `host' is the name of the remote host to which to
  176.         connect.  If specified, `port' specifies the port to which to connect.
  177.         By default, smtplib.SMTP_PORT is used.  An SMTPConnectError is raised
  178.         if the specified `host' doesn't respond correctly.
  179.  
  180.         """
  181.         self.esmtp_features = {}
  182.         if host:
  183.             (code, msg) = self.connect(host, port)
  184.             if code != 220:
  185.                 raise SMTPConnectError(code, msg)
  186.     
  187.     def set_debuglevel(self, debuglevel):
  188.         """Set the debug output level.
  189.  
  190.         A non-false value results in debug messages for connection and for all
  191.         messages sent to and received from the server.
  192.  
  193.         """
  194.         self.debuglevel = debuglevel
  195.  
  196.     def connect(self, host='localhost', port = 0):
  197.         """Connect to a host on a given port.
  198.  
  199.         If the hostname ends with a colon (`:') followed by a number, and
  200.         there is no port specified, that suffix will be stripped off and the
  201.         number interpreted as the port number to use.
  202.  
  203.         Note: This method is automatically invoked by __init__, if a host is
  204.         specified during instantiation.
  205.  
  206.         """
  207.         if not port:
  208.             i = string.find(host, ':')
  209.             if i >= 0:
  210.                 host, port = host[:i], host[i+1:]
  211.                 try: port = string.atoi(port)
  212.                 except string.atoi_error:
  213.                     raise socket.error, "nonnumeric port"
  214.         if not port: port = SMTP_PORT
  215.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  216.         if self.debuglevel > 0: print 'connect:', (host, port)
  217.         self.sock.connect((host, port))
  218.         (code,msg)=self.getreply()
  219.         if self.debuglevel >0 : print "connect:", msg
  220.         return (code,msg)
  221.     
  222.     def send(self, str):
  223.         """Send `str' to the server."""
  224.         if self.debuglevel > 0: print 'send:', `str`
  225.         if self.sock:
  226.             try:
  227.                 sendptr = 0
  228.                 while sendptr < len(str):
  229.                     sendptr = sendptr + self.sock.send(str[sendptr:])
  230.             except socket.error:
  231.                 raise SMTPServerDisconnected('Server not connected')
  232.         else:
  233.             raise SMTPServerDisconnected('please run connect() first')
  234.  
  235.     def putcmd(self, cmd, args=""):
  236.         """Send a command to the server."""
  237.         if args == "":
  238.             str = '%s%s' % (cmd, CRLF)
  239.         else:
  240.             str = '%s %s%s' % (cmd, args, CRLF)
  241.         self.send(str)
  242.     
  243.     def getreply(self):
  244.         """Get a reply from the server.
  245.         
  246.         Returns a tuple consisting of:
  247.  
  248.           - server response code (e.g. '250', or such, if all goes well)
  249.             Note: returns -1 if it can't read response code.
  250.  
  251.           - server response string corresponding to response code (multiline
  252.             responses are converted to a single, multiline string).
  253.  
  254.         Raises SMTPServerDisconnected if end-of-file is reached.
  255.         """
  256.         resp=[]
  257.         if self.file is None:
  258.             self.file = self.sock.makefile('rb')
  259.         while 1:
  260.             line = self.file.readline()
  261.             if line == '':
  262.                 self.close()
  263.                 raise SMTPServerDisconnected("Connection unexpectedly closed")
  264.             if self.debuglevel > 0: print 'reply:', `line`
  265.             resp.append(string.strip(line[4:]))
  266.             code=line[:3]
  267.             # Check that the error code is syntactically correct.
  268.             # Don't attempt to read a continuation line if it is broken.
  269.             try:
  270.                 errcode = string.atoi(code)
  271.             except ValueError:
  272.                 errcode = -1
  273.                 break
  274.             # Check if multiline response.
  275.             if line[3:4]!="-":
  276.                 break
  277.  
  278.         errmsg = string.join(resp,"\n")
  279.         if self.debuglevel > 0: 
  280.             print 'reply: retcode (%s); Msg: %s' % (errcode,errmsg)
  281.         return errcode, errmsg
  282.     
  283.     def docmd(self, cmd, args=""):
  284.         """Send a command, and return its response code."""
  285.         self.putcmd(cmd,args)
  286.         return self.getreply()
  287.  
  288.     # std smtp commands
  289.     def helo(self, name=''):
  290.         """SMTP 'helo' command.
  291.         Hostname to send for this command defaults to the FQDN of the local
  292.         host.
  293.         """
  294.         if name:
  295.             self.putcmd("helo", name)
  296.         else:
  297.             self.putcmd("helo", socket.getfqdn())
  298.         (code,msg)=self.getreply()
  299.         self.helo_resp=msg
  300.         return (code,msg)
  301.  
  302.     def ehlo(self, name=''):
  303.         """ SMTP 'ehlo' command.
  304.         Hostname to send for this command defaults to the FQDN of the local
  305.         host.
  306.         """
  307.         if name:
  308.             self.putcmd("ehlo", name)
  309.         else:
  310.             self.putcmd("ehlo", socket.getfqdn())
  311.         (code,msg)=self.getreply()
  312.         # According to RFC1869 some (badly written) 
  313.         # MTA's will disconnect on an ehlo. Toss an exception if 
  314.         # that happens -ddm
  315.         if code == -1 and len(msg) == 0:
  316.             raise SMTPServerDisconnected("Server not connected")
  317.         self.ehlo_resp=msg
  318.         if code<>250:
  319.             return (code,msg)
  320.         self.does_esmtp=1
  321.         #parse the ehlo response -ddm
  322.         resp=string.split(self.ehlo_resp,'\n')
  323.         del resp[0]
  324.         for each in resp:
  325.             m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*)',each)
  326.             if m:
  327.                 feature=string.lower(m.group("feature"))
  328.                 params=string.strip(m.string[m.end("feature"):])
  329.                 self.esmtp_features[feature]=params
  330.         return (code,msg)
  331.  
  332.     def has_extn(self, opt):
  333.         """Does the server support a given SMTP service extension?"""
  334.         return self.esmtp_features.has_key(string.lower(opt))
  335.  
  336.     def help(self, args=''):
  337.         """SMTP 'help' command.
  338.         Returns help text from server."""
  339.         self.putcmd("help", args)
  340.         return self.getreply()
  341.  
  342.     def rset(self):
  343.         """SMTP 'rset' command -- resets session."""
  344.         return self.docmd("rset")
  345.  
  346.     def noop(self):
  347.         """SMTP 'noop' command -- doesn't do anything :>"""
  348.         return self.docmd("noop")
  349.  
  350.     def mail(self,sender,options=[]):
  351.         """SMTP 'mail' command -- begins mail xfer session."""
  352.         optionlist = ''
  353.         if options and self.does_esmtp:
  354.             optionlist = ' ' + string.join(options, ' ')
  355.         self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender) ,optionlist))
  356.         return self.getreply()
  357.  
  358.     def rcpt(self,recip,options=[]):
  359.         """SMTP 'rcpt' command -- indicates 1 recipient for this mail."""
  360.         optionlist = ''
  361.         if options and self.does_esmtp:
  362.             optionlist = ' ' + string.join(options, ' ')
  363.         self.putcmd("rcpt","TO:%s%s" % (quoteaddr(recip),optionlist))
  364.         return self.getreply()
  365.  
  366.     def data(self,msg):
  367.         """SMTP 'DATA' command -- sends message data to server. 
  368.  
  369.         Automatically quotes lines beginning with a period per rfc821.
  370.         Raises SMTPDataError if there is an unexpected reply to the
  371.         DATA command; the return value from this method is the final
  372.         response code received when the all data is sent.
  373.         """
  374.         self.putcmd("data")
  375.         (code,repl)=self.getreply()
  376.         if self.debuglevel >0 : print "data:", (code,repl)
  377.         if code <> 354:
  378.             raise SMTPDataError(code,repl)
  379.         else:
  380.             q = quotedata(msg)
  381.             if q[-2:] != CRLF:
  382.                 q = q + CRLF
  383.             q = q + "." + CRLF
  384.             self.send(q)
  385.             (code,msg)=self.getreply()
  386.             if self.debuglevel >0 : print "data:", (code,msg)
  387.             return (code,msg)
  388.  
  389.     def verify(self, address):
  390.         """SMTP 'verify' command -- checks for address validity."""
  391.         self.putcmd("vrfy", quoteaddr(address))
  392.         return self.getreply()
  393.     # a.k.a.
  394.     vrfy=verify
  395.  
  396.     def expn(self, address):
  397.         """SMTP 'verify' command -- checks for address validity."""
  398.         self.putcmd("expn", quoteaddr(address))
  399.         return self.getreply()
  400.  
  401.     # some useful methods
  402.     def sendmail(self, from_addr, to_addrs, msg, mail_options=[],
  403.                  rcpt_options=[]): 
  404.         """This command performs an entire mail transaction. 
  405.  
  406.         The arguments are: 
  407.             - from_addr    : The address sending this mail.
  408.             - to_addrs     : A list of addresses to send this mail to.  A bare
  409.                              string will be treated as a list with 1 address.
  410.             - msg          : The message to send. 
  411.             - mail_options : List of ESMTP options (such as 8bitmime) for the
  412.                              mail command.
  413.             - rcpt_options : List of ESMTP options (such as DSN commands) for
  414.                              all the rcpt commands.
  415.  
  416.         If there has been no previous EHLO or HELO command this session, this
  417.         method tries ESMTP EHLO first.  If the server does ESMTP, message size
  418.         and each of the specified options will be passed to it.  If EHLO
  419.         fails, HELO will be tried and ESMTP options suppressed.
  420.  
  421.         This method will return normally if the mail is accepted for at least
  422.         one recipient.  It returns a dictionary, with one entry for each
  423.         recipient that was refused.  Each entry contains a tuple of the SMTP
  424.         error code and the accompanying error message sent by the server.
  425.  
  426.         This method may raise the following exceptions:
  427.  
  428.          SMTPHeloError          The server didn't reply properly to
  429.                                 the helo greeting. 
  430.          SMTPRecipientsRefused  The server rejected ALL recipients
  431.                                 (no mail was sent).
  432.          SMTPSenderRefused      The server didn't accept the from_addr.
  433.          SMTPDataError          The server replied with an unexpected
  434.                                 error code (other than a refusal of
  435.                                 a recipient).
  436.  
  437.         Note: the connection will be open even after an exception is raised.
  438.  
  439.         Example:
  440.       
  441.          >>> import smtplib
  442.          >>> s=smtplib.SMTP("localhost")
  443.          >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
  444.          >>> msg = '''
  445.          ... From: Me@my.org
  446.          ... Subject: testin'...
  447.          ...
  448.          ... This is a test '''
  449.          >>> s.sendmail("me@my.org",tolist,msg)
  450.          { "three@three.org" : ( 550 ,"User unknown" ) }
  451.          >>> s.quit()
  452.         
  453.         In the above example, the message was accepted for delivery to three
  454.         of the four addresses, and one was rejected, with the error code
  455.         550.  If all addresses are accepted, then the method will return an
  456.         empty dictionary.
  457.  
  458.         """
  459.         if self.helo_resp is None and self.ehlo_resp is None:
  460.             if not (200 <= self.ehlo()[0] <= 299):
  461.                 (code,resp) = self.helo()
  462.                 if not (200 <= code <= 299):
  463.                     raise SMTPHeloError(code, resp)
  464.         esmtp_opts = []
  465.         if self.does_esmtp:
  466.             # Hmmm? what's this? -ddm
  467.             # self.esmtp_features['7bit']=""
  468.             if self.has_extn('size'):
  469.                 esmtp_opts.append("size=" + `len(msg)`)
  470.             for option in mail_options:
  471.                 esmtp_opts.append(option)
  472.  
  473.         (code,resp) = self.mail(from_addr, esmtp_opts)
  474.         if code <> 250:
  475.             self.rset()
  476.             raise SMTPSenderRefused(code, resp, from_addr)
  477.         senderrs={}
  478.         if type(to_addrs) == types.StringType:
  479.             to_addrs = [to_addrs]
  480.         for each in to_addrs:
  481.             (code,resp)=self.rcpt(each, rcpt_options)
  482.             if (code <> 250) and (code <> 251):
  483.                 senderrs[each]=(code,resp)
  484.         if len(senderrs)==len(to_addrs):
  485.             # the server refused all our recipients
  486.             self.rset()
  487.             raise SMTPRecipientsRefused(senderrs)
  488.         (code,resp)=self.data(msg)
  489.         if code <> 250:
  490.             self.rset()
  491.             raise SMTPDataError(code, resp)
  492.         #if we got here then somebody got our mail
  493.         return senderrs         
  494.  
  495.  
  496.     def close(self):
  497.         """Close the connection to the SMTP server."""
  498.         if self.file:
  499.             self.file.close()
  500.         self.file = None
  501.         if self.sock:
  502.             self.sock.close()
  503.         self.sock = None
  504.  
  505.  
  506.     def quit(self):
  507.         """Terminate the SMTP session."""
  508.         self.docmd("quit")
  509.         self.close()
  510.  
  511.  
  512. # Test the sendmail method, which tests most of the others.
  513. # Note: This always sends to localhost.
  514. if __name__ == '__main__':
  515.     import sys, rfc822
  516.  
  517.     def prompt(prompt):
  518.         sys.stdout.write(prompt + ": ")
  519.         return string.strip(sys.stdin.readline())
  520.  
  521.     fromaddr = prompt("From")
  522.     toaddrs  = string.splitfields(prompt("To"), ',')
  523.     print "Enter message, end with ^D:"
  524.     msg = ''
  525.     while 1:
  526.         line = sys.stdin.readline()
  527.         if not line:
  528.             break
  529.         msg = msg + line
  530.     print "Message length is " + `len(msg)`
  531.  
  532.     server = SMTP('localhost')
  533.     server.set_debuglevel(1)
  534.     server.sendmail(fromaddr, toaddrs, msg)
  535.     server.quit()
  536.