PageRenderTime 98ms CodeModel.GetById 44ms RepoModel.GetById 1ms app.codeStats 0ms

/Backend/lib/smtplib.boa

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