PageRenderTime 83ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/smtplib.py

https://bitbucket.org/pwaller/pypy
Python | 848 lines | 832 code | 1 blank | 15 comment | 1 complexity | 8cdeed5fe53b795e2c19fa5df0b31144 MD5 | raw file
  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. SMTP_SSL_PORT = 465
  49. CRLF = "\r\n"
  50. OLDSTYLE_AUTH = re.compile(r"auth=(.*)", re.I)
  51. # Exception classes used by this module.
  52. class SMTPException(Exception):
  53. """Base class for all exceptions raised by this module."""
  54. class SMTPServerDisconnected(SMTPException):
  55. """Not connected to any SMTP server.
  56. This exception is raised when the server unexpectedly disconnects,
  57. or when an attempt is made to use the SMTP instance before
  58. connecting it to a server.
  59. """
  60. class SMTPResponseException(SMTPException):
  61. """Base class for all exceptions that include an SMTP error code.
  62. These exceptions are generated in some instances when the SMTP
  63. server returns an error code. The error code is stored in the
  64. `smtp_code' attribute of the error, and the `smtp_error' attribute
  65. is set to the error message.
  66. """
  67. def __init__(self, code, msg):
  68. self.smtp_code = code
  69. self.smtp_error = msg
  70. self.args = (code, msg)
  71. class SMTPSenderRefused(SMTPResponseException):
  72. """Sender address refused.
  73. In addition to the attributes set by on all SMTPResponseException
  74. exceptions, this sets `sender' to the string that the SMTP refused.
  75. """
  76. def __init__(self, code, msg, sender):
  77. self.smtp_code = code
  78. self.smtp_error = msg
  79. self.sender = sender
  80. self.args = (code, msg, sender)
  81. class SMTPRecipientsRefused(SMTPException):
  82. """All recipient addresses refused.
  83. The errors for each recipient are accessible through the attribute
  84. 'recipients', which is a dictionary of exactly the same sort as
  85. SMTP.sendmail() returns.
  86. """
  87. def __init__(self, recipients):
  88. self.recipients = recipients
  89. self.args = (recipients,)
  90. class SMTPDataError(SMTPResponseException):
  91. """The SMTP server didn't accept the data."""
  92. class SMTPConnectError(SMTPResponseException):
  93. """Error during connection establishment."""
  94. class SMTPHeloError(SMTPResponseException):
  95. """The server refused our HELO reply."""
  96. class SMTPAuthenticationError(SMTPResponseException):
  97. """Authentication error.
  98. Most probably the server didn't accept the username/password
  99. combination provided.
  100. """
  101. def quoteaddr(addr):
  102. """Quote a subset of the email addresses defined by RFC 821.
  103. Should be able to handle anything rfc822.parseaddr can handle.
  104. """
  105. m = (None, None)
  106. try:
  107. m = email.utils.parseaddr(addr)[1]
  108. except AttributeError:
  109. pass
  110. if m == (None, None): # Indicates parse failure or AttributeError
  111. # something weird here.. punt -ddm
  112. return "<%s>" % addr
  113. elif m is None:
  114. # the sender wants an empty return address
  115. return "<>"
  116. else:
  117. return "<%s>" % m
  118. def quotedata(data):
  119. """Quote data for email.
  120. Double leading '.', and change Unix newline '\\n', or Mac '\\r' into
  121. Internet CRLF end-of-line.
  122. """
  123. return re.sub(r'(?m)^\.', '..',
  124. re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data))
  125. try:
  126. import ssl
  127. except ImportError:
  128. _have_ssl = False
  129. else:
  130. class SSLFakeFile:
  131. """A fake file like object that really wraps a SSLObject.
  132. It only supports what is needed in smtplib.
  133. """
  134. def __init__(self, sslobj):
  135. self.sslobj = sslobj
  136. def readline(self):
  137. str = ""
  138. chr = None
  139. while chr != "\n":
  140. chr = self.sslobj.read(1)
  141. if not chr:
  142. break
  143. str += chr
  144. return str
  145. def close(self):
  146. pass
  147. _have_ssl = True
  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_msg = "ehlo"
  176. ehlo_resp = None
  177. does_esmtp = 0
  178. default_port = SMTP_PORT
  179. def __init__(self, host='', port=0, local_hostname=None,
  180. timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  181. """Initialize a new instance.
  182. If specified, `host' is the name of the remote host to which to
  183. connect. If specified, `port' specifies the port to which to connect.
  184. By default, smtplib.SMTP_PORT is used. An SMTPConnectError is raised
  185. if the specified `host' doesn't respond correctly. If specified,
  186. `local_hostname` is used as the FQDN of the local host. By default,
  187. the local hostname is found using socket.getfqdn().
  188. """
  189. self.timeout = timeout
  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 _get_socket(self, port, host, timeout):
  219. # This makes it simpler for SMTP_SSL to use the SMTP connect code
  220. # and just alter the socket connection bit.
  221. if self.debuglevel > 0:
  222. print>>stderr, 'connect:', (host, port)
  223. return socket.create_connection((port, host), timeout)
  224. def connect(self, host='localhost', port=0):
  225. """Connect to a host on a given port.
  226. If the hostname ends with a colon (`:') followed by a number, and
  227. there is no port specified, that suffix will be stripped off and the
  228. number interpreted as the port number to use.
  229. Note: This method is automatically invoked by __init__, if a host is
  230. specified during instantiation.
  231. """
  232. if not port and (host.find(':') == host.rfind(':')):
  233. i = host.rfind(':')
  234. if i >= 0:
  235. host, port = host[:i], host[i + 1:]
  236. try:
  237. port = int(port)
  238. except ValueError:
  239. raise socket.error, "nonnumeric port"
  240. if not port:
  241. port = self.default_port
  242. if self.debuglevel > 0:
  243. print>>stderr, 'connect:', (host, port)
  244. self.sock = self._get_socket(host, port, self.timeout)
  245. (code, msg) = self.getreply()
  246. if self.debuglevel > 0:
  247. print>>stderr, "connect:", msg
  248. return (code, msg)
  249. def send(self, str):
  250. """Send `str' to the server."""
  251. if self.debuglevel > 0:
  252. print>>stderr, 'send:', repr(str)
  253. if hasattr(self, 'sock') and self.sock:
  254. try:
  255. self.sock.sendall(str)
  256. except socket.error:
  257. self.close()
  258. raise SMTPServerDisconnected('Server not connected')
  259. else:
  260. raise SMTPServerDisconnected('please run connect() first')
  261. def putcmd(self, cmd, args=""):
  262. """Send a command to the server."""
  263. if args == "":
  264. str = '%s%s' % (cmd, CRLF)
  265. else:
  266. str = '%s %s%s' % (cmd, args, CRLF)
  267. self.send(str)
  268. def getreply(self):
  269. """Get a reply from the server.
  270. Returns a tuple consisting of:
  271. - server response code (e.g. '250', or such, if all goes well)
  272. Note: returns -1 if it can't read response code.
  273. - server response string corresponding to response code (multiline
  274. responses are converted to a single, multiline string).
  275. Raises SMTPServerDisconnected if end-of-file is reached.
  276. """
  277. resp = []
  278. if self.file is None:
  279. self.file = self.sock.makefile('rb')
  280. while 1:
  281. try:
  282. line = self.file.readline()
  283. except socket.error:
  284. line = ''
  285. if line == '':
  286. self.close()
  287. raise SMTPServerDisconnected("Connection unexpectedly closed")
  288. if self.debuglevel > 0:
  289. print>>stderr, 'reply:', repr(line)
  290. resp.append(line[4:].strip())
  291. code = line[:3]
  292. # Check that the error code is syntactically correct.
  293. # Don't attempt to read a continuation line if it is broken.
  294. try:
  295. errcode = int(code)
  296. except ValueError:
  297. errcode = -1
  298. break
  299. # Check if multiline response.
  300. if line[3:4] != "-":
  301. break
  302. errmsg = "\n".join(resp)
  303. if self.debuglevel > 0:
  304. print>>stderr, 'reply: retcode (%s); Msg: %s' % (errcode, errmsg)
  305. return errcode, errmsg
  306. def docmd(self, cmd, args=""):
  307. """Send a command, and return its response code."""
  308. self.putcmd(cmd, args)
  309. return self.getreply()
  310. # std smtp commands
  311. def helo(self, name=''):
  312. """SMTP 'helo' command.
  313. Hostname to send for this command defaults to the FQDN of the local
  314. host.
  315. """
  316. self.putcmd("helo", name or self.local_hostname)
  317. (code, msg) = self.getreply()
  318. self.helo_resp = msg
  319. return (code, msg)
  320. def ehlo(self, name=''):
  321. """ SMTP 'ehlo' command.
  322. Hostname to send for this command defaults to the FQDN of the local
  323. host.
  324. """
  325. self.esmtp_features = {}
  326. self.putcmd(self.ehlo_msg, name or self.local_hostname)
  327. (code, msg) = self.getreply()
  328. # According to RFC1869 some (badly written)
  329. # MTA's will disconnect on an ehlo. Toss an exception if
  330. # that happens -ddm
  331. if code == -1 and len(msg) == 0:
  332. self.close()
  333. raise SMTPServerDisconnected("Server not connected")
  334. self.ehlo_resp = msg
  335. if code != 250:
  336. return (code, msg)
  337. self.does_esmtp = 1
  338. #parse the ehlo response -ddm
  339. resp = self.ehlo_resp.split('\n')
  340. del resp[0]
  341. for each in resp:
  342. # To be able to communicate with as many SMTP servers as possible,
  343. # we have to take the old-style auth advertisement into account,
  344. # because:
  345. # 1) Else our SMTP feature parser gets confused.
  346. # 2) There are some servers that only advertise the auth methods we
  347. # support using the old style.
  348. auth_match = OLDSTYLE_AUTH.match(each)
  349. if auth_match:
  350. # This doesn't remove duplicates, but that's no problem
  351. self.esmtp_features["auth"] = self.esmtp_features.get("auth", "") \
  352. + " " + auth_match.groups(0)[0]
  353. continue
  354. # RFC 1869 requires a space between ehlo keyword and parameters.
  355. # It's actually stricter, in that only spaces are allowed between
  356. # parameters, but were not going to check for that here. Note
  357. # that the space isn't present if there are no parameters.
  358. m = re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*) ?', each)
  359. if m:
  360. feature = m.group("feature").lower()
  361. params = m.string[m.end("feature"):].strip()
  362. if feature == "auth":
  363. self.esmtp_features[feature] = self.esmtp_features.get(feature, "") \
  364. + " " + params
  365. else:
  366. self.esmtp_features[feature] = params
  367. return (code, msg)
  368. def has_extn(self, opt):
  369. """Does the server support a given SMTP service extension?"""
  370. return opt.lower() in self.esmtp_features
  371. def help(self, args=''):
  372. """SMTP 'help' command.
  373. Returns help text from server."""
  374. self.putcmd("help", args)
  375. return self.getreply()[1]
  376. def rset(self):
  377. """SMTP 'rset' command -- resets session."""
  378. return self.docmd("rset")
  379. def noop(self):
  380. """SMTP 'noop' command -- doesn't do anything :>"""
  381. return self.docmd("noop")
  382. def mail(self, sender, options=[]):
  383. """SMTP 'mail' command -- begins mail xfer session."""
  384. optionlist = ''
  385. if options and self.does_esmtp:
  386. optionlist = ' ' + ' '.join(options)
  387. self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender), optionlist))
  388. return self.getreply()
  389. def rcpt(self, recip, options=[]):
  390. """SMTP 'rcpt' command -- indicates 1 recipient for this mail."""
  391. optionlist = ''
  392. if options and self.does_esmtp:
  393. optionlist = ' ' + ' '.join(options)
  394. self.putcmd("rcpt", "TO:%s%s" % (quoteaddr(recip), optionlist))
  395. return self.getreply()
  396. def data(self, msg):
  397. """SMTP 'DATA' command -- sends message data to server.
  398. Automatically quotes lines beginning with a period per rfc821.
  399. Raises SMTPDataError if there is an unexpected reply to the
  400. DATA command; the return value from this method is the final
  401. response code received when the all data is sent.
  402. """
  403. self.putcmd("data")
  404. (code, repl) = self.getreply()
  405. if self.debuglevel > 0:
  406. 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:
  417. print>>stderr, "data:", (code, msg)
  418. return (code, msg)
  419. def verify(self, address):
  420. """SMTP 'verify' command -- checks for address validity."""
  421. self.putcmd("vrfy", quoteaddr(address))
  422. return self.getreply()
  423. # a.k.a.
  424. vrfy = verify
  425. def expn(self, address):
  426. """SMTP 'expn' command -- expands a mailing list."""
  427. self.putcmd("expn", quoteaddr(address))
  428. return self.getreply()
  429. # some useful methods
  430. def ehlo_or_helo_if_needed(self):
  431. """Call self.ehlo() and/or self.helo() if needed.
  432. If there has been no previous EHLO or HELO command this session, this
  433. method tries ESMTP EHLO first.
  434. This method may raise the following exceptions:
  435. SMTPHeloError The server didn't reply properly to
  436. the helo greeting.
  437. """
  438. if self.helo_resp is None and self.ehlo_resp is None:
  439. if not (200 <= self.ehlo()[0] <= 299):
  440. (code, resp) = self.helo()
  441. if not (200 <= code <= 299):
  442. raise SMTPHeloError(code, resp)
  443. def login(self, user, password):
  444. """Log in on an SMTP server that requires authentication.
  445. The arguments are:
  446. - user: The user name to authenticate with.
  447. - password: The password for the authentication.
  448. If there has been no previous EHLO or HELO command this session, this
  449. method tries ESMTP EHLO first.
  450. This method will return normally if the authentication was successful.
  451. This method may raise the following exceptions:
  452. SMTPHeloError The server didn't reply properly to
  453. the helo greeting.
  454. SMTPAuthenticationError The server didn't accept the username/
  455. password combination.
  456. SMTPException No suitable authentication method was
  457. found.
  458. """
  459. def encode_cram_md5(challenge, user, password):
  460. challenge = base64.decodestring(challenge)
  461. response = user + " " + hmac.HMAC(password, challenge).hexdigest()
  462. return encode_base64(response, eol="")
  463. def encode_plain(user, password):
  464. return encode_base64("\0%s\0%s" % (user, password), eol="")
  465. AUTH_PLAIN = "PLAIN"
  466. AUTH_CRAM_MD5 = "CRAM-MD5"
  467. AUTH_LOGIN = "LOGIN"
  468. self.ehlo_or_helo_if_needed()
  469. if not self.has_extn("auth"):
  470. raise SMTPException("SMTP AUTH extension not supported by server.")
  471. # Authentication methods the server supports:
  472. authlist = self.esmtp_features["auth"].split()
  473. # List of authentication methods we support: from preferred to
  474. # less preferred methods. Except for the purpose of testing the weaker
  475. # ones, we prefer stronger methods like CRAM-MD5:
  476. preferred_auths = [AUTH_CRAM_MD5, AUTH_PLAIN, AUTH_LOGIN]
  477. # Determine the authentication method we'll use
  478. authmethod = None
  479. for method in preferred_auths:
  480. if method in authlist:
  481. authmethod = method
  482. break
  483. if authmethod == AUTH_CRAM_MD5:
  484. (code, resp) = self.docmd("AUTH", AUTH_CRAM_MD5)
  485. if code == 503:
  486. # 503 == 'Error: already authenticated'
  487. return (code, resp)
  488. (code, resp) = self.docmd(encode_cram_md5(resp, user, password))
  489. elif authmethod == AUTH_PLAIN:
  490. (code, resp) = self.docmd("AUTH",
  491. AUTH_PLAIN + " " + encode_plain(user, password))
  492. elif authmethod == AUTH_LOGIN:
  493. (code, resp) = self.docmd("AUTH",
  494. "%s %s" % (AUTH_LOGIN, encode_base64(user, eol="")))
  495. if code != 334:
  496. raise SMTPAuthenticationError(code, resp)
  497. (code, resp) = self.docmd(encode_base64(password, eol=""))
  498. elif authmethod is None:
  499. raise SMTPException("No suitable authentication method found.")
  500. if code not in (235, 503):
  501. # 235 == 'Authentication successful'
  502. # 503 == 'Error: already authenticated'
  503. raise SMTPAuthenticationError(code, resp)
  504. return (code, resp)
  505. def starttls(self, keyfile=None, certfile=None):
  506. """Puts the connection to the SMTP server into TLS mode.
  507. If there has been no previous EHLO or HELO command this session, this
  508. method tries ESMTP EHLO first.
  509. If the server supports TLS, this will encrypt the rest of the SMTP
  510. session. If you provide the keyfile and certfile parameters,
  511. the identity of the SMTP server and client can be checked. This,
  512. however, depends on whether the socket module really checks the
  513. certificates.
  514. This method may raise the following exceptions:
  515. SMTPHeloError The server didn't reply properly to
  516. the helo greeting.
  517. """
  518. self.ehlo_or_helo_if_needed()
  519. if not self.has_extn("starttls"):
  520. raise SMTPException("STARTTLS extension not supported by server.")
  521. (resp, reply) = self.docmd("STARTTLS")
  522. if resp == 220:
  523. if not _have_ssl:
  524. raise RuntimeError("No SSL support included in this Python")
  525. self.sock = ssl.wrap_socket(self.sock, keyfile, certfile)
  526. self.file = SSLFakeFile(self.sock)
  527. # RFC 3207:
  528. # The client MUST discard any knowledge obtained from
  529. # the server, such as the list of SMTP service extensions,
  530. # which was not obtained from the TLS negotiation itself.
  531. self.helo_resp = None
  532. self.ehlo_resp = None
  533. self.esmtp_features = {}
  534. self.does_esmtp = 0
  535. return (resp, reply)
  536. def sendmail(self, from_addr, to_addrs, msg, mail_options=[],
  537. rcpt_options=[]):
  538. """This command performs an entire mail transaction.
  539. The arguments are:
  540. - from_addr : The address sending this mail.
  541. - to_addrs : A list of addresses to send this mail to. A bare
  542. string will be treated as a list with 1 address.
  543. - msg : The message to send.
  544. - mail_options : List of ESMTP options (such as 8bitmime) for the
  545. mail command.
  546. - rcpt_options : List of ESMTP options (such as DSN commands) for
  547. all the rcpt commands.
  548. If there has been no previous EHLO or HELO command this session, this
  549. method tries ESMTP EHLO first. If the server does ESMTP, message size
  550. and each of the specified options will be passed to it. If EHLO
  551. fails, HELO will be tried and ESMTP options suppressed.
  552. This method will return normally if the mail is accepted for at least
  553. one recipient. It returns a dictionary, with one entry for each
  554. recipient that was refused. Each entry contains a tuple of the SMTP
  555. error code and the accompanying error message sent by the server.
  556. This method may raise the following exceptions:
  557. SMTPHeloError The server didn't reply properly to
  558. the helo greeting.
  559. SMTPRecipientsRefused The server rejected ALL recipients
  560. (no mail was sent).
  561. SMTPSenderRefused The server didn't accept the from_addr.
  562. SMTPDataError The server replied with an unexpected
  563. error code (other than a refusal of
  564. a recipient).
  565. Note: the connection will be open even after an exception is raised.
  566. Example:
  567. >>> import smtplib
  568. >>> s=smtplib.SMTP("localhost")
  569. >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
  570. >>> msg = '''\\
  571. ... From: Me@my.org
  572. ... Subject: testin'...
  573. ...
  574. ... This is a test '''
  575. >>> s.sendmail("me@my.org",tolist,msg)
  576. { "three@three.org" : ( 550 ,"User unknown" ) }
  577. >>> s.quit()
  578. In the above example, the message was accepted for delivery to three
  579. of the four addresses, and one was rejected, with the error code
  580. 550. If all addresses are accepted, then the method will return an
  581. empty dictionary.
  582. """
  583. self.ehlo_or_helo_if_needed()
  584. esmtp_opts = []
  585. if self.does_esmtp:
  586. # Hmmm? what's this? -ddm
  587. # self.esmtp_features['7bit']=""
  588. if self.has_extn('size'):
  589. esmtp_opts.append("size=%d" % len(msg))
  590. for option in mail_options:
  591. esmtp_opts.append(option)
  592. (code, resp) = self.mail(from_addr, esmtp_opts)
  593. if code != 250:
  594. self.rset()
  595. raise SMTPSenderRefused(code, resp, from_addr)
  596. senderrs = {}
  597. if isinstance(to_addrs, basestring):
  598. to_addrs = [to_addrs]
  599. for each in to_addrs:
  600. (code, resp) = self.rcpt(each, rcpt_options)
  601. if (code != 250) and (code != 251):
  602. senderrs[each] = (code, resp)
  603. if len(senderrs) == len(to_addrs):
  604. # the server refused all our recipients
  605. self.rset()
  606. raise SMTPRecipientsRefused(senderrs)
  607. (code, resp) = self.data(msg)
  608. if code != 250:
  609. self.rset()
  610. raise SMTPDataError(code, resp)
  611. #if we got here then somebody got our mail
  612. return senderrs
  613. def close(self):
  614. """Close the connection to the SMTP server."""
  615. if self.file:
  616. self.file.close()
  617. self.file = None
  618. if self.sock:
  619. self.sock.close()
  620. self.sock = None
  621. def quit(self):
  622. """Terminate the SMTP session."""
  623. res = self.docmd("quit")
  624. self.close()
  625. return res
  626. if _have_ssl:
  627. class SMTP_SSL(SMTP):
  628. """ This is a subclass derived from SMTP that connects over an SSL encrypted
  629. socket (to use this class you need a socket module that was compiled with SSL
  630. support). If host is not specified, '' (the local host) is used. If port is
  631. omitted, the standard SMTP-over-SSL port (465) is used. keyfile and certfile
  632. are also optional - they can contain a PEM formatted private key and
  633. certificate chain file for the SSL connection.
  634. """
  635. default_port = SMTP_SSL_PORT
  636. def __init__(self, host='', port=0, local_hostname=None,
  637. keyfile=None, certfile=None,
  638. timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  639. self.keyfile = keyfile
  640. self.certfile = certfile
  641. SMTP.__init__(self, host, port, local_hostname, timeout)
  642. def _get_socket(self, host, port, timeout):
  643. if self.debuglevel > 0:
  644. print>>stderr, 'connect:', (host, port)
  645. new_socket = socket.create_connection((host, port), timeout)
  646. new_socket = ssl.wrap_socket(new_socket, self.keyfile, self.certfile)
  647. self.file = SSLFakeFile(new_socket)
  648. return new_socket
  649. __all__.append("SMTP_SSL")
  650. #
  651. # LMTP extension
  652. #
  653. LMTP_PORT = 2003
  654. class LMTP(SMTP):
  655. """LMTP - Local Mail Transfer Protocol
  656. The LMTP protocol, which is very similar to ESMTP, is heavily based
  657. on the standard SMTP client. It's common to use Unix sockets for LMTP,
  658. so our connect() method must support that as well as a regular
  659. host:port server. To specify a Unix socket, you must use an absolute
  660. path as the host, starting with a '/'.
  661. Authentication is supported, using the regular SMTP mechanism. When
  662. using a Unix socket, LMTP generally don't support or require any
  663. authentication, but your mileage might vary."""
  664. ehlo_msg = "lhlo"
  665. def __init__(self, host='', port=LMTP_PORT, local_hostname=None):
  666. """Initialize a new instance."""
  667. SMTP.__init__(self, host, port, local_hostname)
  668. def connect(self, host='localhost', port=0):
  669. """Connect to the LMTP daemon, on either a Unix or a TCP socket."""
  670. if host[0] != '/':
  671. return SMTP.connect(self, host, port)
  672. # Handle Unix-domain sockets.
  673. try:
  674. self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  675. self.sock.connect(host)
  676. except socket.error, msg:
  677. if self.debuglevel > 0:
  678. print>>stderr, 'connect fail:', host
  679. if self.sock:
  680. self.sock.close()
  681. self.sock = None
  682. raise socket.error, msg
  683. (code, msg) = self.getreply()
  684. if self.debuglevel > 0:
  685. print>>stderr, "connect:", msg
  686. return (code, msg)
  687. # Test the sendmail method, which tests most of the others.
  688. # Note: This always sends to localhost.
  689. if __name__ == '__main__':
  690. import sys
  691. def prompt(prompt):
  692. sys.stdout.write(prompt + ": ")
  693. return sys.stdin.readline().strip()
  694. fromaddr = prompt("From")
  695. toaddrs = prompt("To").split(',')
  696. print "Enter message, end with ^D:"
  697. msg = ''
  698. while 1:
  699. line = sys.stdin.readline()
  700. if not line:
  701. break
  702. msg = msg + line
  703. print "Message length is %d" % len(msg)
  704. server = SMTP('localhost')
  705. server.set_debuglevel(1)
  706. server.sendmail(fromaddr, toaddrs, msg)
  707. server.quit()