PageRenderTime 57ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/lib-python/2.7/smtplib.py

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