blob: 9011042858fbf396815682a5097dfcfd990275e7 [file] [log] [blame]
Guido van Rossum806c2462007-08-06 23:33:07 +00001import asyncore
R. David Murray7dff9e02010-11-08 17:15:13 +00002import email.mime.text
Guido van Rossum04110fb2007-08-24 16:32:05 +00003import email.utils
Guido van Rossumd8faa362007-04-27 19:54:29 +00004import socket
Guido van Rossum806c2462007-08-06 23:33:07 +00005import smtpd
Guido van Rossumd8faa362007-04-27 19:54:29 +00006import smtplib
Guido van Rossum806c2462007-08-06 23:33:07 +00007import io
R. David Murray7dff9e02010-11-08 17:15:13 +00008import re
Guido van Rossum806c2462007-08-06 23:33:07 +00009import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +000010import time
Guido van Rossum806c2462007-08-06 23:33:07 +000011import select
Ross Lagerwall86407432012-03-29 18:08:48 +020012import errno
R David Murray76e13c12014-07-03 14:47:46 -040013import base64
Guido van Rossumd8faa362007-04-27 19:54:29 +000014
Victor Stinner45df8202010-04-28 22:31:17 +000015import unittest
Richard Jones64b02de2010-08-03 06:39:33 +000016from test import support, mock_socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000017
Victor Stinner45df8202010-04-28 22:31:17 +000018try:
19 import threading
20except ImportError:
21 threading = None
22
Benjamin Petersonee8712c2008-05-20 21:35:26 +000023HOST = support.HOST
Guido van Rossumd8faa362007-04-27 19:54:29 +000024
Josiah Carlsond74900e2008-07-07 04:15:08 +000025if sys.platform == 'darwin':
26 # select.poll returns a select.POLLHUP at the end of the tests
27 # on darwin, so just ignore it
28 def handle_expt(self):
29 pass
30 smtpd.SMTPChannel.handle_expt = handle_expt
31
32
Christian Heimes5e696852008-04-09 08:37:03 +000033def server(evt, buf, serv):
Charles-François Natali6e204602014-07-23 19:28:13 +010034 serv.listen()
Christian Heimes380f7f22008-02-28 11:19:05 +000035 evt.set()
Guido van Rossumd8faa362007-04-27 19:54:29 +000036 try:
37 conn, addr = serv.accept()
38 except socket.timeout:
39 pass
40 else:
Guido van Rossum806c2462007-08-06 23:33:07 +000041 n = 500
42 while buf and n > 0:
43 r, w, e = select.select([], [conn], [])
44 if w:
45 sent = conn.send(buf)
46 buf = buf[sent:]
47
48 n -= 1
Guido van Rossum806c2462007-08-06 23:33:07 +000049
Guido van Rossumd8faa362007-04-27 19:54:29 +000050 conn.close()
51 finally:
52 serv.close()
53 evt.set()
54
Victor Stinner45df8202010-04-28 22:31:17 +000055class GeneralTests(unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +000056
57 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +000058 smtplib.socket = mock_socket
59 self.port = 25
Guido van Rossumd8faa362007-04-27 19:54:29 +000060
61 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +000062 smtplib.socket = socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000063
R. David Murray7dff9e02010-11-08 17:15:13 +000064 # This method is no longer used but is retained for backward compatibility,
65 # so test to make sure it still works.
66 def testQuoteData(self):
67 teststr = "abc\n.jkl\rfoo\r\n..blue"
68 expected = "abc\r\n..jkl\r\nfoo\r\n...blue"
69 self.assertEqual(expected, smtplib.quotedata(teststr))
70
Guido van Rossum806c2462007-08-06 23:33:07 +000071 def testBasic1(self):
Richard Jones64b02de2010-08-03 06:39:33 +000072 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossumd8faa362007-04-27 19:54:29 +000073 # connects
Christian Heimes5e696852008-04-09 08:37:03 +000074 smtp = smtplib.SMTP(HOST, self.port)
Georg Brandlf78e02b2008-06-10 17:40:04 +000075 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +000076
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080077 def testSourceAddress(self):
78 mock_socket.reply_with(b"220 Hola mundo")
79 # connects
80 smtp = smtplib.SMTP(HOST, self.port,
81 source_address=('127.0.0.1',19876))
82 self.assertEqual(smtp.source_address, ('127.0.0.1', 19876))
83 smtp.close()
84
Guido van Rossum806c2462007-08-06 23:33:07 +000085 def testBasic2(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000086 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000087 # connects, include port in host name
Christian Heimes5e696852008-04-09 08:37:03 +000088 smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
Georg Brandlf78e02b2008-06-10 17:40:04 +000089 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000090
91 def testLocalHostName(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000092 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000093 # check that supplied local_hostname is used
Christian Heimes5e696852008-04-09 08:37:03 +000094 smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
Guido van Rossum806c2462007-08-06 23:33:07 +000095 self.assertEqual(smtp.local_hostname, "testhost")
Georg Brandlf78e02b2008-06-10 17:40:04 +000096 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000097
Guido van Rossumd8faa362007-04-27 19:54:29 +000098 def testTimeoutDefault(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000099 mock_socket.reply_with(b"220 Hola mundo")
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200100 self.assertIsNone(mock_socket.getdefaulttimeout())
Richard Jones64b02de2010-08-03 06:39:33 +0000101 mock_socket.setdefaulttimeout(30)
102 self.assertEqual(mock_socket.getdefaulttimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000103 try:
104 smtp = smtplib.SMTP(HOST, self.port)
105 finally:
Richard Jones64b02de2010-08-03 06:39:33 +0000106 mock_socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000107 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000108 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000109
110 def testTimeoutNone(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000111 mock_socket.reply_with(b"220 Hola mundo")
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200112 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000113 socket.setdefaulttimeout(30)
114 try:
Christian Heimes5e696852008-04-09 08:37:03 +0000115 smtp = smtplib.SMTP(HOST, self.port, timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000116 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000117 socket.setdefaulttimeout(None)
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200118 self.assertIsNone(smtp.sock.gettimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +0000119 smtp.close()
120
121 def testTimeoutValue(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000122 mock_socket.reply_with(b"220 Hola mundo")
Georg Brandlf78e02b2008-06-10 17:40:04 +0000123 smtp = smtplib.SMTP(HOST, self.port, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000124 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000125 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000126
R David Murray0c49b892015-04-16 17:14:42 -0400127 def test_debuglevel(self):
128 mock_socket.reply_with(b"220 Hello world")
129 smtp = smtplib.SMTP()
130 smtp.set_debuglevel(1)
131 with support.captured_stderr() as stderr:
132 smtp.connect(HOST, self.port)
133 smtp.close()
134 expected = re.compile(r"^connect:", re.MULTILINE)
135 self.assertRegex(stderr.getvalue(), expected)
136
137 def test_debuglevel_2(self):
138 mock_socket.reply_with(b"220 Hello world")
139 smtp = smtplib.SMTP()
140 smtp.set_debuglevel(2)
141 with support.captured_stderr() as stderr:
142 smtp.connect(HOST, self.port)
143 smtp.close()
144 expected = re.compile(r"^\d{2}:\d{2}:\d{2}\.\d{6} connect: ",
145 re.MULTILINE)
146 self.assertRegex(stderr.getvalue(), expected)
147
Guido van Rossumd8faa362007-04-27 19:54:29 +0000148
Guido van Rossum04110fb2007-08-24 16:32:05 +0000149# Test server thread using the specified SMTP server class
Christian Heimes5e696852008-04-09 08:37:03 +0000150def debugging_server(serv, serv_evt, client_evt):
Christian Heimes380f7f22008-02-28 11:19:05 +0000151 serv_evt.set()
Guido van Rossum806c2462007-08-06 23:33:07 +0000152
153 try:
154 if hasattr(select, 'poll'):
155 poll_fun = asyncore.poll2
156 else:
157 poll_fun = asyncore.poll
158
159 n = 1000
160 while asyncore.socket_map and n > 0:
161 poll_fun(0.01, asyncore.socket_map)
162
163 # when the client conversation is finished, it will
164 # set client_evt, and it's then ok to kill the server
Benjamin Peterson672b8032008-06-11 19:14:14 +0000165 if client_evt.is_set():
Guido van Rossum806c2462007-08-06 23:33:07 +0000166 serv.close()
167 break
168
169 n -= 1
170
171 except socket.timeout:
172 pass
173 finally:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000174 if not client_evt.is_set():
Christian Heimes380f7f22008-02-28 11:19:05 +0000175 # allow some time for the client to read the result
176 time.sleep(0.5)
177 serv.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000178 asyncore.close_all()
Guido van Rossum806c2462007-08-06 23:33:07 +0000179 serv_evt.set()
180
181MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
182MSG_END = '------------ END MESSAGE ------------\n'
183
Guido van Rossum04110fb2007-08-24 16:32:05 +0000184# NOTE: Some SMTP objects in the tests below are created with a non-default
185# local_hostname argument to the constructor, since (on some systems) the FQDN
186# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000187# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000188
189# Test behavior of smtpd.DebuggingServer
Victor Stinner45df8202010-04-28 22:31:17 +0000190@unittest.skipUnless(threading, 'Threading required for this test.')
191class DebuggingServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000192
R. David Murray7dff9e02010-11-08 17:15:13 +0000193 maxDiff = None
194
Guido van Rossum806c2462007-08-06 23:33:07 +0000195 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000196 self.real_getfqdn = socket.getfqdn
197 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000198 # temporarily replace sys.stdout to capture DebuggingServer output
199 self.old_stdout = sys.stdout
200 self.output = io.StringIO()
201 sys.stdout = self.output
202
203 self.serv_evt = threading.Event()
204 self.client_evt = threading.Event()
R. David Murray7dff9e02010-11-08 17:15:13 +0000205 # Capture SMTPChannel debug output
206 self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
207 smtpd.DEBUGSTREAM = io.StringIO()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000208 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400209 self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1),
210 decode_data=True)
Antoine Pitrou043bad02010-04-30 23:20:15 +0000211 # Keep a note of what port was assigned
212 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000213 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000214 self.thread = threading.Thread(target=debugging_server, args=serv_args)
215 self.thread.start()
Guido van Rossum806c2462007-08-06 23:33:07 +0000216
217 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000218 self.serv_evt.wait()
219 self.serv_evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000220
221 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000222 socket.getfqdn = self.real_getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000223 # indicate that the client is finished
224 self.client_evt.set()
225 # wait for the server thread to terminate
226 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000227 self.thread.join()
Guido van Rossum806c2462007-08-06 23:33:07 +0000228 # restore sys.stdout
229 sys.stdout = self.old_stdout
R. David Murray7dff9e02010-11-08 17:15:13 +0000230 # restore DEBUGSTREAM
231 smtpd.DEBUGSTREAM.close()
232 smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
Guido van Rossum806c2462007-08-06 23:33:07 +0000233
234 def testBasic(self):
235 # connect
Christian Heimes5e696852008-04-09 08:37:03 +0000236 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000237 smtp.quit()
238
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800239 def testSourceAddress(self):
240 # connect
Senthil Kumaranb351a482011-07-31 09:14:17 +0800241 port = support.find_unused_port()
242 try:
243 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
244 timeout=3, source_address=('127.0.0.1', port))
245 self.assertEqual(smtp.source_address, ('127.0.0.1', port))
246 self.assertEqual(smtp.local_hostname, 'localhost')
247 smtp.quit()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200248 except OSError as e:
Senthil Kumaranb351a482011-07-31 09:14:17 +0800249 if e.errno == errno.EADDRINUSE:
250 self.skipTest("couldn't bind to port %d" % port)
251 raise
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800252
Guido van Rossum04110fb2007-08-24 16:32:05 +0000253 def testNOOP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000254 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400255 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000256 self.assertEqual(smtp.noop(), expected)
257 smtp.quit()
258
259 def testRSET(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000260 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400261 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000262 self.assertEqual(smtp.rset(), expected)
263 smtp.quit()
264
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400265 def testELHO(self):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000266 # EHLO isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000267 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400268 expected = (250, b'\nSIZE 33554432\nHELP')
Guido van Rossum806c2462007-08-06 23:33:07 +0000269 self.assertEqual(smtp.ehlo(), expected)
270 smtp.quit()
271
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400272 def testEXPNNotImplemented(self):
R David Murrayd1a30c92012-05-26 14:33:59 -0400273 # EXPN isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000274 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400275 expected = (502, b'EXPN not implemented')
276 smtp.putcmd('EXPN')
277 self.assertEqual(smtp.getreply(), expected)
278 smtp.quit()
279
280 def testVRFY(self):
281 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
282 expected = (252, b'Cannot VRFY user, but will accept message ' + \
283 b'and attempt delivery')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000284 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
285 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
286 smtp.quit()
287
288 def testSecondHELO(self):
289 # check that a second HELO returns a message that it's a duplicate
290 # (this behavior is specific to smtpd.SMTPChannel)
Christian Heimes5e696852008-04-09 08:37:03 +0000291 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000292 smtp.helo()
293 expected = (503, b'Duplicate HELO/EHLO')
294 self.assertEqual(smtp.helo(), expected)
295 smtp.quit()
296
Guido van Rossum806c2462007-08-06 23:33:07 +0000297 def testHELP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000298 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400299 self.assertEqual(smtp.help(), b'Supported commands: EHLO HELO MAIL ' + \
300 b'RCPT DATA RSET NOOP QUIT VRFY')
Guido van Rossum806c2462007-08-06 23:33:07 +0000301 smtp.quit()
302
303 def testSend(self):
304 # connect and send mail
305 m = 'A test message'
Christian Heimes5e696852008-04-09 08:37:03 +0000306 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000307 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000308 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
309 # in asyncore. This sleep might help, but should really be fixed
310 # properly by using an Event variable.
311 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000312 smtp.quit()
313
314 self.client_evt.set()
315 self.serv_evt.wait()
316 self.output.flush()
317 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
318 self.assertEqual(self.output.getvalue(), mexpect)
319
R. David Murray7dff9e02010-11-08 17:15:13 +0000320 def testSendBinary(self):
321 m = b'A test message'
322 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
323 smtp.sendmail('John', 'Sally', m)
324 # XXX (see comment in testSend)
325 time.sleep(0.01)
326 smtp.quit()
327
328 self.client_evt.set()
329 self.serv_evt.wait()
330 self.output.flush()
331 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
332 self.assertEqual(self.output.getvalue(), mexpect)
333
R David Murray0f663d02011-06-09 15:05:57 -0400334 def testSendNeedingDotQuote(self):
335 # Issue 12283
336 m = '.A test\n.mes.sage.'
337 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
338 smtp.sendmail('John', 'Sally', m)
339 # XXX (see comment in testSend)
340 time.sleep(0.01)
341 smtp.quit()
342
343 self.client_evt.set()
344 self.serv_evt.wait()
345 self.output.flush()
346 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
347 self.assertEqual(self.output.getvalue(), mexpect)
348
R David Murray46346762011-07-18 21:38:54 -0400349 def testSendNullSender(self):
350 m = 'A test message'
351 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
352 smtp.sendmail('<>', 'Sally', m)
353 # XXX (see comment in testSend)
354 time.sleep(0.01)
355 smtp.quit()
356
357 self.client_evt.set()
358 self.serv_evt.wait()
359 self.output.flush()
360 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
361 self.assertEqual(self.output.getvalue(), mexpect)
362 debugout = smtpd.DEBUGSTREAM.getvalue()
363 sender = re.compile("^sender: <>$", re.MULTILINE)
364 self.assertRegex(debugout, sender)
365
R. David Murray7dff9e02010-11-08 17:15:13 +0000366 def testSendMessage(self):
367 m = email.mime.text.MIMEText('A test message')
368 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
369 smtp.send_message(m, from_addr='John', to_addrs='Sally')
370 # XXX (see comment in testSend)
371 time.sleep(0.01)
372 smtp.quit()
373
374 self.client_evt.set()
375 self.serv_evt.wait()
376 self.output.flush()
377 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400378 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000379 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
380 self.assertEqual(self.output.getvalue(), mexpect)
381
382 def testSendMessageWithAddresses(self):
383 m = email.mime.text.MIMEText('A test message')
384 m['From'] = 'foo@bar.com'
385 m['To'] = 'John'
386 m['CC'] = 'Sally, Fred'
387 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
388 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
389 smtp.send_message(m)
390 # XXX (see comment in testSend)
391 time.sleep(0.01)
392 smtp.quit()
R David Murrayac4e5ab2011-07-02 21:03:19 -0400393 # make sure the Bcc header is still in the message.
394 self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
395 '<warped@silly.walks.com>')
R. David Murray7dff9e02010-11-08 17:15:13 +0000396
397 self.client_evt.set()
398 self.serv_evt.wait()
399 self.output.flush()
400 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400401 m['X-Peer'] = socket.gethostbyname('localhost')
R David Murrayac4e5ab2011-07-02 21:03:19 -0400402 # The Bcc header should not be transmitted.
R. David Murray7dff9e02010-11-08 17:15:13 +0000403 del m['Bcc']
404 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
405 self.assertEqual(self.output.getvalue(), mexpect)
406 debugout = smtpd.DEBUGSTREAM.getvalue()
407 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000408 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000409 for addr in ('John', 'Sally', 'Fred', 'root@localhost',
410 'warped@silly.walks.com'):
411 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
412 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000413 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000414
415 def testSendMessageWithSomeAddresses(self):
416 # Make sure nothing breaks if not all of the three 'to' headers exist
417 m = email.mime.text.MIMEText('A test message')
418 m['From'] = 'foo@bar.com'
419 m['To'] = 'John, Dinsdale'
420 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
421 smtp.send_message(m)
422 # XXX (see comment in testSend)
423 time.sleep(0.01)
424 smtp.quit()
425
426 self.client_evt.set()
427 self.serv_evt.wait()
428 self.output.flush()
429 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400430 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000431 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
432 self.assertEqual(self.output.getvalue(), mexpect)
433 debugout = smtpd.DEBUGSTREAM.getvalue()
434 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000435 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000436 for addr in ('John', 'Dinsdale'):
437 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
438 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000439 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000440
R David Murrayac4e5ab2011-07-02 21:03:19 -0400441 def testSendMessageWithSpecifiedAddresses(self):
442 # Make sure addresses specified in call override those in message.
443 m = email.mime.text.MIMEText('A test message')
444 m['From'] = 'foo@bar.com'
445 m['To'] = 'John, Dinsdale'
446 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
447 smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
448 # XXX (see comment in testSend)
449 time.sleep(0.01)
450 smtp.quit()
451
452 self.client_evt.set()
453 self.serv_evt.wait()
454 self.output.flush()
455 # Add the X-Peer header that DebuggingServer adds
456 m['X-Peer'] = socket.gethostbyname('localhost')
457 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
458 self.assertEqual(self.output.getvalue(), mexpect)
459 debugout = smtpd.DEBUGSTREAM.getvalue()
460 sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
461 self.assertRegex(debugout, sender)
462 for addr in ('John', 'Dinsdale'):
463 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
464 re.MULTILINE)
465 self.assertNotRegex(debugout, to_addr)
466 recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
467 self.assertRegex(debugout, recip)
468
469 def testSendMessageWithMultipleFrom(self):
470 # Sender overrides To
471 m = email.mime.text.MIMEText('A test message')
472 m['From'] = 'Bernard, Bianca'
473 m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com'
474 m['To'] = 'John, Dinsdale'
475 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
476 smtp.send_message(m)
477 # XXX (see comment in testSend)
478 time.sleep(0.01)
479 smtp.quit()
480
481 self.client_evt.set()
482 self.serv_evt.wait()
483 self.output.flush()
484 # Add the X-Peer header that DebuggingServer adds
485 m['X-Peer'] = socket.gethostbyname('localhost')
486 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
487 self.assertEqual(self.output.getvalue(), mexpect)
488 debugout = smtpd.DEBUGSTREAM.getvalue()
489 sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
490 self.assertRegex(debugout, sender)
491 for addr in ('John', 'Dinsdale'):
492 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
493 re.MULTILINE)
494 self.assertRegex(debugout, to_addr)
495
496 def testSendMessageResent(self):
497 m = email.mime.text.MIMEText('A test message')
498 m['From'] = 'foo@bar.com'
499 m['To'] = 'John'
500 m['CC'] = 'Sally, Fred'
501 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
502 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
503 m['Resent-From'] = 'holy@grail.net'
504 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
505 m['Resent-Bcc'] = 'doe@losthope.net'
506 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
507 smtp.send_message(m)
508 # XXX (see comment in testSend)
509 time.sleep(0.01)
510 smtp.quit()
511
512 self.client_evt.set()
513 self.serv_evt.wait()
514 self.output.flush()
515 # The Resent-Bcc headers are deleted before serialization.
516 del m['Bcc']
517 del m['Resent-Bcc']
518 # Add the X-Peer header that DebuggingServer adds
519 m['X-Peer'] = socket.gethostbyname('localhost')
520 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
521 self.assertEqual(self.output.getvalue(), mexpect)
522 debugout = smtpd.DEBUGSTREAM.getvalue()
523 sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
524 self.assertRegex(debugout, sender)
525 for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
526 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
527 re.MULTILINE)
528 self.assertRegex(debugout, to_addr)
529
530 def testSendMessageMultipleResentRaises(self):
531 m = email.mime.text.MIMEText('A test message')
532 m['From'] = 'foo@bar.com'
533 m['To'] = 'John'
534 m['CC'] = 'Sally, Fred'
535 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
536 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
537 m['Resent-From'] = 'holy@grail.net'
538 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
539 m['Resent-Bcc'] = 'doe@losthope.net'
540 m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
541 m['Resent-To'] = 'holy@grail.net'
542 m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
543 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
544 with self.assertRaises(ValueError):
545 smtp.send_message(m)
546 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000547
Victor Stinner45df8202010-04-28 22:31:17 +0000548class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000549
550 def testNotConnected(self):
551 # Test various operations on an unconnected SMTP object that
552 # should raise exceptions (at present the attempt in SMTP.send
553 # to reference the nonexistent 'sock' attribute of the SMTP object
554 # causes an AttributeError)
555 smtp = smtplib.SMTP()
556 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
557 self.assertRaises(smtplib.SMTPServerDisconnected,
558 smtp.send, 'test msg')
559
560 def testNonnumericPort(self):
Andrew Svetlov0832af62012-12-18 23:10:48 +0200561 # check that non-numeric port raises OSError
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200562 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000563 "localhost", "bogus")
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200564 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000565 "localhost:bogus")
566
567
Guido van Rossum04110fb2007-08-24 16:32:05 +0000568# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000569@unittest.skipUnless(threading, 'Threading required for this test.')
570class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000571
572 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000573 smtplib.socket = mock_socket
574 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000575 self.old_stdout = sys.stdout
576 self.output = io.StringIO()
577 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000578 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000579
580 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000581 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000582 sys.stdout = self.old_stdout
583
584 def testFailingHELO(self):
585 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000586 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000587
Guido van Rossum04110fb2007-08-24 16:32:05 +0000588
Georg Brandlb38b5c42014-02-10 22:11:21 +0100589@unittest.skipUnless(threading, 'Threading required for this test.')
590class TooLongLineTests(unittest.TestCase):
591 respdata = b'250 OK' + (b'.' * smtplib._MAXLINE * 2) + b'\n'
592
593 def setUp(self):
594 self.old_stdout = sys.stdout
595 self.output = io.StringIO()
596 sys.stdout = self.output
597
598 self.evt = threading.Event()
599 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
600 self.sock.settimeout(15)
601 self.port = support.bind_port(self.sock)
602 servargs = (self.evt, self.respdata, self.sock)
603 threading.Thread(target=server, args=servargs).start()
604 self.evt.wait()
605 self.evt.clear()
606
607 def tearDown(self):
608 self.evt.wait()
609 sys.stdout = self.old_stdout
610
611 def testLineTooLong(self):
612 self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
613 HOST, self.port, 'localhost', 3)
614
615
Guido van Rossum04110fb2007-08-24 16:32:05 +0000616sim_users = {'Mr.A@somewhere.com':'John A',
R David Murray46346762011-07-18 21:38:54 -0400617 'Ms.B@xn--fo-fka.com':'Sally B',
Guido van Rossum04110fb2007-08-24 16:32:05 +0000618 'Mrs.C@somewhereesle.com':'Ruth C',
619 }
620
R. David Murraycaa27b72009-05-23 18:49:56 +0000621sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000622sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
623 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
624sim_auth_credentials = {
625 'login': 'TXIuQUBzb21ld2hlcmUuY29t',
626 'plain': 'AE1yLkFAc29tZXdoZXJlLmNvbQBzb21lcGFzc3dvcmQ=',
627 'cram-md5': ('TXIUQUBZB21LD2HLCMUUY29TIDG4OWQ0MJ'
628 'KWZGQ4ODNMNDA4NTGXMDRLZWMYZJDMODG1'),
629 }
R David Murray76e13c12014-07-03 14:47:46 -0400630sim_auth_login_user = 'TXIUQUBZB21LD2HLCMUUY29T'
631sim_auth_plain = 'AE1YLKFAC29TZXDOZXJLLMNVBQBZB21LCGFZC3DVCMQ='
R. David Murraycaa27b72009-05-23 18:49:56 +0000632
Guido van Rossum04110fb2007-08-24 16:32:05 +0000633sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
R David Murray46346762011-07-18 21:38:54 -0400634 'list-2':['Ms.B@xn--fo-fka.com',],
Guido van Rossum04110fb2007-08-24 16:32:05 +0000635 }
636
637# Simulated SMTP channel & server
638class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000639
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400640 quit_response = None
R David Murrayd312c742013-03-20 20:36:14 -0400641 mail_response = None
642 rcpt_response = None
643 data_response = None
644 rcpt_count = 0
645 rset_count = 0
R David Murrayafb151a2014-04-14 18:21:38 -0400646 disconnect = 0
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400647
R. David Murray23ddc0e2009-05-29 18:03:16 +0000648 def __init__(self, extra_features, *args, **kw):
649 self._extrafeatures = ''.join(
650 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000651 super(SimSMTPChannel, self).__init__(*args, **kw)
652
Guido van Rossum04110fb2007-08-24 16:32:05 +0000653 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000654 resp = ('250-testhost\r\n'
655 '250-EXPN\r\n'
656 '250-SIZE 20000000\r\n'
657 '250-STARTTLS\r\n'
658 '250-DELIVERBY\r\n')
659 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000660 self.push(resp)
R David Murrayf1a40b42013-03-20 21:12:17 -0400661 self.seen_greeting = arg
662 self.extended_smtp = True
Guido van Rossum04110fb2007-08-24 16:32:05 +0000663
664 def smtp_VRFY(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400665 # For max compatibility smtplib should be sending the raw address.
666 if arg in sim_users:
667 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000668 else:
669 self.push('550 No such user: %s' % arg)
670
671 def smtp_EXPN(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400672 list_name = arg.lower()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000673 if list_name in sim_lists:
674 user_list = sim_lists[list_name]
675 for n, user_email in enumerate(user_list):
676 quoted_addr = smtplib.quoteaddr(user_email)
677 if n < len(user_list) - 1:
678 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
679 else:
680 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
681 else:
682 self.push('550 No access for you!')
683
R. David Murraycaa27b72009-05-23 18:49:56 +0000684 def smtp_AUTH(self, arg):
R David Murray76e13c12014-07-03 14:47:46 -0400685 mech = arg.strip().lower()
686 if mech=='cram-md5':
R. David Murrayfb123912009-05-28 18:19:00 +0000687 self.push('334 {}'.format(sim_cram_md5_challenge))
R David Murray76e13c12014-07-03 14:47:46 -0400688 elif mech not in sim_auth_credentials:
R. David Murraycaa27b72009-05-23 18:49:56 +0000689 self.push('504 auth type unimplemented')
R. David Murrayfb123912009-05-28 18:19:00 +0000690 return
R David Murray76e13c12014-07-03 14:47:46 -0400691 elif mech=='plain':
692 self.push('334 ')
693 elif mech=='login':
694 self.push('334 ')
R. David Murrayfb123912009-05-28 18:19:00 +0000695 else:
696 self.push('550 No access for you!')
R. David Murraycaa27b72009-05-23 18:49:56 +0000697
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400698 def smtp_QUIT(self, arg):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400699 if self.quit_response is None:
700 super(SimSMTPChannel, self).smtp_QUIT(arg)
701 else:
702 self.push(self.quit_response)
703 self.close_when_done()
704
R David Murrayd312c742013-03-20 20:36:14 -0400705 def smtp_MAIL(self, arg):
706 if self.mail_response is None:
707 super().smtp_MAIL(arg)
708 else:
709 self.push(self.mail_response)
R David Murrayafb151a2014-04-14 18:21:38 -0400710 if self.disconnect:
711 self.close_when_done()
R David Murrayd312c742013-03-20 20:36:14 -0400712
713 def smtp_RCPT(self, arg):
714 if self.rcpt_response is None:
715 super().smtp_RCPT(arg)
716 return
R David Murrayd312c742013-03-20 20:36:14 -0400717 self.rcpt_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400718 self.push(self.rcpt_response[self.rcpt_count-1])
R David Murrayd312c742013-03-20 20:36:14 -0400719
720 def smtp_RSET(self, arg):
R David Murrayd312c742013-03-20 20:36:14 -0400721 self.rset_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400722 super().smtp_RSET(arg)
R David Murrayd312c742013-03-20 20:36:14 -0400723
724 def smtp_DATA(self, arg):
725 if self.data_response is None:
726 super().smtp_DATA(arg)
727 else:
728 self.push(self.data_response)
729
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000730 def handle_error(self):
731 raise
732
Guido van Rossum04110fb2007-08-24 16:32:05 +0000733
734class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000735
R David Murrayd312c742013-03-20 20:36:14 -0400736 channel_class = SimSMTPChannel
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400737
R. David Murray23ddc0e2009-05-29 18:03:16 +0000738 def __init__(self, *args, **kw):
739 self._extra_features = []
740 smtpd.SMTPServer.__init__(self, *args, **kw)
741
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000742 def handle_accepted(self, conn, addr):
R David Murrayf1a40b42013-03-20 21:12:17 -0400743 self._SMTPchannel = self.channel_class(
R David Murray1144da52014-06-11 12:27:40 -0400744 self._extra_features, self, conn, addr,
745 decode_data=self._decode_data)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000746
747 def process_message(self, peer, mailfrom, rcpttos, data):
748 pass
749
R. David Murrayfb123912009-05-28 18:19:00 +0000750 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000751 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000752
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000753 def handle_error(self):
754 raise
755
Guido van Rossum04110fb2007-08-24 16:32:05 +0000756
757# Test various SMTP & ESMTP commands/behaviors that require a simulated server
758# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000759@unittest.skipUnless(threading, 'Threading required for this test.')
760class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000761
762 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000763 self.real_getfqdn = socket.getfqdn
764 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000765 self.serv_evt = threading.Event()
766 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000767 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400768 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1), decode_data=True)
Antoine Pitrou043bad02010-04-30 23:20:15 +0000769 # Keep a note of what port was assigned
770 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000771 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000772 self.thread = threading.Thread(target=debugging_server, args=serv_args)
773 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000774
775 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000776 self.serv_evt.wait()
777 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000778
779 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000780 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000781 # indicate that the client is finished
782 self.client_evt.set()
783 # wait for the server thread to terminate
784 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000785 self.thread.join()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000786
787 def testBasic(self):
788 # smoke test
Christian Heimes5e696852008-04-09 08:37:03 +0000789 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000790 smtp.quit()
791
792 def testEHLO(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000793 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000794
795 # no features should be present before the EHLO
796 self.assertEqual(smtp.esmtp_features, {})
797
798 # features expected from the test server
799 expected_features = {'expn':'',
800 'size': '20000000',
801 'starttls': '',
802 'deliverby': '',
803 'help': '',
804 }
805
806 smtp.ehlo()
807 self.assertEqual(smtp.esmtp_features, expected_features)
808 for k in expected_features:
809 self.assertTrue(smtp.has_extn(k))
810 self.assertFalse(smtp.has_extn('unsupported-feature'))
811 smtp.quit()
812
813 def testVRFY(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000814 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000815
816 for email, name in sim_users.items():
817 expected_known = (250, bytes('%s %s' %
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000818 (name, smtplib.quoteaddr(email)),
819 "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000820 self.assertEqual(smtp.vrfy(email), expected_known)
821
822 u = 'nobody@nowhere.com'
R David Murray46346762011-07-18 21:38:54 -0400823 expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000824 self.assertEqual(smtp.vrfy(u), expected_unknown)
825 smtp.quit()
826
827 def testEXPN(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000828 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000829
830 for listname, members in sim_lists.items():
831 users = []
832 for m in members:
833 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000834 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000835 self.assertEqual(smtp.expn(listname), expected_known)
836
837 u = 'PSU-Members-List'
838 expected_unknown = (550, b'No access for you!')
839 self.assertEqual(smtp.expn(u), expected_unknown)
840 smtp.quit()
841
R David Murray76e13c12014-07-03 14:47:46 -0400842 # SimSMTPChannel doesn't fully support AUTH because it requires a
843 # synchronous read to obtain the credentials...so instead smtpd
R. David Murrayfb123912009-05-28 18:19:00 +0000844 # sees the credential sent by smtplib's login method as an unknown command,
845 # which results in smtplib raising an auth error. Fortunately the error
846 # message contains the encoded credential, so we can partially check that it
847 # was generated correctly (partially, because the 'word' is uppercased in
848 # the error message).
849
R David Murray76e13c12014-07-03 14:47:46 -0400850 def testAUTH_PLAIN(self):
851 self.serv.add_feature("AUTH PLAIN")
852 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
853 try: smtp.login(sim_auth[0], sim_auth[1])
854 except smtplib.SMTPAuthenticationError as err:
855 self.assertIn(sim_auth_plain, str(err))
856 smtp.close()
857
R. David Murrayfb123912009-05-28 18:19:00 +0000858 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000859 self.serv.add_feature("AUTH LOGIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000860 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000861 try: smtp.login(sim_auth[0], sim_auth[1])
862 except smtplib.SMTPAuthenticationError as err:
R David Murray76e13c12014-07-03 14:47:46 -0400863 self.assertIn(sim_auth_login_user, str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000864 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000865
866 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000867 self.serv.add_feature("AUTH CRAM-MD5")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000868 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000869
870 try: smtp.login(sim_auth[0], sim_auth[1])
871 except smtplib.SMTPAuthenticationError as err:
Benjamin Peterson95951662010-10-31 17:59:20 +0000872 self.assertIn(sim_auth_credentials['cram-md5'], str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000873 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000874
Andrew Kuchling78591822013-11-11 14:03:23 -0500875 def testAUTH_multiple(self):
876 # Test that multiple authentication methods are tried.
877 self.serv.add_feature("AUTH BOGUS PLAIN LOGIN CRAM-MD5")
878 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
879 try: smtp.login(sim_auth[0], sim_auth[1])
880 except smtplib.SMTPAuthenticationError as err:
R David Murray76e13c12014-07-03 14:47:46 -0400881 self.assertIn(sim_auth_login_user, str(err))
882 smtp.close()
883
884 def test_auth_function(self):
885 smtp = smtplib.SMTP(HOST, self.port,
886 local_hostname='localhost', timeout=15)
887 self.serv.add_feature("AUTH CRAM-MD5")
888 smtp.user, smtp.password = sim_auth[0], sim_auth[1]
889 supported = {'CRAM-MD5': smtp.auth_cram_md5,
890 'PLAIN': smtp.auth_plain,
891 'LOGIN': smtp.auth_login,
892 }
893 for mechanism, method in supported.items():
894 try: smtp.auth(mechanism, method)
895 except smtplib.SMTPAuthenticationError as err:
896 self.assertIn(sim_auth_credentials[mechanism.lower()].upper(),
897 str(err))
Andrew Kuchling78591822013-11-11 14:03:23 -0500898 smtp.close()
899
R David Murray0cff49f2014-08-30 16:51:59 -0400900 def test_quit_resets_greeting(self):
901 smtp = smtplib.SMTP(HOST, self.port,
902 local_hostname='localhost',
903 timeout=15)
904 code, message = smtp.ehlo()
905 self.assertEqual(code, 250)
906 self.assertIn('size', smtp.esmtp_features)
907 smtp.quit()
908 self.assertNotIn('size', smtp.esmtp_features)
909 smtp.connect(HOST, self.port)
910 self.assertNotIn('size', smtp.esmtp_features)
911 smtp.ehlo_or_helo_if_needed()
912 self.assertIn('size', smtp.esmtp_features)
913 smtp.quit()
914
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400915 def test_with_statement(self):
916 with smtplib.SMTP(HOST, self.port) as smtp:
917 code, message = smtp.noop()
918 self.assertEqual(code, 250)
919 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
920 with smtplib.SMTP(HOST, self.port) as smtp:
921 smtp.close()
922 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
923
924 def test_with_statement_QUIT_failure(self):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400925 with self.assertRaises(smtplib.SMTPResponseException) as error:
926 with smtplib.SMTP(HOST, self.port) as smtp:
927 smtp.noop()
R David Murray6bd52022013-03-21 00:32:31 -0400928 self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400929 self.assertEqual(error.exception.smtp_code, 421)
930 self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400931
R. David Murrayfb123912009-05-28 18:19:00 +0000932 #TODO: add tests for correct AUTH method fallback now that the
933 #test infrastructure can support it.
934
R David Murrayafb151a2014-04-14 18:21:38 -0400935 # Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception
936 def test__rest_from_mail_cmd(self):
937 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
938 smtp.noop()
939 self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
940 self.serv._SMTPchannel.disconnect = True
941 with self.assertRaises(smtplib.SMTPSenderRefused):
942 smtp.sendmail('John', 'Sally', 'test message')
943 self.assertIsNone(smtp.sock)
944
R David Murrayd312c742013-03-20 20:36:14 -0400945 # Issue 5713: make sure close, not rset, is called if we get a 421 error
946 def test_421_from_mail_cmd(self):
947 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -0400948 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -0400949 self.serv._SMTPchannel.mail_response = '421 closing connection'
950 with self.assertRaises(smtplib.SMTPSenderRefused):
951 smtp.sendmail('John', 'Sally', 'test message')
952 self.assertIsNone(smtp.sock)
R David Murray03b01162013-03-20 22:11:40 -0400953 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
R David Murrayd312c742013-03-20 20:36:14 -0400954
955 def test_421_from_rcpt_cmd(self):
956 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -0400957 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -0400958 self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
959 with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
960 smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
961 self.assertIsNone(smtp.sock)
962 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
963 self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
964
965 def test_421_from_data_cmd(self):
966 class MySimSMTPChannel(SimSMTPChannel):
967 def found_terminator(self):
968 if self.smtp_state == self.DATA:
969 self.push('421 closing')
970 else:
971 super().found_terminator()
972 self.serv.channel_class = MySimSMTPChannel
973 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -0400974 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -0400975 with self.assertRaises(smtplib.SMTPDataError):
976 smtp.sendmail('John@foo.org', ['Sally@foo.org'], 'test message')
977 self.assertIsNone(smtp.sock)
978 self.assertEqual(self.serv._SMTPchannel.rcpt_count, 0)
979
Guido van Rossum04110fb2007-08-24 16:32:05 +0000980
Antoine Pitroud54fa552011-08-28 01:23:52 +0200981@support.reap_threads
Guido van Rossumd8faa362007-04-27 19:54:29 +0000982def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000983 support.run_unittest(GeneralTests, DebuggingServerTests,
Christian Heimes380f7f22008-02-28 11:19:05 +0000984 NonConnectingTests,
Georg Brandlb38b5c42014-02-10 22:11:21 +0100985 BadHELOServerTests, SMTPSimTests,
986 TooLongLineTests)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000987
988if __name__ == '__main__':
989 test_main()