PageRenderTime 60ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/python/lib/Lib/smtplib.py

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