blob: 5f12d28eeafe21cc147816c2007689ab645fe0e5 [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
127
Guido van Rossum04110fb2007-08-24 16:32:05 +0000128# Test server thread using the specified SMTP server class
Christian Heimes5e696852008-04-09 08:37:03 +0000129def debugging_server(serv, serv_evt, client_evt):
Christian Heimes380f7f22008-02-28 11:19:05 +0000130 serv_evt.set()
Guido van Rossum806c2462007-08-06 23:33:07 +0000131
132 try:
133 if hasattr(select, 'poll'):
134 poll_fun = asyncore.poll2
135 else:
136 poll_fun = asyncore.poll
137
138 n = 1000
139 while asyncore.socket_map and n > 0:
140 poll_fun(0.01, asyncore.socket_map)
141
142 # when the client conversation is finished, it will
143 # set client_evt, and it's then ok to kill the server
Benjamin Peterson672b8032008-06-11 19:14:14 +0000144 if client_evt.is_set():
Guido van Rossum806c2462007-08-06 23:33:07 +0000145 serv.close()
146 break
147
148 n -= 1
149
150 except socket.timeout:
151 pass
152 finally:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000153 if not client_evt.is_set():
Christian Heimes380f7f22008-02-28 11:19:05 +0000154 # allow some time for the client to read the result
155 time.sleep(0.5)
156 serv.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000157 asyncore.close_all()
Guido van Rossum806c2462007-08-06 23:33:07 +0000158 serv_evt.set()
159
160MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
161MSG_END = '------------ END MESSAGE ------------\n'
162
Guido van Rossum04110fb2007-08-24 16:32:05 +0000163# NOTE: Some SMTP objects in the tests below are created with a non-default
164# local_hostname argument to the constructor, since (on some systems) the FQDN
165# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000166# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000167
168# Test behavior of smtpd.DebuggingServer
Victor Stinner45df8202010-04-28 22:31:17 +0000169@unittest.skipUnless(threading, 'Threading required for this test.')
170class DebuggingServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000171
R. David Murray7dff9e02010-11-08 17:15:13 +0000172 maxDiff = None
173
Guido van Rossum806c2462007-08-06 23:33:07 +0000174 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000175 self.real_getfqdn = socket.getfqdn
176 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000177 # temporarily replace sys.stdout to capture DebuggingServer output
178 self.old_stdout = sys.stdout
179 self.output = io.StringIO()
180 sys.stdout = self.output
181
182 self.serv_evt = threading.Event()
183 self.client_evt = threading.Event()
R. David Murray7dff9e02010-11-08 17:15:13 +0000184 # Capture SMTPChannel debug output
185 self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
186 smtpd.DEBUGSTREAM = io.StringIO()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000187 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400188 self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1),
189 decode_data=True)
Antoine Pitrou043bad02010-04-30 23:20:15 +0000190 # Keep a note of what port was assigned
191 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000192 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000193 self.thread = threading.Thread(target=debugging_server, args=serv_args)
194 self.thread.start()
Guido van Rossum806c2462007-08-06 23:33:07 +0000195
196 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000197 self.serv_evt.wait()
198 self.serv_evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000199
200 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000201 socket.getfqdn = self.real_getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000202 # indicate that the client is finished
203 self.client_evt.set()
204 # wait for the server thread to terminate
205 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000206 self.thread.join()
Guido van Rossum806c2462007-08-06 23:33:07 +0000207 # restore sys.stdout
208 sys.stdout = self.old_stdout
R. David Murray7dff9e02010-11-08 17:15:13 +0000209 # restore DEBUGSTREAM
210 smtpd.DEBUGSTREAM.close()
211 smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
Guido van Rossum806c2462007-08-06 23:33:07 +0000212
213 def testBasic(self):
214 # connect
Christian Heimes5e696852008-04-09 08:37:03 +0000215 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000216 smtp.quit()
217
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800218 def testSourceAddress(self):
219 # connect
Senthil Kumaranb351a482011-07-31 09:14:17 +0800220 port = support.find_unused_port()
221 try:
222 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
223 timeout=3, source_address=('127.0.0.1', port))
224 self.assertEqual(smtp.source_address, ('127.0.0.1', port))
225 self.assertEqual(smtp.local_hostname, 'localhost')
226 smtp.quit()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200227 except OSError as e:
Senthil Kumaranb351a482011-07-31 09:14:17 +0800228 if e.errno == errno.EADDRINUSE:
229 self.skipTest("couldn't bind to port %d" % port)
230 raise
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800231
Guido van Rossum04110fb2007-08-24 16:32:05 +0000232 def testNOOP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000233 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400234 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000235 self.assertEqual(smtp.noop(), expected)
236 smtp.quit()
237
238 def testRSET(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000239 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400240 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000241 self.assertEqual(smtp.rset(), expected)
242 smtp.quit()
243
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400244 def testELHO(self):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000245 # EHLO isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000246 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400247 expected = (250, b'\nSIZE 33554432\nHELP')
Guido van Rossum806c2462007-08-06 23:33:07 +0000248 self.assertEqual(smtp.ehlo(), expected)
249 smtp.quit()
250
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400251 def testEXPNNotImplemented(self):
R David Murrayd1a30c92012-05-26 14:33:59 -0400252 # EXPN isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000253 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400254 expected = (502, b'EXPN not implemented')
255 smtp.putcmd('EXPN')
256 self.assertEqual(smtp.getreply(), expected)
257 smtp.quit()
258
259 def testVRFY(self):
260 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
261 expected = (252, b'Cannot VRFY user, but will accept message ' + \
262 b'and attempt delivery')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000263 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
264 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
265 smtp.quit()
266
267 def testSecondHELO(self):
268 # check that a second HELO returns a message that it's a duplicate
269 # (this behavior is specific to smtpd.SMTPChannel)
Christian Heimes5e696852008-04-09 08:37:03 +0000270 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000271 smtp.helo()
272 expected = (503, b'Duplicate HELO/EHLO')
273 self.assertEqual(smtp.helo(), expected)
274 smtp.quit()
275
Guido van Rossum806c2462007-08-06 23:33:07 +0000276 def testHELP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000277 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400278 self.assertEqual(smtp.help(), b'Supported commands: EHLO HELO MAIL ' + \
279 b'RCPT DATA RSET NOOP QUIT VRFY')
Guido van Rossum806c2462007-08-06 23:33:07 +0000280 smtp.quit()
281
282 def testSend(self):
283 # connect and send mail
284 m = 'A test message'
Christian Heimes5e696852008-04-09 08:37:03 +0000285 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000286 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000287 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
288 # in asyncore. This sleep might help, but should really be fixed
289 # properly by using an Event variable.
290 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000291 smtp.quit()
292
293 self.client_evt.set()
294 self.serv_evt.wait()
295 self.output.flush()
296 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
297 self.assertEqual(self.output.getvalue(), mexpect)
298
R. David Murray7dff9e02010-11-08 17:15:13 +0000299 def testSendBinary(self):
300 m = b'A test message'
301 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
302 smtp.sendmail('John', 'Sally', m)
303 # XXX (see comment in testSend)
304 time.sleep(0.01)
305 smtp.quit()
306
307 self.client_evt.set()
308 self.serv_evt.wait()
309 self.output.flush()
310 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
311 self.assertEqual(self.output.getvalue(), mexpect)
312
R David Murray0f663d02011-06-09 15:05:57 -0400313 def testSendNeedingDotQuote(self):
314 # Issue 12283
315 m = '.A test\n.mes.sage.'
316 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
317 smtp.sendmail('John', 'Sally', m)
318 # XXX (see comment in testSend)
319 time.sleep(0.01)
320 smtp.quit()
321
322 self.client_evt.set()
323 self.serv_evt.wait()
324 self.output.flush()
325 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
326 self.assertEqual(self.output.getvalue(), mexpect)
327
R David Murray46346762011-07-18 21:38:54 -0400328 def testSendNullSender(self):
329 m = 'A test message'
330 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
331 smtp.sendmail('<>', 'Sally', m)
332 # XXX (see comment in testSend)
333 time.sleep(0.01)
334 smtp.quit()
335
336 self.client_evt.set()
337 self.serv_evt.wait()
338 self.output.flush()
339 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
340 self.assertEqual(self.output.getvalue(), mexpect)
341 debugout = smtpd.DEBUGSTREAM.getvalue()
342 sender = re.compile("^sender: <>$", re.MULTILINE)
343 self.assertRegex(debugout, sender)
344
R. David Murray7dff9e02010-11-08 17:15:13 +0000345 def testSendMessage(self):
346 m = email.mime.text.MIMEText('A test message')
347 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
348 smtp.send_message(m, from_addr='John', to_addrs='Sally')
349 # XXX (see comment in testSend)
350 time.sleep(0.01)
351 smtp.quit()
352
353 self.client_evt.set()
354 self.serv_evt.wait()
355 self.output.flush()
356 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400357 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000358 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
359 self.assertEqual(self.output.getvalue(), mexpect)
360
361 def testSendMessageWithAddresses(self):
362 m = email.mime.text.MIMEText('A test message')
363 m['From'] = 'foo@bar.com'
364 m['To'] = 'John'
365 m['CC'] = 'Sally, Fred'
366 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
367 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
368 smtp.send_message(m)
369 # XXX (see comment in testSend)
370 time.sleep(0.01)
371 smtp.quit()
R David Murrayac4e5ab2011-07-02 21:03:19 -0400372 # make sure the Bcc header is still in the message.
373 self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
374 '<warped@silly.walks.com>')
R. David Murray7dff9e02010-11-08 17:15:13 +0000375
376 self.client_evt.set()
377 self.serv_evt.wait()
378 self.output.flush()
379 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400380 m['X-Peer'] = socket.gethostbyname('localhost')
R David Murrayac4e5ab2011-07-02 21:03:19 -0400381 # The Bcc header should not be transmitted.
R. David Murray7dff9e02010-11-08 17:15:13 +0000382 del m['Bcc']
383 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
384 self.assertEqual(self.output.getvalue(), mexpect)
385 debugout = smtpd.DEBUGSTREAM.getvalue()
386 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000387 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000388 for addr in ('John', 'Sally', 'Fred', 'root@localhost',
389 'warped@silly.walks.com'):
390 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
391 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000392 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000393
394 def testSendMessageWithSomeAddresses(self):
395 # Make sure nothing breaks if not all of the three 'to' headers exist
396 m = email.mime.text.MIMEText('A test message')
397 m['From'] = 'foo@bar.com'
398 m['To'] = 'John, Dinsdale'
399 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
400 smtp.send_message(m)
401 # XXX (see comment in testSend)
402 time.sleep(0.01)
403 smtp.quit()
404
405 self.client_evt.set()
406 self.serv_evt.wait()
407 self.output.flush()
408 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400409 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000410 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
411 self.assertEqual(self.output.getvalue(), mexpect)
412 debugout = smtpd.DEBUGSTREAM.getvalue()
413 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000414 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000415 for addr in ('John', 'Dinsdale'):
416 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
417 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000418 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000419
R David Murrayac4e5ab2011-07-02 21:03:19 -0400420 def testSendMessageWithSpecifiedAddresses(self):
421 # Make sure addresses specified in call override those in message.
422 m = email.mime.text.MIMEText('A test message')
423 m['From'] = 'foo@bar.com'
424 m['To'] = 'John, Dinsdale'
425 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
426 smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
427 # XXX (see comment in testSend)
428 time.sleep(0.01)
429 smtp.quit()
430
431 self.client_evt.set()
432 self.serv_evt.wait()
433 self.output.flush()
434 # Add the X-Peer header that DebuggingServer adds
435 m['X-Peer'] = socket.gethostbyname('localhost')
436 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
437 self.assertEqual(self.output.getvalue(), mexpect)
438 debugout = smtpd.DEBUGSTREAM.getvalue()
439 sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
440 self.assertRegex(debugout, sender)
441 for addr in ('John', 'Dinsdale'):
442 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
443 re.MULTILINE)
444 self.assertNotRegex(debugout, to_addr)
445 recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
446 self.assertRegex(debugout, recip)
447
448 def testSendMessageWithMultipleFrom(self):
449 # Sender overrides To
450 m = email.mime.text.MIMEText('A test message')
451 m['From'] = 'Bernard, Bianca'
452 m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com'
453 m['To'] = 'John, Dinsdale'
454 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
455 smtp.send_message(m)
456 # XXX (see comment in testSend)
457 time.sleep(0.01)
458 smtp.quit()
459
460 self.client_evt.set()
461 self.serv_evt.wait()
462 self.output.flush()
463 # Add the X-Peer header that DebuggingServer adds
464 m['X-Peer'] = socket.gethostbyname('localhost')
465 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
466 self.assertEqual(self.output.getvalue(), mexpect)
467 debugout = smtpd.DEBUGSTREAM.getvalue()
468 sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
469 self.assertRegex(debugout, sender)
470 for addr in ('John', 'Dinsdale'):
471 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
472 re.MULTILINE)
473 self.assertRegex(debugout, to_addr)
474
475 def testSendMessageResent(self):
476 m = email.mime.text.MIMEText('A test message')
477 m['From'] = 'foo@bar.com'
478 m['To'] = 'John'
479 m['CC'] = 'Sally, Fred'
480 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
481 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
482 m['Resent-From'] = 'holy@grail.net'
483 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
484 m['Resent-Bcc'] = 'doe@losthope.net'
485 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
486 smtp.send_message(m)
487 # XXX (see comment in testSend)
488 time.sleep(0.01)
489 smtp.quit()
490
491 self.client_evt.set()
492 self.serv_evt.wait()
493 self.output.flush()
494 # The Resent-Bcc headers are deleted before serialization.
495 del m['Bcc']
496 del m['Resent-Bcc']
497 # Add the X-Peer header that DebuggingServer adds
498 m['X-Peer'] = socket.gethostbyname('localhost')
499 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
500 self.assertEqual(self.output.getvalue(), mexpect)
501 debugout = smtpd.DEBUGSTREAM.getvalue()
502 sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
503 self.assertRegex(debugout, sender)
504 for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
505 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
506 re.MULTILINE)
507 self.assertRegex(debugout, to_addr)
508
509 def testSendMessageMultipleResentRaises(self):
510 m = email.mime.text.MIMEText('A test message')
511 m['From'] = 'foo@bar.com'
512 m['To'] = 'John'
513 m['CC'] = 'Sally, Fred'
514 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
515 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
516 m['Resent-From'] = 'holy@grail.net'
517 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
518 m['Resent-Bcc'] = 'doe@losthope.net'
519 m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
520 m['Resent-To'] = 'holy@grail.net'
521 m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
522 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
523 with self.assertRaises(ValueError):
524 smtp.send_message(m)
525 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000526
Victor Stinner45df8202010-04-28 22:31:17 +0000527class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000528
529 def testNotConnected(self):
530 # Test various operations on an unconnected SMTP object that
531 # should raise exceptions (at present the attempt in SMTP.send
532 # to reference the nonexistent 'sock' attribute of the SMTP object
533 # causes an AttributeError)
534 smtp = smtplib.SMTP()
535 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
536 self.assertRaises(smtplib.SMTPServerDisconnected,
537 smtp.send, 'test msg')
538
539 def testNonnumericPort(self):
Andrew Svetlov0832af62012-12-18 23:10:48 +0200540 # check that non-numeric port raises OSError
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200541 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000542 "localhost", "bogus")
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200543 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000544 "localhost:bogus")
545
546
Guido van Rossum04110fb2007-08-24 16:32:05 +0000547# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000548@unittest.skipUnless(threading, 'Threading required for this test.')
549class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000550
551 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000552 smtplib.socket = mock_socket
553 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000554 self.old_stdout = sys.stdout
555 self.output = io.StringIO()
556 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000557 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000558
559 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000560 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000561 sys.stdout = self.old_stdout
562
563 def testFailingHELO(self):
564 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000565 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000566
Guido van Rossum04110fb2007-08-24 16:32:05 +0000567
Georg Brandlb38b5c42014-02-10 22:11:21 +0100568@unittest.skipUnless(threading, 'Threading required for this test.')
569class TooLongLineTests(unittest.TestCase):
570 respdata = b'250 OK' + (b'.' * smtplib._MAXLINE * 2) + b'\n'
571
572 def setUp(self):
573 self.old_stdout = sys.stdout
574 self.output = io.StringIO()
575 sys.stdout = self.output
576
577 self.evt = threading.Event()
578 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
579 self.sock.settimeout(15)
580 self.port = support.bind_port(self.sock)
581 servargs = (self.evt, self.respdata, self.sock)
582 threading.Thread(target=server, args=servargs).start()
583 self.evt.wait()
584 self.evt.clear()
585
586 def tearDown(self):
587 self.evt.wait()
588 sys.stdout = self.old_stdout
589
590 def testLineTooLong(self):
591 self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
592 HOST, self.port, 'localhost', 3)
593
594
Guido van Rossum04110fb2007-08-24 16:32:05 +0000595sim_users = {'Mr.A@somewhere.com':'John A',
R David Murray46346762011-07-18 21:38:54 -0400596 'Ms.B@xn--fo-fka.com':'Sally B',
Guido van Rossum04110fb2007-08-24 16:32:05 +0000597 'Mrs.C@somewhereesle.com':'Ruth C',
598 }
599
R. David Murraycaa27b72009-05-23 18:49:56 +0000600sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000601sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
602 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
603sim_auth_credentials = {
604 'login': 'TXIuQUBzb21ld2hlcmUuY29t',
605 'plain': 'AE1yLkFAc29tZXdoZXJlLmNvbQBzb21lcGFzc3dvcmQ=',
606 'cram-md5': ('TXIUQUBZB21LD2HLCMUUY29TIDG4OWQ0MJ'
607 'KWZGQ4ODNMNDA4NTGXMDRLZWMYZJDMODG1'),
608 }
R David Murray76e13c12014-07-03 14:47:46 -0400609sim_auth_login_user = 'TXIUQUBZB21LD2HLCMUUY29T'
610sim_auth_plain = 'AE1YLKFAC29TZXDOZXJLLMNVBQBZB21LCGFZC3DVCMQ='
R. David Murraycaa27b72009-05-23 18:49:56 +0000611
Guido van Rossum04110fb2007-08-24 16:32:05 +0000612sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
R David Murray46346762011-07-18 21:38:54 -0400613 'list-2':['Ms.B@xn--fo-fka.com',],
Guido van Rossum04110fb2007-08-24 16:32:05 +0000614 }
615
616# Simulated SMTP channel & server
617class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000618
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400619 quit_response = None
R David Murrayd312c742013-03-20 20:36:14 -0400620 mail_response = None
621 rcpt_response = None
622 data_response = None
623 rcpt_count = 0
624 rset_count = 0
R David Murrayafb151a2014-04-14 18:21:38 -0400625 disconnect = 0
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400626
R. David Murray23ddc0e2009-05-29 18:03:16 +0000627 def __init__(self, extra_features, *args, **kw):
628 self._extrafeatures = ''.join(
629 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000630 super(SimSMTPChannel, self).__init__(*args, **kw)
631
Guido van Rossum04110fb2007-08-24 16:32:05 +0000632 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000633 resp = ('250-testhost\r\n'
634 '250-EXPN\r\n'
635 '250-SIZE 20000000\r\n'
636 '250-STARTTLS\r\n'
637 '250-DELIVERBY\r\n')
638 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000639 self.push(resp)
R David Murrayf1a40b42013-03-20 21:12:17 -0400640 self.seen_greeting = arg
641 self.extended_smtp = True
Guido van Rossum04110fb2007-08-24 16:32:05 +0000642
643 def smtp_VRFY(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400644 # For max compatibility smtplib should be sending the raw address.
645 if arg in sim_users:
646 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000647 else:
648 self.push('550 No such user: %s' % arg)
649
650 def smtp_EXPN(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400651 list_name = arg.lower()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000652 if list_name in sim_lists:
653 user_list = sim_lists[list_name]
654 for n, user_email in enumerate(user_list):
655 quoted_addr = smtplib.quoteaddr(user_email)
656 if n < len(user_list) - 1:
657 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
658 else:
659 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
660 else:
661 self.push('550 No access for you!')
662
R. David Murraycaa27b72009-05-23 18:49:56 +0000663 def smtp_AUTH(self, arg):
R David Murray76e13c12014-07-03 14:47:46 -0400664 mech = arg.strip().lower()
665 if mech=='cram-md5':
R. David Murrayfb123912009-05-28 18:19:00 +0000666 self.push('334 {}'.format(sim_cram_md5_challenge))
R David Murray76e13c12014-07-03 14:47:46 -0400667 elif mech not in sim_auth_credentials:
R. David Murraycaa27b72009-05-23 18:49:56 +0000668 self.push('504 auth type unimplemented')
R. David Murrayfb123912009-05-28 18:19:00 +0000669 return
R David Murray76e13c12014-07-03 14:47:46 -0400670 elif mech=='plain':
671 self.push('334 ')
672 elif mech=='login':
673 self.push('334 ')
R. David Murrayfb123912009-05-28 18:19:00 +0000674 else:
675 self.push('550 No access for you!')
R. David Murraycaa27b72009-05-23 18:49:56 +0000676
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400677 def smtp_QUIT(self, arg):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400678 if self.quit_response is None:
679 super(SimSMTPChannel, self).smtp_QUIT(arg)
680 else:
681 self.push(self.quit_response)
682 self.close_when_done()
683
R David Murrayd312c742013-03-20 20:36:14 -0400684 def smtp_MAIL(self, arg):
685 if self.mail_response is None:
686 super().smtp_MAIL(arg)
687 else:
688 self.push(self.mail_response)
R David Murrayafb151a2014-04-14 18:21:38 -0400689 if self.disconnect:
690 self.close_when_done()
R David Murrayd312c742013-03-20 20:36:14 -0400691
692 def smtp_RCPT(self, arg):
693 if self.rcpt_response is None:
694 super().smtp_RCPT(arg)
695 return
R David Murrayd312c742013-03-20 20:36:14 -0400696 self.rcpt_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400697 self.push(self.rcpt_response[self.rcpt_count-1])
R David Murrayd312c742013-03-20 20:36:14 -0400698
699 def smtp_RSET(self, arg):
R David Murrayd312c742013-03-20 20:36:14 -0400700 self.rset_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400701 super().smtp_RSET(arg)
R David Murrayd312c742013-03-20 20:36:14 -0400702
703 def smtp_DATA(self, arg):
704 if self.data_response is None:
705 super().smtp_DATA(arg)
706 else:
707 self.push(self.data_response)
708
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000709 def handle_error(self):
710 raise
711
Guido van Rossum04110fb2007-08-24 16:32:05 +0000712
713class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000714
R David Murrayd312c742013-03-20 20:36:14 -0400715 channel_class = SimSMTPChannel
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400716
R. David Murray23ddc0e2009-05-29 18:03:16 +0000717 def __init__(self, *args, **kw):
718 self._extra_features = []
719 smtpd.SMTPServer.__init__(self, *args, **kw)
720
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000721 def handle_accepted(self, conn, addr):
R David Murrayf1a40b42013-03-20 21:12:17 -0400722 self._SMTPchannel = self.channel_class(
R David Murray1144da52014-06-11 12:27:40 -0400723 self._extra_features, self, conn, addr,
724 decode_data=self._decode_data)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000725
726 def process_message(self, peer, mailfrom, rcpttos, data):
727 pass
728
R. David Murrayfb123912009-05-28 18:19:00 +0000729 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000730 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000731
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000732 def handle_error(self):
733 raise
734
Guido van Rossum04110fb2007-08-24 16:32:05 +0000735
736# Test various SMTP & ESMTP commands/behaviors that require a simulated server
737# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000738@unittest.skipUnless(threading, 'Threading required for this test.')
739class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000740
741 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000742 self.real_getfqdn = socket.getfqdn
743 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000744 self.serv_evt = threading.Event()
745 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000746 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400747 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1), decode_data=True)
Antoine Pitrou043bad02010-04-30 23:20:15 +0000748 # Keep a note of what port was assigned
749 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000750 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000751 self.thread = threading.Thread(target=debugging_server, args=serv_args)
752 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000753
754 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000755 self.serv_evt.wait()
756 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000757
758 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000759 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000760 # indicate that the client is finished
761 self.client_evt.set()
762 # wait for the server thread to terminate
763 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000764 self.thread.join()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000765
766 def testBasic(self):
767 # smoke test
Christian Heimes5e696852008-04-09 08:37:03 +0000768 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000769 smtp.quit()
770
771 def testEHLO(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000772 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000773
774 # no features should be present before the EHLO
775 self.assertEqual(smtp.esmtp_features, {})
776
777 # features expected from the test server
778 expected_features = {'expn':'',
779 'size': '20000000',
780 'starttls': '',
781 'deliverby': '',
782 'help': '',
783 }
784
785 smtp.ehlo()
786 self.assertEqual(smtp.esmtp_features, expected_features)
787 for k in expected_features:
788 self.assertTrue(smtp.has_extn(k))
789 self.assertFalse(smtp.has_extn('unsupported-feature'))
790 smtp.quit()
791
792 def testVRFY(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 for email, name in sim_users.items():
796 expected_known = (250, bytes('%s %s' %
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000797 (name, smtplib.quoteaddr(email)),
798 "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000799 self.assertEqual(smtp.vrfy(email), expected_known)
800
801 u = 'nobody@nowhere.com'
R David Murray46346762011-07-18 21:38:54 -0400802 expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000803 self.assertEqual(smtp.vrfy(u), expected_unknown)
804 smtp.quit()
805
806 def testEXPN(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000807 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000808
809 for listname, members in sim_lists.items():
810 users = []
811 for m in members:
812 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000813 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000814 self.assertEqual(smtp.expn(listname), expected_known)
815
816 u = 'PSU-Members-List'
817 expected_unknown = (550, b'No access for you!')
818 self.assertEqual(smtp.expn(u), expected_unknown)
819 smtp.quit()
820
R David Murray76e13c12014-07-03 14:47:46 -0400821 # SimSMTPChannel doesn't fully support AUTH because it requires a
822 # synchronous read to obtain the credentials...so instead smtpd
R. David Murrayfb123912009-05-28 18:19:00 +0000823 # sees the credential sent by smtplib's login method as an unknown command,
824 # which results in smtplib raising an auth error. Fortunately the error
825 # message contains the encoded credential, so we can partially check that it
826 # was generated correctly (partially, because the 'word' is uppercased in
827 # the error message).
828
R David Murray76e13c12014-07-03 14:47:46 -0400829 def testAUTH_PLAIN(self):
830 self.serv.add_feature("AUTH PLAIN")
831 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
832 try: smtp.login(sim_auth[0], sim_auth[1])
833 except smtplib.SMTPAuthenticationError as err:
834 self.assertIn(sim_auth_plain, str(err))
835 smtp.close()
836
R. David Murrayfb123912009-05-28 18:19:00 +0000837 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000838 self.serv.add_feature("AUTH LOGIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000839 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000840 try: smtp.login(sim_auth[0], sim_auth[1])
841 except smtplib.SMTPAuthenticationError as err:
R David Murray76e13c12014-07-03 14:47:46 -0400842 self.assertIn(sim_auth_login_user, str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000843 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000844
845 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000846 self.serv.add_feature("AUTH CRAM-MD5")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000847 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000848
849 try: smtp.login(sim_auth[0], sim_auth[1])
850 except smtplib.SMTPAuthenticationError as err:
Benjamin Peterson95951662010-10-31 17:59:20 +0000851 self.assertIn(sim_auth_credentials['cram-md5'], str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000852 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000853
Andrew Kuchling78591822013-11-11 14:03:23 -0500854 def testAUTH_multiple(self):
855 # Test that multiple authentication methods are tried.
856 self.serv.add_feature("AUTH BOGUS PLAIN LOGIN CRAM-MD5")
857 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
858 try: smtp.login(sim_auth[0], sim_auth[1])
859 except smtplib.SMTPAuthenticationError as err:
R David Murray76e13c12014-07-03 14:47:46 -0400860 self.assertIn(sim_auth_login_user, str(err))
861 smtp.close()
862
863 def test_auth_function(self):
864 smtp = smtplib.SMTP(HOST, self.port,
865 local_hostname='localhost', timeout=15)
866 self.serv.add_feature("AUTH CRAM-MD5")
867 smtp.user, smtp.password = sim_auth[0], sim_auth[1]
868 supported = {'CRAM-MD5': smtp.auth_cram_md5,
869 'PLAIN': smtp.auth_plain,
870 'LOGIN': smtp.auth_login,
871 }
872 for mechanism, method in supported.items():
873 try: smtp.auth(mechanism, method)
874 except smtplib.SMTPAuthenticationError as err:
875 self.assertIn(sim_auth_credentials[mechanism.lower()].upper(),
876 str(err))
Andrew Kuchling78591822013-11-11 14:03:23 -0500877 smtp.close()
878
R David Murray0cff49f2014-08-30 16:51:59 -0400879 def test_quit_resets_greeting(self):
880 smtp = smtplib.SMTP(HOST, self.port,
881 local_hostname='localhost',
882 timeout=15)
883 code, message = smtp.ehlo()
884 self.assertEqual(code, 250)
885 self.assertIn('size', smtp.esmtp_features)
886 smtp.quit()
887 self.assertNotIn('size', smtp.esmtp_features)
888 smtp.connect(HOST, self.port)
889 self.assertNotIn('size', smtp.esmtp_features)
890 smtp.ehlo_or_helo_if_needed()
891 self.assertIn('size', smtp.esmtp_features)
892 smtp.quit()
893
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400894 def test_with_statement(self):
895 with smtplib.SMTP(HOST, self.port) as smtp:
896 code, message = smtp.noop()
897 self.assertEqual(code, 250)
898 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
899 with smtplib.SMTP(HOST, self.port) as smtp:
900 smtp.close()
901 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
902
903 def test_with_statement_QUIT_failure(self):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400904 with self.assertRaises(smtplib.SMTPResponseException) as error:
905 with smtplib.SMTP(HOST, self.port) as smtp:
906 smtp.noop()
R David Murray6bd52022013-03-21 00:32:31 -0400907 self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400908 self.assertEqual(error.exception.smtp_code, 421)
909 self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400910
R. David Murrayfb123912009-05-28 18:19:00 +0000911 #TODO: add tests for correct AUTH method fallback now that the
912 #test infrastructure can support it.
913
R David Murrayafb151a2014-04-14 18:21:38 -0400914 # Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception
915 def test__rest_from_mail_cmd(self):
916 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
917 smtp.noop()
918 self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
919 self.serv._SMTPchannel.disconnect = True
920 with self.assertRaises(smtplib.SMTPSenderRefused):
921 smtp.sendmail('John', 'Sally', 'test message')
922 self.assertIsNone(smtp.sock)
923
R David Murrayd312c742013-03-20 20:36:14 -0400924 # Issue 5713: make sure close, not rset, is called if we get a 421 error
925 def test_421_from_mail_cmd(self):
926 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -0400927 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -0400928 self.serv._SMTPchannel.mail_response = '421 closing connection'
929 with self.assertRaises(smtplib.SMTPSenderRefused):
930 smtp.sendmail('John', 'Sally', 'test message')
931 self.assertIsNone(smtp.sock)
R David Murray03b01162013-03-20 22:11:40 -0400932 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
R David Murrayd312c742013-03-20 20:36:14 -0400933
934 def test_421_from_rcpt_cmd(self):
935 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -0400936 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -0400937 self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
938 with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
939 smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
940 self.assertIsNone(smtp.sock)
941 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
942 self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
943
944 def test_421_from_data_cmd(self):
945 class MySimSMTPChannel(SimSMTPChannel):
946 def found_terminator(self):
947 if self.smtp_state == self.DATA:
948 self.push('421 closing')
949 else:
950 super().found_terminator()
951 self.serv.channel_class = MySimSMTPChannel
952 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -0400953 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -0400954 with self.assertRaises(smtplib.SMTPDataError):
955 smtp.sendmail('John@foo.org', ['Sally@foo.org'], 'test message')
956 self.assertIsNone(smtp.sock)
957 self.assertEqual(self.serv._SMTPchannel.rcpt_count, 0)
958
Guido van Rossum04110fb2007-08-24 16:32:05 +0000959
Antoine Pitroud54fa552011-08-28 01:23:52 +0200960@support.reap_threads
Guido van Rossumd8faa362007-04-27 19:54:29 +0000961def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000962 support.run_unittest(GeneralTests, DebuggingServerTests,
Christian Heimes380f7f22008-02-28 11:19:05 +0000963 NonConnectingTests,
Georg Brandlb38b5c42014-02-10 22:11:21 +0100964 BadHELOServerTests, SMTPSimTests,
965 TooLongLineTests)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000966
967if __name__ == '__main__':
968 test_main()