PageRenderTime 53ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/test/test_smtplib.py

https://bitbucket.org/mirror/cpython/
Python | 1290 lines | 1138 code | 86 blank | 66 comment | 40 complexity | cac023374e061ad2d888ad7088ec6a0f MD5 | raw file
Possible License(s): Unlicense, 0BSD, BSD-3-Clause
  1. import asyncore
  2. import base64
  3. import email.mime.text
  4. from email.message import EmailMessage
  5. from email.base64mime import body_encode as encode_base64
  6. import email.utils
  7. import hmac
  8. import socket
  9. import smtpd
  10. import smtplib
  11. import io
  12. import re
  13. import sys
  14. import time
  15. import select
  16. import errno
  17. import textwrap
  18. import unittest
  19. from test import support, mock_socket
  20. try:
  21. import threading
  22. except ImportError:
  23. threading = None
  24. HOST = support.HOST
  25. if sys.platform == 'darwin':
  26. # select.poll returns a select.POLLHUP at the end of the tests
  27. # on darwin, so just ignore it
  28. def handle_expt(self):
  29. pass
  30. smtpd.SMTPChannel.handle_expt = handle_expt
  31. def server(evt, buf, serv):
  32. serv.listen()
  33. evt.set()
  34. try:
  35. conn, addr = serv.accept()
  36. except socket.timeout:
  37. pass
  38. else:
  39. n = 500
  40. while buf and n > 0:
  41. r, w, e = select.select([], [conn], [])
  42. if w:
  43. sent = conn.send(buf)
  44. buf = buf[sent:]
  45. n -= 1
  46. conn.close()
  47. finally:
  48. serv.close()
  49. evt.set()
  50. class GeneralTests(unittest.TestCase):
  51. def setUp(self):
  52. smtplib.socket = mock_socket
  53. self.port = 25
  54. def tearDown(self):
  55. smtplib.socket = socket
  56. # This method is no longer used but is retained for backward compatibility,
  57. # so test to make sure it still works.
  58. def testQuoteData(self):
  59. teststr = "abc\n.jkl\rfoo\r\n..blue"
  60. expected = "abc\r\n..jkl\r\nfoo\r\n...blue"
  61. self.assertEqual(expected, smtplib.quotedata(teststr))
  62. def testBasic1(self):
  63. mock_socket.reply_with(b"220 Hola mundo")
  64. # connects
  65. smtp = smtplib.SMTP(HOST, self.port)
  66. smtp.close()
  67. def testSourceAddress(self):
  68. mock_socket.reply_with(b"220 Hola mundo")
  69. # connects
  70. smtp = smtplib.SMTP(HOST, self.port,
  71. source_address=('127.0.0.1',19876))
  72. self.assertEqual(smtp.source_address, ('127.0.0.1', 19876))
  73. smtp.close()
  74. def testBasic2(self):
  75. mock_socket.reply_with(b"220 Hola mundo")
  76. # connects, include port in host name
  77. smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
  78. smtp.close()
  79. def testLocalHostName(self):
  80. mock_socket.reply_with(b"220 Hola mundo")
  81. # check that supplied local_hostname is used
  82. smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
  83. self.assertEqual(smtp.local_hostname, "testhost")
  84. smtp.close()
  85. def testTimeoutDefault(self):
  86. mock_socket.reply_with(b"220 Hola mundo")
  87. self.assertIsNone(mock_socket.getdefaulttimeout())
  88. mock_socket.setdefaulttimeout(30)
  89. self.assertEqual(mock_socket.getdefaulttimeout(), 30)
  90. try:
  91. smtp = smtplib.SMTP(HOST, self.port)
  92. finally:
  93. mock_socket.setdefaulttimeout(None)
  94. self.assertEqual(smtp.sock.gettimeout(), 30)
  95. smtp.close()
  96. def testTimeoutNone(self):
  97. mock_socket.reply_with(b"220 Hola mundo")
  98. self.assertIsNone(socket.getdefaulttimeout())
  99. socket.setdefaulttimeout(30)
  100. try:
  101. smtp = smtplib.SMTP(HOST, self.port, timeout=None)
  102. finally:
  103. socket.setdefaulttimeout(None)
  104. self.assertIsNone(smtp.sock.gettimeout())
  105. smtp.close()
  106. def testTimeoutValue(self):
  107. mock_socket.reply_with(b"220 Hola mundo")
  108. smtp = smtplib.SMTP(HOST, self.port, timeout=30)
  109. self.assertEqual(smtp.sock.gettimeout(), 30)
  110. smtp.close()
  111. def test_debuglevel(self):
  112. mock_socket.reply_with(b"220 Hello world")
  113. smtp = smtplib.SMTP()
  114. smtp.set_debuglevel(1)
  115. with support.captured_stderr() as stderr:
  116. smtp.connect(HOST, self.port)
  117. smtp.close()
  118. expected = re.compile(r"^connect:", re.MULTILINE)
  119. self.assertRegex(stderr.getvalue(), expected)
  120. def test_debuglevel_2(self):
  121. mock_socket.reply_with(b"220 Hello world")
  122. smtp = smtplib.SMTP()
  123. smtp.set_debuglevel(2)
  124. with support.captured_stderr() as stderr:
  125. smtp.connect(HOST, self.port)
  126. smtp.close()
  127. expected = re.compile(r"^\d{2}:\d{2}:\d{2}\.\d{6} connect: ",
  128. re.MULTILINE)
  129. self.assertRegex(stderr.getvalue(), expected)
  130. # Test server thread using the specified SMTP server class
  131. def debugging_server(serv, serv_evt, client_evt):
  132. serv_evt.set()
  133. try:
  134. if hasattr(select, 'poll'):
  135. poll_fun = asyncore.poll2
  136. else:
  137. poll_fun = asyncore.poll
  138. n = 1000
  139. while asyncore.socket_map and n > 0:
  140. poll_fun(0.01, asyncore.socket_map)
  141. # when the client conversation is finished, it will
  142. # set client_evt, and it's then ok to kill the server
  143. if client_evt.is_set():
  144. serv.close()
  145. break
  146. n -= 1
  147. except socket.timeout:
  148. pass
  149. finally:
  150. if not client_evt.is_set():
  151. # allow some time for the client to read the result
  152. time.sleep(0.5)
  153. serv.close()
  154. asyncore.close_all()
  155. serv_evt.set()
  156. MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
  157. MSG_END = '------------ END MESSAGE ------------\n'
  158. # NOTE: Some SMTP objects in the tests below are created with a non-default
  159. # local_hostname argument to the constructor, since (on some systems) the FQDN
  160. # lookup caused by the default local_hostname sometimes takes so long that the
  161. # test server times out, causing the test to fail.
  162. # Test behavior of smtpd.DebuggingServer
  163. @unittest.skipUnless(threading, 'Threading required for this test.')
  164. class DebuggingServerTests(unittest.TestCase):
  165. maxDiff = None
  166. def setUp(self):
  167. self.real_getfqdn = socket.getfqdn
  168. socket.getfqdn = mock_socket.getfqdn
  169. # temporarily replace sys.stdout to capture DebuggingServer output
  170. self.old_stdout = sys.stdout
  171. self.output = io.StringIO()
  172. sys.stdout = self.output
  173. self.serv_evt = threading.Event()
  174. self.client_evt = threading.Event()
  175. # Capture SMTPChannel debug output
  176. self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
  177. smtpd.DEBUGSTREAM = io.StringIO()
  178. # Pick a random unused port by passing 0 for the port number
  179. self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1),
  180. decode_data=True)
  181. # Keep a note of what port was assigned
  182. self.port = self.serv.socket.getsockname()[1]
  183. serv_args = (self.serv, self.serv_evt, self.client_evt)
  184. self.thread = threading.Thread(target=debugging_server, args=serv_args)
  185. self.thread.start()
  186. # wait until server thread has assigned a port number
  187. self.serv_evt.wait()
  188. self.serv_evt.clear()
  189. def tearDown(self):
  190. socket.getfqdn = self.real_getfqdn
  191. # indicate that the client is finished
  192. self.client_evt.set()
  193. # wait for the server thread to terminate
  194. self.serv_evt.wait()
  195. self.thread.join()
  196. # restore sys.stdout
  197. sys.stdout = self.old_stdout
  198. # restore DEBUGSTREAM
  199. smtpd.DEBUGSTREAM.close()
  200. smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
  201. def testBasic(self):
  202. # connect
  203. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  204. smtp.quit()
  205. def testSourceAddress(self):
  206. # connect
  207. port = support.find_unused_port()
  208. try:
  209. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
  210. timeout=3, source_address=('127.0.0.1', port))
  211. self.assertEqual(smtp.source_address, ('127.0.0.1', port))
  212. self.assertEqual(smtp.local_hostname, 'localhost')
  213. smtp.quit()
  214. except OSError as e:
  215. if e.errno == errno.EADDRINUSE:
  216. self.skipTest("couldn't bind to port %d" % port)
  217. raise
  218. def testNOOP(self):
  219. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  220. expected = (250, b'OK')
  221. self.assertEqual(smtp.noop(), expected)
  222. smtp.quit()
  223. def testRSET(self):
  224. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  225. expected = (250, b'OK')
  226. self.assertEqual(smtp.rset(), expected)
  227. smtp.quit()
  228. def testELHO(self):
  229. # EHLO isn't implemented in DebuggingServer
  230. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  231. expected = (250, b'\nSIZE 33554432\nHELP')
  232. self.assertEqual(smtp.ehlo(), expected)
  233. smtp.quit()
  234. def testEXPNNotImplemented(self):
  235. # EXPN isn't implemented in DebuggingServer
  236. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  237. expected = (502, b'EXPN not implemented')
  238. smtp.putcmd('EXPN')
  239. self.assertEqual(smtp.getreply(), expected)
  240. smtp.quit()
  241. def testVRFY(self):
  242. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  243. expected = (252, b'Cannot VRFY user, but will accept message ' + \
  244. b'and attempt delivery')
  245. self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
  246. self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
  247. smtp.quit()
  248. def testSecondHELO(self):
  249. # check that a second HELO returns a message that it's a duplicate
  250. # (this behavior is specific to smtpd.SMTPChannel)
  251. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  252. smtp.helo()
  253. expected = (503, b'Duplicate HELO/EHLO')
  254. self.assertEqual(smtp.helo(), expected)
  255. smtp.quit()
  256. def testHELP(self):
  257. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  258. self.assertEqual(smtp.help(), b'Supported commands: EHLO HELO MAIL ' + \
  259. b'RCPT DATA RSET NOOP QUIT VRFY')
  260. smtp.quit()
  261. def testSend(self):
  262. # connect and send mail
  263. m = 'A test message'
  264. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  265. smtp.sendmail('John', 'Sally', m)
  266. # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
  267. # in asyncore. This sleep might help, but should really be fixed
  268. # properly by using an Event variable.
  269. time.sleep(0.01)
  270. smtp.quit()
  271. self.client_evt.set()
  272. self.serv_evt.wait()
  273. self.output.flush()
  274. mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
  275. self.assertEqual(self.output.getvalue(), mexpect)
  276. def testSendBinary(self):
  277. m = b'A test message'
  278. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  279. smtp.sendmail('John', 'Sally', m)
  280. # XXX (see comment in testSend)
  281. time.sleep(0.01)
  282. smtp.quit()
  283. self.client_evt.set()
  284. self.serv_evt.wait()
  285. self.output.flush()
  286. mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
  287. self.assertEqual(self.output.getvalue(), mexpect)
  288. def testSendNeedingDotQuote(self):
  289. # Issue 12283
  290. m = '.A test\n.mes.sage.'
  291. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  292. smtp.sendmail('John', 'Sally', m)
  293. # XXX (see comment in testSend)
  294. time.sleep(0.01)
  295. smtp.quit()
  296. self.client_evt.set()
  297. self.serv_evt.wait()
  298. self.output.flush()
  299. mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
  300. self.assertEqual(self.output.getvalue(), mexpect)
  301. def testSendNullSender(self):
  302. m = 'A test message'
  303. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  304. smtp.sendmail('<>', 'Sally', m)
  305. # XXX (see comment in testSend)
  306. time.sleep(0.01)
  307. smtp.quit()
  308. self.client_evt.set()
  309. self.serv_evt.wait()
  310. self.output.flush()
  311. mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
  312. self.assertEqual(self.output.getvalue(), mexpect)
  313. debugout = smtpd.DEBUGSTREAM.getvalue()
  314. sender = re.compile("^sender: <>$", re.MULTILINE)
  315. self.assertRegex(debugout, sender)
  316. def testSendMessage(self):
  317. m = email.mime.text.MIMEText('A test message')
  318. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  319. smtp.send_message(m, from_addr='John', to_addrs='Sally')
  320. # XXX (see comment in testSend)
  321. time.sleep(0.01)
  322. smtp.quit()
  323. self.client_evt.set()
  324. self.serv_evt.wait()
  325. self.output.flush()
  326. # Add the X-Peer header that DebuggingServer adds
  327. m['X-Peer'] = socket.gethostbyname('localhost')
  328. mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
  329. self.assertEqual(self.output.getvalue(), mexpect)
  330. def testSendMessageWithAddresses(self):
  331. m = email.mime.text.MIMEText('A test message')
  332. m['From'] = 'foo@bar.com'
  333. m['To'] = 'John'
  334. m['CC'] = 'Sally, Fred'
  335. m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
  336. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  337. smtp.send_message(m)
  338. # XXX (see comment in testSend)
  339. time.sleep(0.01)
  340. smtp.quit()
  341. # make sure the Bcc header is still in the message.
  342. self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
  343. '<warped@silly.walks.com>')
  344. self.client_evt.set()
  345. self.serv_evt.wait()
  346. self.output.flush()
  347. # Add the X-Peer header that DebuggingServer adds
  348. m['X-Peer'] = socket.gethostbyname('localhost')
  349. # The Bcc header should not be transmitted.
  350. del m['Bcc']
  351. mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
  352. self.assertEqual(self.output.getvalue(), mexpect)
  353. debugout = smtpd.DEBUGSTREAM.getvalue()
  354. sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
  355. self.assertRegex(debugout, sender)
  356. for addr in ('John', 'Sally', 'Fred', 'root@localhost',
  357. 'warped@silly.walks.com'):
  358. to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
  359. re.MULTILINE)
  360. self.assertRegex(debugout, to_addr)
  361. def testSendMessageWithSomeAddresses(self):
  362. # Make sure nothing breaks if not all of the three 'to' headers exist
  363. m = email.mime.text.MIMEText('A test message')
  364. m['From'] = 'foo@bar.com'
  365. m['To'] = 'John, Dinsdale'
  366. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  367. smtp.send_message(m)
  368. # XXX (see comment in testSend)
  369. time.sleep(0.01)
  370. smtp.quit()
  371. self.client_evt.set()
  372. self.serv_evt.wait()
  373. self.output.flush()
  374. # Add the X-Peer header that DebuggingServer adds
  375. m['X-Peer'] = socket.gethostbyname('localhost')
  376. mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
  377. self.assertEqual(self.output.getvalue(), mexpect)
  378. debugout = smtpd.DEBUGSTREAM.getvalue()
  379. sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
  380. self.assertRegex(debugout, sender)
  381. for addr in ('John', 'Dinsdale'):
  382. to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
  383. re.MULTILINE)
  384. self.assertRegex(debugout, to_addr)
  385. def testSendMessageWithSpecifiedAddresses(self):
  386. # Make sure addresses specified in call override those in message.
  387. m = email.mime.text.MIMEText('A test message')
  388. m['From'] = 'foo@bar.com'
  389. m['To'] = 'John, Dinsdale'
  390. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  391. smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
  392. # XXX (see comment in testSend)
  393. time.sleep(0.01)
  394. smtp.quit()
  395. self.client_evt.set()
  396. self.serv_evt.wait()
  397. self.output.flush()
  398. # Add the X-Peer header that DebuggingServer adds
  399. m['X-Peer'] = socket.gethostbyname('localhost')
  400. mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
  401. self.assertEqual(self.output.getvalue(), mexpect)
  402. debugout = smtpd.DEBUGSTREAM.getvalue()
  403. sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
  404. self.assertRegex(debugout, sender)
  405. for addr in ('John', 'Dinsdale'):
  406. to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
  407. re.MULTILINE)
  408. self.assertNotRegex(debugout, to_addr)
  409. recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
  410. self.assertRegex(debugout, recip)
  411. def testSendMessageWithMultipleFrom(self):
  412. # Sender overrides To
  413. m = email.mime.text.MIMEText('A test message')
  414. m['From'] = 'Bernard, Bianca'
  415. m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com'
  416. m['To'] = 'John, Dinsdale'
  417. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  418. smtp.send_message(m)
  419. # XXX (see comment in testSend)
  420. time.sleep(0.01)
  421. smtp.quit()
  422. self.client_evt.set()
  423. self.serv_evt.wait()
  424. self.output.flush()
  425. # Add the X-Peer header that DebuggingServer adds
  426. m['X-Peer'] = socket.gethostbyname('localhost')
  427. mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
  428. self.assertEqual(self.output.getvalue(), mexpect)
  429. debugout = smtpd.DEBUGSTREAM.getvalue()
  430. sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
  431. self.assertRegex(debugout, sender)
  432. for addr in ('John', 'Dinsdale'):
  433. to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
  434. re.MULTILINE)
  435. self.assertRegex(debugout, to_addr)
  436. def testSendMessageResent(self):
  437. m = email.mime.text.MIMEText('A test message')
  438. m['From'] = 'foo@bar.com'
  439. m['To'] = 'John'
  440. m['CC'] = 'Sally, Fred'
  441. m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
  442. m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
  443. m['Resent-From'] = 'holy@grail.net'
  444. m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
  445. m['Resent-Bcc'] = 'doe@losthope.net'
  446. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  447. smtp.send_message(m)
  448. # XXX (see comment in testSend)
  449. time.sleep(0.01)
  450. smtp.quit()
  451. self.client_evt.set()
  452. self.serv_evt.wait()
  453. self.output.flush()
  454. # The Resent-Bcc headers are deleted before serialization.
  455. del m['Bcc']
  456. del m['Resent-Bcc']
  457. # Add the X-Peer header that DebuggingServer adds
  458. m['X-Peer'] = socket.gethostbyname('localhost')
  459. mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
  460. self.assertEqual(self.output.getvalue(), mexpect)
  461. debugout = smtpd.DEBUGSTREAM.getvalue()
  462. sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
  463. self.assertRegex(debugout, sender)
  464. for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
  465. to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
  466. re.MULTILINE)
  467. self.assertRegex(debugout, to_addr)
  468. def testSendMessageMultipleResentRaises(self):
  469. m = email.mime.text.MIMEText('A test message')
  470. m['From'] = 'foo@bar.com'
  471. m['To'] = 'John'
  472. m['CC'] = 'Sally, Fred'
  473. m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
  474. m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
  475. m['Resent-From'] = 'holy@grail.net'
  476. m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
  477. m['Resent-Bcc'] = 'doe@losthope.net'
  478. m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
  479. m['Resent-To'] = 'holy@grail.net'
  480. m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
  481. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  482. with self.assertRaises(ValueError):
  483. smtp.send_message(m)
  484. smtp.close()
  485. class NonConnectingTests(unittest.TestCase):
  486. def testNotConnected(self):
  487. # Test various operations on an unconnected SMTP object that
  488. # should raise exceptions (at present the attempt in SMTP.send
  489. # to reference the nonexistent 'sock' attribute of the SMTP object
  490. # causes an AttributeError)
  491. smtp = smtplib.SMTP()
  492. self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
  493. self.assertRaises(smtplib.SMTPServerDisconnected,
  494. smtp.send, 'test msg')
  495. def testNonnumericPort(self):
  496. # check that non-numeric port raises OSError
  497. self.assertRaises(OSError, smtplib.SMTP,
  498. "localhost", "bogus")
  499. self.assertRaises(OSError, smtplib.SMTP,
  500. "localhost:bogus")
  501. # test response of client to a non-successful HELO message
  502. @unittest.skipUnless(threading, 'Threading required for this test.')
  503. class BadHELOServerTests(unittest.TestCase):
  504. def setUp(self):
  505. smtplib.socket = mock_socket
  506. mock_socket.reply_with(b"199 no hello for you!")
  507. self.old_stdout = sys.stdout
  508. self.output = io.StringIO()
  509. sys.stdout = self.output
  510. self.port = 25
  511. def tearDown(self):
  512. smtplib.socket = socket
  513. sys.stdout = self.old_stdout
  514. def testFailingHELO(self):
  515. self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
  516. HOST, self.port, 'localhost', 3)
  517. @unittest.skipUnless(threading, 'Threading required for this test.')
  518. class TooLongLineTests(unittest.TestCase):
  519. respdata = b'250 OK' + (b'.' * smtplib._MAXLINE * 2) + b'\n'
  520. def setUp(self):
  521. self.old_stdout = sys.stdout
  522. self.output = io.StringIO()
  523. sys.stdout = self.output
  524. self.evt = threading.Event()
  525. self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  526. self.sock.settimeout(15)
  527. self.port = support.bind_port(self.sock)
  528. servargs = (self.evt, self.respdata, self.sock)
  529. threading.Thread(target=server, args=servargs).start()
  530. self.evt.wait()
  531. self.evt.clear()
  532. def tearDown(self):
  533. self.evt.wait()
  534. sys.stdout = self.old_stdout
  535. def testLineTooLong(self):
  536. self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
  537. HOST, self.port, 'localhost', 3)
  538. sim_users = {'Mr.A@somewhere.com':'John A',
  539. 'Ms.B@xn--fo-fka.com':'Sally B',
  540. 'Mrs.C@somewhereesle.com':'Ruth C',
  541. }
  542. sim_auth = ('Mr.A@somewhere.com', 'somepassword')
  543. sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
  544. 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
  545. sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
  546. 'list-2':['Ms.B@xn--fo-fka.com',],
  547. }
  548. # Simulated SMTP channel & server
  549. class ResponseException(Exception): pass
  550. class SimSMTPChannel(smtpd.SMTPChannel):
  551. quit_response = None
  552. mail_response = None
  553. rcpt_response = None
  554. data_response = None
  555. rcpt_count = 0
  556. rset_count = 0
  557. disconnect = 0
  558. AUTH = 99 # Add protocol state to enable auth testing.
  559. authenticated_user = None
  560. def __init__(self, extra_features, *args, **kw):
  561. self._extrafeatures = ''.join(
  562. [ "250-{0}\r\n".format(x) for x in extra_features ])
  563. super(SimSMTPChannel, self).__init__(*args, **kw)
  564. # AUTH related stuff. It would be nice if support for this were in smtpd.
  565. def found_terminator(self):
  566. if self.smtp_state == self.AUTH:
  567. line = self._emptystring.join(self.received_lines)
  568. print('Data:', repr(line), file=smtpd.DEBUGSTREAM)
  569. self.received_lines = []
  570. try:
  571. self.auth_object(line)
  572. except ResponseException as e:
  573. self.smtp_state = self.COMMAND
  574. self.push('%s %s' % (e.smtp_code, e.smtp_error))
  575. return
  576. super().found_terminator()
  577. def smtp_AUTH(self, arg):
  578. if not self.seen_greeting:
  579. self.push('503 Error: send EHLO first')
  580. return
  581. if not self.extended_smtp or 'AUTH' not in self._extrafeatures:
  582. self.push('500 Error: command "AUTH" not recognized')
  583. return
  584. if self.authenticated_user is not None:
  585. self.push(
  586. '503 Bad sequence of commands: already authenticated')
  587. return
  588. args = arg.split()
  589. if len(args) not in [1, 2]:
  590. self.push('501 Syntax: AUTH <mechanism> [initial-response]')
  591. return
  592. auth_object_name = '_auth_%s' % args[0].lower().replace('-', '_')
  593. try:
  594. self.auth_object = getattr(self, auth_object_name)
  595. except AttributeError:
  596. self.push('504 Command parameter not implemented: unsupported '
  597. ' authentication mechanism {!r}'.format(auth_object_name))
  598. return
  599. self.smtp_state = self.AUTH
  600. self.auth_object(args[1] if len(args) == 2 else None)
  601. def _authenticated(self, user, valid):
  602. if valid:
  603. self.authenticated_user = user
  604. self.push('235 Authentication Succeeded')
  605. else:
  606. self.push('535 Authentication credentials invalid')
  607. self.smtp_state = self.COMMAND
  608. def _decode_base64(self, string):
  609. return base64.decodebytes(string.encode('ascii')).decode('utf-8')
  610. def _auth_plain(self, arg=None):
  611. if arg is None:
  612. self.push('334 ')
  613. else:
  614. logpass = self._decode_base64(arg)
  615. try:
  616. *_, user, password = logpass.split('\0')
  617. except ValueError as e:
  618. self.push('535 Splitting response {!r} into user and password'
  619. ' failed: {}'.format(logpass, e))
  620. return
  621. self._authenticated(user, password == sim_auth[1])
  622. def _auth_login(self, arg=None):
  623. if arg is None:
  624. # base64 encoded 'Username:'
  625. self.push('334 VXNlcm5hbWU6')
  626. elif not hasattr(self, '_auth_login_user'):
  627. self._auth_login_user = self._decode_base64(arg)
  628. # base64 encoded 'Password:'
  629. self.push('334 UGFzc3dvcmQ6')
  630. else:
  631. password = self._decode_base64(arg)
  632. self._authenticated(self._auth_login_user, password == sim_auth[1])
  633. del self._auth_login_user
  634. def _auth_cram_md5(self, arg=None):
  635. if arg is None:
  636. self.push('334 {}'.format(sim_cram_md5_challenge))
  637. else:
  638. logpass = self._decode_base64(arg)
  639. try:
  640. user, hashed_pass = logpass.split()
  641. except ValueError as e:
  642. self.push('535 Splitting response {!r} into user and password'
  643. 'failed: {}'.format(logpass, e))
  644. return False
  645. valid_hashed_pass = hmac.HMAC(
  646. sim_auth[1].encode('ascii'),
  647. self._decode_base64(sim_cram_md5_challenge).encode('ascii'),
  648. 'md5').hexdigest()
  649. self._authenticated(user, hashed_pass == valid_hashed_pass)
  650. # end AUTH related stuff.
  651. def smtp_EHLO(self, arg):
  652. resp = ('250-testhost\r\n'
  653. '250-EXPN\r\n'
  654. '250-SIZE 20000000\r\n'
  655. '250-STARTTLS\r\n'
  656. '250-DELIVERBY\r\n')
  657. resp = resp + self._extrafeatures + '250 HELP'
  658. self.push(resp)
  659. self.seen_greeting = arg
  660. self.extended_smtp = True
  661. def smtp_VRFY(self, arg):
  662. # For max compatibility smtplib should be sending the raw address.
  663. if arg in sim_users:
  664. self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
  665. else:
  666. self.push('550 No such user: %s' % arg)
  667. def smtp_EXPN(self, arg):
  668. list_name = arg.lower()
  669. if list_name in sim_lists:
  670. user_list = sim_lists[list_name]
  671. for n, user_email in enumerate(user_list):
  672. quoted_addr = smtplib.quoteaddr(user_email)
  673. if n < len(user_list) - 1:
  674. self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
  675. else:
  676. self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
  677. else:
  678. self.push('550 No access for you!')
  679. def smtp_QUIT(self, arg):
  680. if self.quit_response is None:
  681. super(SimSMTPChannel, self).smtp_QUIT(arg)
  682. else:
  683. self.push(self.quit_response)
  684. self.close_when_done()
  685. def smtp_MAIL(self, arg):
  686. if self.mail_response is None:
  687. super().smtp_MAIL(arg)
  688. else:
  689. self.push(self.mail_response)
  690. if self.disconnect:
  691. self.close_when_done()
  692. def smtp_RCPT(self, arg):
  693. if self.rcpt_response is None:
  694. super().smtp_RCPT(arg)
  695. return
  696. self.rcpt_count += 1
  697. self.push(self.rcpt_response[self.rcpt_count-1])
  698. def smtp_RSET(self, arg):
  699. self.rset_count += 1
  700. super().smtp_RSET(arg)
  701. def smtp_DATA(self, arg):
  702. if self.data_response is None:
  703. super().smtp_DATA(arg)
  704. else:
  705. self.push(self.data_response)
  706. def handle_error(self):
  707. raise
  708. class SimSMTPServer(smtpd.SMTPServer):
  709. channel_class = SimSMTPChannel
  710. def __init__(self, *args, **kw):
  711. self._extra_features = []
  712. smtpd.SMTPServer.__init__(self, *args, **kw)
  713. def handle_accepted(self, conn, addr):
  714. self._SMTPchannel = self.channel_class(
  715. self._extra_features, self, conn, addr,
  716. decode_data=self._decode_data)
  717. def process_message(self, peer, mailfrom, rcpttos, data):
  718. pass
  719. def add_feature(self, feature):
  720. self._extra_features.append(feature)
  721. def handle_error(self):
  722. raise
  723. # Test various SMTP & ESMTP commands/behaviors that require a simulated server
  724. # (i.e., something with more features than DebuggingServer)
  725. @unittest.skipUnless(threading, 'Threading required for this test.')
  726. class SMTPSimTests(unittest.TestCase):
  727. def setUp(self):
  728. self.real_getfqdn = socket.getfqdn
  729. socket.getfqdn = mock_socket.getfqdn
  730. self.serv_evt = threading.Event()
  731. self.client_evt = threading.Event()
  732. # Pick a random unused port by passing 0 for the port number
  733. self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1), decode_data=True)
  734. # Keep a note of what port was assigned
  735. self.port = self.serv.socket.getsockname()[1]
  736. serv_args = (self.serv, self.serv_evt, self.client_evt)
  737. self.thread = threading.Thread(target=debugging_server, args=serv_args)
  738. self.thread.start()
  739. # wait until server thread has assigned a port number
  740. self.serv_evt.wait()
  741. self.serv_evt.clear()
  742. def tearDown(self):
  743. socket.getfqdn = self.real_getfqdn
  744. # indicate that the client is finished
  745. self.client_evt.set()
  746. # wait for the server thread to terminate
  747. self.serv_evt.wait()
  748. self.thread.join()
  749. def testBasic(self):
  750. # smoke test
  751. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  752. smtp.quit()
  753. def testEHLO(self):
  754. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  755. # no features should be present before the EHLO
  756. self.assertEqual(smtp.esmtp_features, {})
  757. # features expected from the test server
  758. expected_features = {'expn':'',
  759. 'size': '20000000',
  760. 'starttls': '',
  761. 'deliverby': '',
  762. 'help': '',
  763. }
  764. smtp.ehlo()
  765. self.assertEqual(smtp.esmtp_features, expected_features)
  766. for k in expected_features:
  767. self.assertTrue(smtp.has_extn(k))
  768. self.assertFalse(smtp.has_extn('unsupported-feature'))
  769. smtp.quit()
  770. def testVRFY(self):
  771. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  772. for addr_spec, name in sim_users.items():
  773. expected_known = (250, bytes('%s %s' %
  774. (name, smtplib.quoteaddr(addr_spec)),
  775. "ascii"))
  776. self.assertEqual(smtp.vrfy(addr_spec), expected_known)
  777. u = 'nobody@nowhere.com'
  778. expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
  779. self.assertEqual(smtp.vrfy(u), expected_unknown)
  780. smtp.quit()
  781. def testEXPN(self):
  782. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  783. for listname, members in sim_lists.items():
  784. users = []
  785. for m in members:
  786. users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
  787. expected_known = (250, bytes('\n'.join(users), "ascii"))
  788. self.assertEqual(smtp.expn(listname), expected_known)
  789. u = 'PSU-Members-List'
  790. expected_unknown = (550, b'No access for you!')
  791. self.assertEqual(smtp.expn(u), expected_unknown)
  792. smtp.quit()
  793. def testAUTH_PLAIN(self):
  794. self.serv.add_feature("AUTH PLAIN")
  795. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  796. resp = smtp.login(sim_auth[0], sim_auth[1])
  797. self.assertEqual(resp, (235, b'Authentication Succeeded'))
  798. smtp.close()
  799. def testAUTH_LOGIN(self):
  800. self.serv.add_feature("AUTH LOGIN")
  801. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  802. resp = smtp.login(sim_auth[0], sim_auth[1])
  803. self.assertEqual(resp, (235, b'Authentication Succeeded'))
  804. smtp.close()
  805. def testAUTH_CRAM_MD5(self):
  806. self.serv.add_feature("AUTH CRAM-MD5")
  807. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  808. resp = smtp.login(sim_auth[0], sim_auth[1])
  809. self.assertEqual(resp, (235, b'Authentication Succeeded'))
  810. smtp.close()
  811. def testAUTH_multiple(self):
  812. # Test that multiple authentication methods are tried.
  813. self.serv.add_feature("AUTH BOGUS PLAIN LOGIN CRAM-MD5")
  814. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  815. resp = smtp.login(sim_auth[0], sim_auth[1])
  816. self.assertEqual(resp, (235, b'Authentication Succeeded'))
  817. smtp.close()
  818. def test_auth_function(self):
  819. supported = {'CRAM-MD5', 'PLAIN', 'LOGIN'}
  820. for mechanism in supported:
  821. self.serv.add_feature("AUTH {}".format(mechanism))
  822. for mechanism in supported:
  823. with self.subTest(mechanism=mechanism):
  824. smtp = smtplib.SMTP(HOST, self.port,
  825. local_hostname='localhost', timeout=15)
  826. smtp.ehlo('foo')
  827. smtp.user, smtp.password = sim_auth[0], sim_auth[1]
  828. method = 'auth_' + mechanism.lower().replace('-', '_')
  829. resp = smtp.auth(mechanism, getattr(smtp, method))
  830. self.assertEqual(resp, (235, b'Authentication Succeeded'))
  831. smtp.close()
  832. def test_quit_resets_greeting(self):
  833. smtp = smtplib.SMTP(HOST, self.port,
  834. local_hostname='localhost',
  835. timeout=15)
  836. code, message = smtp.ehlo()
  837. self.assertEqual(code, 250)
  838. self.assertIn('size', smtp.esmtp_features)
  839. smtp.quit()
  840. self.assertNotIn('size', smtp.esmtp_features)
  841. smtp.connect(HOST, self.port)
  842. self.assertNotIn('size', smtp.esmtp_features)
  843. smtp.ehlo_or_helo_if_needed()
  844. self.assertIn('size', smtp.esmtp_features)
  845. smtp.quit()
  846. def test_with_statement(self):
  847. with smtplib.SMTP(HOST, self.port) as smtp:
  848. code, message = smtp.noop()
  849. self.assertEqual(code, 250)
  850. self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
  851. with smtplib.SMTP(HOST, self.port) as smtp:
  852. smtp.close()
  853. self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
  854. def test_with_statement_QUIT_failure(self):
  855. with self.assertRaises(smtplib.SMTPResponseException) as error:
  856. with smtplib.SMTP(HOST, self.port) as smtp:
  857. smtp.noop()
  858. self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
  859. self.assertEqual(error.exception.smtp_code, 421)
  860. self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
  861. #TODO: add tests for correct AUTH method fallback now that the
  862. #test infrastructure can support it.
  863. # Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception
  864. def test__rest_from_mail_cmd(self):
  865. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  866. smtp.noop()
  867. self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
  868. self.serv._SMTPchannel.disconnect = True
  869. with self.assertRaises(smtplib.SMTPSenderRefused):
  870. smtp.sendmail('John', 'Sally', 'test message')
  871. self.assertIsNone(smtp.sock)
  872. # Issue 5713: make sure close, not rset, is called if we get a 421 error
  873. def test_421_from_mail_cmd(self):
  874. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  875. smtp.noop()
  876. self.serv._SMTPchannel.mail_response = '421 closing connection'
  877. with self.assertRaises(smtplib.SMTPSenderRefused):
  878. smtp.sendmail('John', 'Sally', 'test message')
  879. self.assertIsNone(smtp.sock)
  880. self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
  881. def test_421_from_rcpt_cmd(self):
  882. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  883. smtp.noop()
  884. self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
  885. with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
  886. smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
  887. self.assertIsNone(smtp.sock)
  888. self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
  889. self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
  890. def test_421_from_data_cmd(self):
  891. class MySimSMTPChannel(SimSMTPChannel):
  892. def found_terminator(self):
  893. if self.smtp_state == self.DATA:
  894. self.push('421 closing')
  895. else:
  896. super().found_terminator()
  897. self.serv.channel_class = MySimSMTPChannel
  898. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  899. smtp.noop()
  900. with self.assertRaises(smtplib.SMTPDataError):
  901. smtp.sendmail('John@foo.org', ['Sally@foo.org'], 'test message')
  902. self.assertIsNone(smtp.sock)
  903. self.assertEqual(self.serv._SMTPchannel.rcpt_count, 0)
  904. def test_smtputf8_NotSupportedError_if_no_server_support(self):
  905. smtp = smtplib.SMTP(
  906. HOST, self.port, local_hostname='localhost', timeout=3)
  907. self.addCleanup(smtp.close)
  908. smtp.ehlo()
  909. self.assertTrue(smtp.does_esmtp)
  910. self.assertFalse(smtp.has_extn('smtputf8'))
  911. self.assertRaises(
  912. smtplib.SMTPNotSupportedError,
  913. smtp.sendmail,
  914. 'John', 'Sally', '', mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
  915. self.assertRaises(
  916. smtplib.SMTPNotSupportedError,
  917. smtp.mail, 'John', options=['BODY=8BITMIME', 'SMTPUTF8'])
  918. def test_send_unicode_without_SMTPUTF8(self):
  919. smtp = smtplib.SMTP(
  920. HOST, self.port, local_hostname='localhost', timeout=3)
  921. self.addCleanup(smtp.close)
  922. self.assertRaises(UnicodeEncodeError, smtp.sendmail, 'Alice', 'Böb', '')
  923. self.assertRaises(UnicodeEncodeError, smtp.mail, 'Älice')
  924. class SimSMTPUTF8Server(SimSMTPServer):
  925. def __init__(self, *args, **kw):
  926. # The base SMTP server turns these on automatically, but our test
  927. # server is set up to munge the EHLO response, so we need to provide
  928. # them as well. And yes, the call is to SMTPServer not SimSMTPServer.
  929. self._extra_features = ['SMTPUTF8', '8BITMIME']
  930. smtpd.SMTPServer.__init__(self, *args, **kw)
  931. def handle_accepted(self, conn, addr):
  932. self._SMTPchannel = self.channel_class(
  933. self._extra_features, self, conn, addr,
  934. decode_data=self._decode_data,
  935. enable_SMTPUTF8=self.enable_SMTPUTF8,
  936. )
  937. def process_message(self, peer, mailfrom, rcpttos, data, mail_options=None,
  938. rcpt_options=None):
  939. self.last_peer = peer
  940. self.last_mailfrom = mailfrom
  941. self.last_rcpttos = rcpttos
  942. self.last_message = data
  943. self.last_mail_options = mail_options
  944. self.last_rcpt_options = rcpt_options
  945. @unittest.skipUnless(threading, 'Threading required for this test.')
  946. class SMTPUTF8SimTests(unittest.TestCase):
  947. maxDiff = None
  948. def setUp(self):
  949. self.real_getfqdn = socket.getfqdn
  950. socket.getfqdn = mock_socket.getfqdn
  951. self.serv_evt = threading.Event()
  952. self.client_evt = threading.Event()
  953. # Pick a random unused port by passing 0 for the port number
  954. self.serv = SimSMTPUTF8Server((HOST, 0), ('nowhere', -1),
  955. decode_data=False,
  956. enable_SMTPUTF8=True)
  957. # Keep a note of what port was assigned
  958. self.port = self.serv.socket.getsockname()[1]
  959. serv_args = (self.serv, self.serv_evt, self.client_evt)
  960. self.thread = threading.Thread(target=debugging_server, args=serv_args)
  961. self.thread.start()
  962. # wait until server thread has assigned a port number
  963. self.serv_evt.wait()
  964. self.serv_evt.clear()
  965. def tearDown(self):
  966. socket.getfqdn = self.real_getfqdn
  967. # indicate that the client is finished
  968. self.client_evt.set()
  969. # wait for the server thread to terminate
  970. self.serv_evt.wait()
  971. self.thread.join()
  972. def test_test_server_supports_extensions(self):
  973. smtp = smtplib.SMTP(
  974. HOST, self.port, local_hostname='localhost', timeout=3)
  975. self.addCleanup(smtp.close)
  976. smtp.ehlo()
  977. self.assertTrue(smtp.does_esmtp)
  978. self.assertTrue(smtp.has_extn('smtputf8'))
  979. def test_send_unicode_with_SMTPUTF8_via_sendmail(self):
  980. m = '¡a test message containing unicode!'.encode('utf-8')
  981. smtp = smtplib.SMTP(
  982. HOST, self.port, local_hostname='localhost', timeout=3)
  983. self.addCleanup(smtp.close)
  984. smtp.sendmail('Jőhn', 'Sálly', m,
  985. mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
  986. self.assertEqual(self.serv.last_mailfrom, 'Jőhn')
  987. self.assertEqual(self.serv.last_rcpttos, ['Sálly'])
  988. self.assertEqual(self.serv.last_message, m)
  989. self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
  990. self.assertIn('SMTPUTF8', self.serv.last_mail_options)
  991. self.assertEqual(self.serv.last_rcpt_options, [])
  992. def test_send_unicode_with_SMTPUTF8_via_low_level_API(self):
  993. m = '¡a test message containing unicode!'.encode('utf-8')
  994. smtp = smtplib.SMTP(
  995. HOST, self.port, local_hostname='localhost', timeout=3)
  996. self.addCleanup(smtp.close)
  997. smtp.ehlo()
  998. self.assertEqual(
  999. smtp.mail('Jő', options=['BODY=8BITMIME', 'SMTPUTF8']),
  1000. (250, b'OK'))
  1001. self.assertEqual(smtp.rcpt('János'), (250, b'OK'))
  1002. self.assertEqual(smtp.data(m), (250, b'OK'))
  1003. self.assertEqual(self.serv.last_mailfrom, 'Jő')
  1004. self.assertEqual(self.serv.last_rcpttos, ['János'])
  1005. self.assertEqual(self.serv.last_message, m)
  1006. self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
  1007. self.assertIn('SMTPUTF8', self.serv.last_mail_options)
  1008. self.assertEqual(self.serv.last_rcpt_options, [])
  1009. def test_send_message_uses_smtputf8_if_addrs_non_ascii(self):
  1010. msg = EmailMessage()
  1011. msg['From'] = "Páolo <főo@bar.com>"
  1012. msg['To'] = 'Dinsdale'
  1013. msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
  1014. # XXX I don't know why I need two \n's here, but this is an existing
  1015. # bug (if it is one) and not a problem with the new functionality.
  1016. msg.set_content("oh là là, know what I mean, know what I mean?\n\n")
  1017. # XXX smtpd converts received /r/n to /n, so we can't easily test that
  1018. # we are successfully sending /r/n :(.
  1019. expected = textwrap.dedent("""\
  1020. From: Páolo <főo@bar.com>
  1021. To: Dinsdale
  1022. Subject: Nudge nudge, wink, wink \u1F609
  1023. Content-Type: text/plain; charset="utf-8"
  1024. Content-Transfer-Encoding: 8bit
  1025. MIME-Version: 1.0
  1026. oh , know what I mean, know what I mean?
  1027. """)
  1028. smtp = smtplib.SMTP(
  1029. HOST, self.port, local_hostname='localhost', timeout=3)
  1030. self.addCleanup(smtp.close)
  1031. self.assertEqual(smtp.send_message(msg), {})
  1032. self.assertEqual(self.serv.last_mailfrom, 'főo@bar.com')
  1033. self.assertEqual(self.serv.last_rcpttos, ['Dinsdale'])
  1034. self.assertEqual(self.serv.last_message.decode(), expected)
  1035. self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
  1036. self.assertIn('SMTPUTF8', self.serv.last_mail_options)
  1037. self.assertEqual(self.serv.last_rcpt_options, [])
  1038. def test_send_message_error_on_non_ascii_addrs_if_no_smtputf8(self):
  1039. msg = EmailMessage()
  1040. msg['From'] = "Páolo <főo@bar.com>"
  1041. msg['To'] = 'Dinsdale'
  1042. msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
  1043. smtp = smtplib.SMTP(
  1044. HOST, self.port, local_hostname='localhost', timeout=3)
  1045. self.addCleanup(smtp.close)
  1046. self.assertRaises(smtplib.SMTPNotSupportedError,
  1047. smtp.send_message(msg))
  1048. EXPECTED_RESPONSE = encode_base64(b'\0psu\0doesnotexist', eol='')
  1049. class SimSMTPAUTHInitialResponseChannel(SimSMTPChannel):
  1050. def smtp_AUTH(self, arg):
  1051. # RFC 4954's AUTH command allows for an optional initial-response.
  1052. # Not all AUTH methods support this; some require a challenge. AUTH
  1053. # PLAIN does those, so test that here. See issue #15014.
  1054. args = arg.split()
  1055. if args[0].lower() == 'plain':
  1056. if len(args) == 2:
  1057. # AUTH PLAIN <initial-response> with the response base 64
  1058. # encoded. Hard code the expected response for the test.
  1059. if args[1] == EXPECTED_RESPONSE:
  1060. self.push('235 Ok')
  1061. return
  1062. self.push('571 Bad authentication')
  1063. class SimSMTPAUTHInitialResponseServer(SimSMTPServer):
  1064. channel_class = SimSMTPAUTHInitialResponseChannel
  1065. @unittest.skipUnless(threading, 'Threading required for this test.')
  1066. class SMTPAUTHInitialResponseSimTests(unittest.TestCase):
  1067. def setUp(self):
  1068. self.real_getfqdn = socket.getfqdn
  1069. socket.getfqdn = mock_socket.getfqdn
  1070. self.serv_evt = threading.Event()
  1071. self.client_evt = threading.Event()
  1072. # Pick a random unused port by passing 0 for the port number
  1073. self.serv = SimSMTPAUTHInitialResponseServer(
  1074. (HOST, 0), ('nowhere', -1), decode_data=True)
  1075. # Keep a note of what port was assigned
  1076. self.port = self.serv.socket.getsockname()[1]
  1077. serv_args = (self.serv, self.serv_evt, self.client_evt)
  1078. self.thread = threading.Thread(target=debugging_server, args=serv_args)
  1079. self.thread.start()
  1080. # wait until server thread has assigned a port number
  1081. self.serv_evt.wait()
  1082. self.serv_evt.clear()
  1083. def tearDown(self):
  1084. socket.getfqdn = self.real_getfqdn
  1085. # indicate that the client is finished
  1086. self.client_evt.set()
  1087. # wait for the server thread to terminate
  1088. self.serv_evt.wait()
  1089. self.thread.join()
  1090. def testAUTH_PLAIN_initial_response_login(self):
  1091. self.serv.add_feature('AUTH PLAIN')
  1092. smtp = smtplib.SMTP(HOST, self.port,
  1093. local_hostname='localhost', timeout=15)
  1094. smtp.login('psu', 'doesnotexist')
  1095. smtp.close()
  1096. def testAUTH_PLAIN_initial_response_auth(self):
  1097. self.serv.add_feature('AUTH PLAIN')
  1098. smtp = smtplib.SMTP(HOST, self.port,
  1099. local_hostname='localhost', timeout=15)
  1100. smtp.user = 'psu'
  1101. smtp.password = 'doesnotexist'
  1102. code, response = smtp.auth('plain', smtp.auth_plain)
  1103. smtp.close()
  1104. self.assertEqual(code, 235)
  1105. @support.reap_threads
  1106. def test_main(verbose=None):
  1107. support.run_unittest(
  1108. BadHELOServerTests,
  1109. DebuggingServerTests,
  1110. GeneralTests,
  1111. NonConnectingTests,
  1112. SMTPAUTHInitialResponseSimTests,
  1113. SMTPSimTests,
  1114. TooLongLineTests,
  1115. )
  1116. if __name__ == '__main__':
  1117. test_main()