smtplib.py 31 KB

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