PageRenderTime 122ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/test/test_smtplib.py

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