test_smtplib.py 60 KB

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