test_smtplib.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. import asyncore
  2. import email.utils
  3. import socket
  4. import smtpd
  5. import smtplib
  6. import StringIO
  7. import sys
  8. import time
  9. import select
  10. import unittest
  11. from test import test_support
  12. try:
  13. import threading
  14. except ImportError:
  15. threading = None
  16. HOST = test_support.HOST
  17. def server(evt, buf, serv):
  18. serv.listen(5)
  19. evt.set()
  20. try:
  21. conn, addr = serv.accept()
  22. except socket.timeout:
  23. pass
  24. else:
  25. n = 500
  26. while buf and n > 0:
  27. r, w, e = select.select([], [conn], [])
  28. if w:
  29. sent = conn.send(buf)
  30. buf = buf[sent:]
  31. n -= 1
  32. conn.close()
  33. finally:
  34. serv.close()
  35. evt.set()
  36. @unittest.skipUnless(threading, 'Threading required for this test.')
  37. class GeneralTests(unittest.TestCase):
  38. def setUp(self):
  39. self._threads = test_support.threading_setup()
  40. self.evt = threading.Event()
  41. self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  42. self.sock.settimeout(15)
  43. self.port = test_support.bind_port(self.sock)
  44. servargs = (self.evt, "220 Hola mundo\n", self.sock)
  45. self.thread = threading.Thread(target=server, args=servargs)
  46. self.thread.start()
  47. self.evt.wait()
  48. self.evt.clear()
  49. def tearDown(self):
  50. self.evt.wait()
  51. self.thread.join()
  52. test_support.threading_cleanup(*self._threads)
  53. def testBasic1(self):
  54. # connects
  55. smtp = smtplib.SMTP(HOST, self.port)
  56. smtp.close()
  57. def testBasic2(self):
  58. # connects, include port in host name
  59. smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
  60. smtp.close()
  61. def testLocalHostName(self):
  62. # check that supplied local_hostname is used
  63. smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
  64. self.assertEqual(smtp.local_hostname, "testhost")
  65. smtp.close()
  66. def testTimeoutDefault(self):
  67. self.assertIsNone(socket.getdefaulttimeout())
  68. socket.setdefaulttimeout(30)
  69. try:
  70. smtp = smtplib.SMTP(HOST, self.port)
  71. finally:
  72. socket.setdefaulttimeout(None)
  73. self.assertEqual(smtp.sock.gettimeout(), 30)
  74. smtp.close()
  75. def testTimeoutNone(self):
  76. self.assertIsNone(socket.getdefaulttimeout())
  77. socket.setdefaulttimeout(30)
  78. try:
  79. smtp = smtplib.SMTP(HOST, self.port, timeout=None)
  80. finally:
  81. socket.setdefaulttimeout(None)
  82. self.assertIsNone(smtp.sock.gettimeout())
  83. smtp.close()
  84. def testTimeoutValue(self):
  85. smtp = smtplib.SMTP(HOST, self.port, timeout=30)
  86. self.assertEqual(smtp.sock.gettimeout(), 30)
  87. smtp.close()
  88. # Test server thread using the specified SMTP server class
  89. def debugging_server(serv, serv_evt, client_evt):
  90. serv_evt.set()
  91. try:
  92. if hasattr(select, 'poll'):
  93. poll_fun = asyncore.poll2
  94. else:
  95. poll_fun = asyncore.poll
  96. n = 1000
  97. while asyncore.socket_map and n > 0:
  98. poll_fun(0.01, asyncore.socket_map)
  99. # when the client conversation is finished, it will
  100. # set client_evt, and it's then ok to kill the server
  101. if client_evt.is_set():
  102. serv.close()
  103. break
  104. n -= 1
  105. except socket.timeout:
  106. pass
  107. finally:
  108. if not client_evt.is_set():
  109. # allow some time for the client to read the result
  110. time.sleep(0.5)
  111. serv.close()
  112. asyncore.close_all()
  113. serv_evt.set()
  114. MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
  115. MSG_END = '------------ END MESSAGE ------------\n'
  116. # NOTE: Some SMTP objects in the tests below are created with a non-default
  117. # local_hostname argument to the constructor, since (on some systems) the FQDN
  118. # lookup caused by the default local_hostname sometimes takes so long that the
  119. # test server times out, causing the test to fail.
  120. # Test behavior of smtpd.DebuggingServer
  121. @unittest.skipUnless(threading, 'Threading required for this test.')
  122. class DebuggingServerTests(unittest.TestCase):
  123. def setUp(self):
  124. # temporarily replace sys.stdout to capture DebuggingServer output
  125. self.old_stdout = sys.stdout
  126. self.output = StringIO.StringIO()
  127. sys.stdout = self.output
  128. self._threads = test_support.threading_setup()
  129. self.serv_evt = threading.Event()
  130. self.client_evt = threading.Event()
  131. # Pick a random unused port by passing 0 for the port number
  132. self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1))
  133. # Keep a note of what port was assigned
  134. self.port = self.serv.socket.getsockname()[1]
  135. serv_args = (self.serv, self.serv_evt, self.client_evt)
  136. self.thread = threading.Thread(target=debugging_server, args=serv_args)
  137. self.thread.start()
  138. # wait until server thread has assigned a port number
  139. self.serv_evt.wait()
  140. self.serv_evt.clear()
  141. def tearDown(self):
  142. # indicate that the client is finished
  143. self.client_evt.set()
  144. # wait for the server thread to terminate
  145. self.serv_evt.wait()
  146. self.thread.join()
  147. test_support.threading_cleanup(*self._threads)
  148. # restore sys.stdout
  149. sys.stdout = self.old_stdout
  150. def testBasic(self):
  151. # connect
  152. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  153. smtp.quit()
  154. def testNOOP(self):
  155. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  156. expected = (250, 'Ok')
  157. self.assertEqual(smtp.noop(), expected)
  158. smtp.quit()
  159. def testRSET(self):
  160. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  161. expected = (250, 'Ok')
  162. self.assertEqual(smtp.rset(), expected)
  163. smtp.quit()
  164. def testNotImplemented(self):
  165. # EHLO isn't implemented in DebuggingServer
  166. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  167. expected = (502, 'Error: command "EHLO" not implemented')
  168. self.assertEqual(smtp.ehlo(), expected)
  169. smtp.quit()
  170. def testVRFY(self):
  171. # VRFY isn't implemented in DebuggingServer
  172. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  173. expected = (502, 'Error: command "VRFY" not implemented')
  174. self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
  175. self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
  176. smtp.quit()
  177. def testSecondHELO(self):
  178. # check that a second HELO returns a message that it's a duplicate
  179. # (this behavior is specific to smtpd.SMTPChannel)
  180. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  181. smtp.helo()
  182. expected = (503, 'Duplicate HELO/EHLO')
  183. self.assertEqual(smtp.helo(), expected)
  184. smtp.quit()
  185. def testHELP(self):
  186. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  187. self.assertEqual(smtp.help(), 'Error: command "HELP" not implemented')
  188. smtp.quit()
  189. def testSend(self):
  190. # connect and send mail
  191. m = 'A test message'
  192. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  193. smtp.sendmail('John', 'Sally', m)
  194. # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
  195. # in asyncore. This sleep might help, but should really be fixed
  196. # properly by using an Event variable.
  197. time.sleep(0.01)
  198. smtp.quit()
  199. self.client_evt.set()
  200. self.serv_evt.wait()
  201. self.output.flush()
  202. mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
  203. self.assertEqual(self.output.getvalue(), mexpect)
  204. class NonConnectingTests(unittest.TestCase):
  205. def testNotConnected(self):
  206. # Test various operations on an unconnected SMTP object that
  207. # should raise exceptions (at present the attempt in SMTP.send
  208. # to reference the nonexistent 'sock' attribute of the SMTP object
  209. # causes an AttributeError)
  210. smtp = smtplib.SMTP()
  211. self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
  212. self.assertRaises(smtplib.SMTPServerDisconnected,
  213. smtp.send, 'test msg')
  214. def testNonnumericPort(self):
  215. # check that non-numeric port raises socket.error
  216. self.assertRaises(socket.error, smtplib.SMTP,
  217. "localhost", "bogus")
  218. self.assertRaises(socket.error, smtplib.SMTP,
  219. "localhost:bogus")
  220. # test response of client to a non-successful HELO message
  221. @unittest.skipUnless(threading, 'Threading required for this test.')
  222. class BadHELOServerTests(unittest.TestCase):
  223. def setUp(self):
  224. self.old_stdout = sys.stdout
  225. self.output = StringIO.StringIO()
  226. sys.stdout = self.output
  227. self._threads = test_support.threading_setup()
  228. self.evt = threading.Event()
  229. self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  230. self.sock.settimeout(15)
  231. self.port = test_support.bind_port(self.sock)
  232. servargs = (self.evt, "199 no hello for you!\n", self.sock)
  233. self.thread = threading.Thread(target=server, args=servargs)
  234. self.thread.start()
  235. self.evt.wait()
  236. self.evt.clear()
  237. def tearDown(self):
  238. self.evt.wait()
  239. self.thread.join()
  240. test_support.threading_cleanup(*self._threads)
  241. sys.stdout = self.old_stdout
  242. def testFailingHELO(self):
  243. self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
  244. HOST, self.port, 'localhost', 3)
  245. @unittest.skipUnless(threading, 'Threading required for this test.')
  246. class TooLongLineTests(unittest.TestCase):
  247. respdata = '250 OK' + ('.' * smtplib._MAXLINE * 2) + '\n'
  248. def setUp(self):
  249. self.old_stdout = sys.stdout
  250. self.output = StringIO.StringIO()
  251. sys.stdout = self.output
  252. self.evt = threading.Event()
  253. self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  254. self.sock.settimeout(15)
  255. self.port = test_support.bind_port(self.sock)
  256. servargs = (self.evt, self.respdata, self.sock)
  257. threading.Thread(target=server, args=servargs).start()
  258. self.evt.wait()
  259. self.evt.clear()
  260. def tearDown(self):
  261. self.evt.wait()
  262. sys.stdout = self.old_stdout
  263. def testLineTooLong(self):
  264. self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
  265. HOST, self.port, 'localhost', 3)
  266. sim_users = {'Mr.A@somewhere.com':'John A',
  267. 'Ms.B@somewhere.com':'Sally B',
  268. 'Mrs.C@somewhereesle.com':'Ruth C',
  269. }
  270. sim_auth = ('Mr.A@somewhere.com', 'somepassword')
  271. sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
  272. 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
  273. sim_auth_credentials = {
  274. 'login': 'TXIuQUBzb21ld2hlcmUuY29t',
  275. 'plain': 'AE1yLkFAc29tZXdoZXJlLmNvbQBzb21lcGFzc3dvcmQ=',
  276. 'cram-md5': ('TXIUQUBZB21LD2HLCMUUY29TIDG4OWQ0MJ'
  277. 'KWZGQ4ODNMNDA4NTGXMDRLZWMYZJDMODG1'),
  278. }
  279. sim_auth_login_password = 'C29TZXBHC3N3B3JK'
  280. sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
  281. 'list-2':['Ms.B@somewhere.com',],
  282. }
  283. # Simulated SMTP channel & server
  284. class SimSMTPChannel(smtpd.SMTPChannel):
  285. def __init__(self, extra_features, *args, **kw):
  286. self._extrafeatures = ''.join(
  287. [ "250-{0}\r\n".format(x) for x in extra_features ])
  288. smtpd.SMTPChannel.__init__(self, *args, **kw)
  289. def smtp_EHLO(self, arg):
  290. resp = ('250-testhost\r\n'
  291. '250-EXPN\r\n'
  292. '250-SIZE 20000000\r\n'
  293. '250-STARTTLS\r\n'
  294. '250-DELIVERBY\r\n')
  295. resp = resp + self._extrafeatures + '250 HELP'
  296. self.push(resp)
  297. def smtp_VRFY(self, arg):
  298. # For max compatibility smtplib should be sending the raw address.
  299. if arg in sim_users:
  300. self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
  301. else:
  302. self.push('550 No such user: %s' % arg)
  303. def smtp_EXPN(self, arg):
  304. list_name = arg.lower()
  305. if list_name in sim_lists:
  306. user_list = sim_lists[list_name]
  307. for n, user_email in enumerate(user_list):
  308. quoted_addr = smtplib.quoteaddr(user_email)
  309. if n < len(user_list) - 1:
  310. self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
  311. else:
  312. self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
  313. else:
  314. self.push('550 No access for you!')
  315. def smtp_AUTH(self, arg):
  316. if arg.strip().lower()=='cram-md5':
  317. self.push('334 {0}'.format(sim_cram_md5_challenge))
  318. return
  319. mech, auth = arg.split()
  320. mech = mech.lower()
  321. if mech not in sim_auth_credentials:
  322. self.push('504 auth type unimplemented')
  323. return
  324. if mech == 'plain' and auth==sim_auth_credentials['plain']:
  325. self.push('235 plain auth ok')
  326. elif mech=='login' and auth==sim_auth_credentials['login']:
  327. self.push('334 Password:')
  328. else:
  329. self.push('550 No access for you!')
  330. def handle_error(self):
  331. raise
  332. class SimSMTPServer(smtpd.SMTPServer):
  333. def __init__(self, *args, **kw):
  334. self._extra_features = []
  335. smtpd.SMTPServer.__init__(self, *args, **kw)
  336. def handle_accept(self):
  337. conn, addr = self.accept()
  338. self._SMTPchannel = SimSMTPChannel(self._extra_features,
  339. self, conn, addr)
  340. def process_message(self, peer, mailfrom, rcpttos, data):
  341. pass
  342. def add_feature(self, feature):
  343. self._extra_features.append(feature)
  344. def handle_error(self):
  345. raise
  346. # Test various SMTP & ESMTP commands/behaviors that require a simulated server
  347. # (i.e., something with more features than DebuggingServer)
  348. @unittest.skipUnless(threading, 'Threading required for this test.')
  349. class SMTPSimTests(unittest.TestCase):
  350. def setUp(self):
  351. self._threads = test_support.threading_setup()
  352. self.serv_evt = threading.Event()
  353. self.client_evt = threading.Event()
  354. # Pick a random unused port by passing 0 for the port number
  355. self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1))
  356. # Keep a note of what port was assigned
  357. self.port = self.serv.socket.getsockname()[1]
  358. serv_args = (self.serv, self.serv_evt, self.client_evt)
  359. self.thread = threading.Thread(target=debugging_server, args=serv_args)
  360. self.thread.start()
  361. # wait until server thread has assigned a port number
  362. self.serv_evt.wait()
  363. self.serv_evt.clear()
  364. def tearDown(self):
  365. # indicate that the client is finished
  366. self.client_evt.set()
  367. # wait for the server thread to terminate
  368. self.serv_evt.wait()
  369. self.thread.join()
  370. test_support.threading_cleanup(*self._threads)
  371. def testBasic(self):
  372. # smoke test
  373. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  374. smtp.quit()
  375. def testEHLO(self):
  376. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  377. # no features should be present before the EHLO
  378. self.assertEqual(smtp.esmtp_features, {})
  379. # features expected from the test server
  380. expected_features = {'expn':'',
  381. 'size': '20000000',
  382. 'starttls': '',
  383. 'deliverby': '',
  384. 'help': '',
  385. }
  386. smtp.ehlo()
  387. self.assertEqual(smtp.esmtp_features, expected_features)
  388. for k in expected_features:
  389. self.assertTrue(smtp.has_extn(k))
  390. self.assertFalse(smtp.has_extn('unsupported-feature'))
  391. smtp.quit()
  392. def testVRFY(self):
  393. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  394. for email, name in sim_users.items():
  395. expected_known = (250, '%s %s' % (name, smtplib.quoteaddr(email)))
  396. self.assertEqual(smtp.vrfy(email), expected_known)
  397. u = 'nobody@nowhere.com'
  398. expected_unknown = (550, 'No such user: %s' % u)
  399. self.assertEqual(smtp.vrfy(u), expected_unknown)
  400. smtp.quit()
  401. def testEXPN(self):
  402. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  403. for listname, members in sim_lists.items():
  404. users = []
  405. for m in members:
  406. users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
  407. expected_known = (250, '\n'.join(users))
  408. self.assertEqual(smtp.expn(listname), expected_known)
  409. u = 'PSU-Members-List'
  410. expected_unknown = (550, 'No access for you!')
  411. self.assertEqual(smtp.expn(u), expected_unknown)
  412. smtp.quit()
  413. def testAUTH_PLAIN(self):
  414. self.serv.add_feature("AUTH PLAIN")
  415. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  416. expected_auth_ok = (235, b'plain auth ok')
  417. self.assertEqual(smtp.login(sim_auth[0], sim_auth[1]), expected_auth_ok)
  418. # SimSMTPChannel doesn't fully support LOGIN or CRAM-MD5 auth because they
  419. # require a synchronous read to obtain the credentials...so instead smtpd
  420. # sees the credential sent by smtplib's login method as an unknown command,
  421. # which results in smtplib raising an auth error. Fortunately the error
  422. # message contains the encoded credential, so we can partially check that it
  423. # was generated correctly (partially, because the 'word' is uppercased in
  424. # the error message).
  425. def testAUTH_LOGIN(self):
  426. self.serv.add_feature("AUTH LOGIN")
  427. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  428. try: smtp.login(sim_auth[0], sim_auth[1])
  429. except smtplib.SMTPAuthenticationError as err:
  430. if sim_auth_login_password not in str(err):
  431. raise "expected encoded password not found in error message"
  432. def testAUTH_CRAM_MD5(self):
  433. self.serv.add_feature("AUTH CRAM-MD5")
  434. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  435. try: smtp.login(sim_auth[0], sim_auth[1])
  436. except smtplib.SMTPAuthenticationError as err:
  437. if sim_auth_credentials['cram-md5'] not in str(err):
  438. raise "expected encoded credentials not found in error message"
  439. #TODO: add tests for correct AUTH method fallback now that the
  440. #test infrastructure can support it.
  441. def test_quit_resets_greeting(self):
  442. smtp = smtplib.SMTP(HOST, self.port,
  443. local_hostname='localhost',
  444. timeout=15)
  445. code, message = smtp.ehlo()
  446. self.assertEqual(code, 250)
  447. self.assertIn('size', smtp.esmtp_features)
  448. smtp.quit()
  449. self.assertNotIn('size', smtp.esmtp_features)
  450. smtp.connect(HOST, self.port)
  451. self.assertNotIn('size', smtp.esmtp_features)
  452. smtp.ehlo_or_helo_if_needed()
  453. self.assertIn('size', smtp.esmtp_features)
  454. smtp.quit()
  455. def test_main(verbose=None):
  456. test_support.run_unittest(GeneralTests, DebuggingServerTests,
  457. NonConnectingTests,
  458. BadHELOServerTests, SMTPSimTests,
  459. TooLongLineTests)
  460. if __name__ == '__main__':
  461. test_main()