blob: faf013ac9a66e0e56070e3ba5f78ec36db1aea8d [file] [log] [blame]
Guido van Rossum806c2462007-08-06 23:33:07 +00001import asyncore
R David Murrayb0deeb42015-11-08 01:03:52 -05002import base64
R. David Murray7dff9e02010-11-08 17:15:13 +00003import email.mime.text
R David Murray83084442015-05-17 19:27:22 -04004from email.message import EmailMessage
Barry Warsawc5ea7542015-07-09 10:39:55 -04005from email.base64mime import body_encode as encode_base64
Guido van Rossum04110fb2007-08-24 16:32:05 +00006import email.utils
Christian Heimesc64a1a62019-09-25 16:30:20 +02007import hashlib
R David Murrayb0deeb42015-11-08 01:03:52 -05008import hmac
Guido van Rossumd8faa362007-04-27 19:54:29 +00009import socket
Guido van Rossum806c2462007-08-06 23:33:07 +000010import smtpd
Guido van Rossumd8faa362007-04-27 19:54:29 +000011import smtplib
Guido van Rossum806c2462007-08-06 23:33:07 +000012import io
R. David Murray7dff9e02010-11-08 17:15:13 +000013import re
Guido van Rossum806c2462007-08-06 23:33:07 +000014import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +000015import time
Guido van Rossum806c2462007-08-06 23:33:07 +000016import select
Ross Lagerwall86407432012-03-29 18:08:48 +020017import errno
R David Murray83084442015-05-17 19:27:22 -040018import textwrap
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020019import threading
Guido van Rossumd8faa362007-04-27 19:54:29 +000020
Victor Stinner45df8202010-04-28 22:31:17 +000021import unittest
Richard Jones64b02de2010-08-03 06:39:33 +000022from test import support, mock_socket
Victor Stinner8f4ef3b2019-07-01 18:28:25 +020023from test.support import HOST
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +010024from test.support import threading_setup, threading_cleanup, join_thread
Christian Heimesc64a1a62019-09-25 16:30:20 +020025from test.support import requires_hashdigest
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +020026from unittest.mock import Mock
Guido van Rossumd8faa362007-04-27 19:54:29 +000027
Victor Stinner45df8202010-04-28 22:31:17 +000028
Josiah Carlsond74900e2008-07-07 04:15:08 +000029if sys.platform == 'darwin':
30 # select.poll returns a select.POLLHUP at the end of the tests
31 # on darwin, so just ignore it
32 def handle_expt(self):
33 pass
34 smtpd.SMTPChannel.handle_expt = handle_expt
35
36
Christian Heimes5e696852008-04-09 08:37:03 +000037def server(evt, buf, serv):
Charles-François Natali6e204602014-07-23 19:28:13 +010038 serv.listen()
Christian Heimes380f7f22008-02-28 11:19:05 +000039 evt.set()
Guido van Rossumd8faa362007-04-27 19:54:29 +000040 try:
41 conn, addr = serv.accept()
42 except socket.timeout:
43 pass
44 else:
Guido van Rossum806c2462007-08-06 23:33:07 +000045 n = 500
46 while buf and n > 0:
47 r, w, e = select.select([], [conn], [])
48 if w:
49 sent = conn.send(buf)
50 buf = buf[sent:]
51
52 n -= 1
Guido van Rossum806c2462007-08-06 23:33:07 +000053
Guido van Rossumd8faa362007-04-27 19:54:29 +000054 conn.close()
55 finally:
56 serv.close()
57 evt.set()
58
Victor Stinner45df8202010-04-28 22:31:17 +000059class GeneralTests(unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +000060
61 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +000062 smtplib.socket = mock_socket
63 self.port = 25
Guido van Rossumd8faa362007-04-27 19:54:29 +000064
65 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +000066 smtplib.socket = socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000067
R. David Murray7dff9e02010-11-08 17:15:13 +000068 # This method is no longer used but is retained for backward compatibility,
69 # so test to make sure it still works.
70 def testQuoteData(self):
71 teststr = "abc\n.jkl\rfoo\r\n..blue"
72 expected = "abc\r\n..jkl\r\nfoo\r\n...blue"
73 self.assertEqual(expected, smtplib.quotedata(teststr))
74
Guido van Rossum806c2462007-08-06 23:33:07 +000075 def testBasic1(self):
Richard Jones64b02de2010-08-03 06:39:33 +000076 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossumd8faa362007-04-27 19:54:29 +000077 # connects
Christian Heimes5e696852008-04-09 08:37:03 +000078 smtp = smtplib.SMTP(HOST, self.port)
Georg Brandlf78e02b2008-06-10 17:40:04 +000079 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +000080
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080081 def testSourceAddress(self):
82 mock_socket.reply_with(b"220 Hola mundo")
83 # connects
84 smtp = smtplib.SMTP(HOST, self.port,
85 source_address=('127.0.0.1',19876))
86 self.assertEqual(smtp.source_address, ('127.0.0.1', 19876))
87 smtp.close()
88
Guido van Rossum806c2462007-08-06 23:33:07 +000089 def testBasic2(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000090 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000091 # connects, include port in host name
Christian Heimes5e696852008-04-09 08:37:03 +000092 smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
Georg Brandlf78e02b2008-06-10 17:40:04 +000093 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000094
95 def testLocalHostName(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000096 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000097 # check that supplied local_hostname is used
Christian Heimes5e696852008-04-09 08:37:03 +000098 smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
Guido van Rossum806c2462007-08-06 23:33:07 +000099 self.assertEqual(smtp.local_hostname, "testhost")
Georg Brandlf78e02b2008-06-10 17:40:04 +0000100 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000101
Guido van Rossumd8faa362007-04-27 19:54:29 +0000102 def testTimeoutDefault(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000103 mock_socket.reply_with(b"220 Hola mundo")
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200104 self.assertIsNone(mock_socket.getdefaulttimeout())
Richard Jones64b02de2010-08-03 06:39:33 +0000105 mock_socket.setdefaulttimeout(30)
106 self.assertEqual(mock_socket.getdefaulttimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000107 try:
108 smtp = smtplib.SMTP(HOST, self.port)
109 finally:
Richard Jones64b02de2010-08-03 06:39:33 +0000110 mock_socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000111 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000112 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000113
114 def testTimeoutNone(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000115 mock_socket.reply_with(b"220 Hola mundo")
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200116 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000117 socket.setdefaulttimeout(30)
118 try:
Christian Heimes5e696852008-04-09 08:37:03 +0000119 smtp = smtplib.SMTP(HOST, self.port, timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000120 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000121 socket.setdefaulttimeout(None)
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200122 self.assertIsNone(smtp.sock.gettimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +0000123 smtp.close()
124
125 def testTimeoutValue(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000126 mock_socket.reply_with(b"220 Hola mundo")
Georg Brandlf78e02b2008-06-10 17:40:04 +0000127 smtp = smtplib.SMTP(HOST, self.port, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000128 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000129 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000130
R David Murray0c49b892015-04-16 17:14:42 -0400131 def test_debuglevel(self):
132 mock_socket.reply_with(b"220 Hello world")
133 smtp = smtplib.SMTP()
134 smtp.set_debuglevel(1)
135 with support.captured_stderr() as stderr:
136 smtp.connect(HOST, self.port)
137 smtp.close()
138 expected = re.compile(r"^connect:", re.MULTILINE)
139 self.assertRegex(stderr.getvalue(), expected)
140
141 def test_debuglevel_2(self):
142 mock_socket.reply_with(b"220 Hello world")
143 smtp = smtplib.SMTP()
144 smtp.set_debuglevel(2)
145 with support.captured_stderr() as stderr:
146 smtp.connect(HOST, self.port)
147 smtp.close()
148 expected = re.compile(r"^\d{2}:\d{2}:\d{2}\.\d{6} connect: ",
149 re.MULTILINE)
150 self.assertRegex(stderr.getvalue(), expected)
151
Guido van Rossumd8faa362007-04-27 19:54:29 +0000152
Guido van Rossum04110fb2007-08-24 16:32:05 +0000153# Test server thread using the specified SMTP server class
Christian Heimes5e696852008-04-09 08:37:03 +0000154def debugging_server(serv, serv_evt, client_evt):
Christian Heimes380f7f22008-02-28 11:19:05 +0000155 serv_evt.set()
Guido van Rossum806c2462007-08-06 23:33:07 +0000156
157 try:
158 if hasattr(select, 'poll'):
159 poll_fun = asyncore.poll2
160 else:
161 poll_fun = asyncore.poll
162
163 n = 1000
164 while asyncore.socket_map and n > 0:
165 poll_fun(0.01, asyncore.socket_map)
166
167 # when the client conversation is finished, it will
168 # set client_evt, and it's then ok to kill the server
Benjamin Peterson672b8032008-06-11 19:14:14 +0000169 if client_evt.is_set():
Guido van Rossum806c2462007-08-06 23:33:07 +0000170 serv.close()
171 break
172
173 n -= 1
174
175 except socket.timeout:
176 pass
177 finally:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000178 if not client_evt.is_set():
Christian Heimes380f7f22008-02-28 11:19:05 +0000179 # allow some time for the client to read the result
180 time.sleep(0.5)
181 serv.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000182 asyncore.close_all()
Guido van Rossum806c2462007-08-06 23:33:07 +0000183 serv_evt.set()
184
185MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
186MSG_END = '------------ END MESSAGE ------------\n'
187
Guido van Rossum04110fb2007-08-24 16:32:05 +0000188# NOTE: Some SMTP objects in the tests below are created with a non-default
189# local_hostname argument to the constructor, since (on some systems) the FQDN
190# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000191# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000192
193# Test behavior of smtpd.DebuggingServer
Victor Stinner45df8202010-04-28 22:31:17 +0000194class DebuggingServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000195
R. David Murray7dff9e02010-11-08 17:15:13 +0000196 maxDiff = None
197
Guido van Rossum806c2462007-08-06 23:33:07 +0000198 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100199 self.thread_key = threading_setup()
Richard Jones64b02de2010-08-03 06:39:33 +0000200 self.real_getfqdn = socket.getfqdn
201 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000202 # temporarily replace sys.stdout to capture DebuggingServer output
203 self.old_stdout = sys.stdout
204 self.output = io.StringIO()
205 sys.stdout = self.output
206
207 self.serv_evt = threading.Event()
208 self.client_evt = threading.Event()
R. David Murray7dff9e02010-11-08 17:15:13 +0000209 # Capture SMTPChannel debug output
210 self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
211 smtpd.DEBUGSTREAM = io.StringIO()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000212 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400213 self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1),
214 decode_data=True)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700215 # Keep a note of what server host and port were assigned
216 self.host, self.port = self.serv.socket.getsockname()[:2]
Christian Heimes5e696852008-04-09 08:37:03 +0000217 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000218 self.thread = threading.Thread(target=debugging_server, args=serv_args)
219 self.thread.start()
Guido van Rossum806c2462007-08-06 23:33:07 +0000220
221 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000222 self.serv_evt.wait()
223 self.serv_evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000224
225 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000226 socket.getfqdn = self.real_getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000227 # indicate that the client is finished
228 self.client_evt.set()
229 # wait for the server thread to terminate
230 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100231 join_thread(self.thread)
Guido van Rossum806c2462007-08-06 23:33:07 +0000232 # restore sys.stdout
233 sys.stdout = self.old_stdout
R. David Murray7dff9e02010-11-08 17:15:13 +0000234 # restore DEBUGSTREAM
235 smtpd.DEBUGSTREAM.close()
236 smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100237 del self.thread
238 self.doCleanups()
239 threading_cleanup(*self.thread_key)
Guido van Rossum806c2462007-08-06 23:33:07 +0000240
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700241 def get_output_without_xpeer(self):
242 test_output = self.output.getvalue()
243 return re.sub(r'(.*?)^X-Peer:\s*\S+\n(.*)', r'\1\2',
244 test_output, flags=re.MULTILINE|re.DOTALL)
245
Guido van Rossum806c2462007-08-06 23:33:07 +0000246 def testBasic(self):
247 # connect
Victor Stinner07871b22019-12-10 20:32:59 +0100248 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
249 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum806c2462007-08-06 23:33:07 +0000250 smtp.quit()
251
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800252 def testSourceAddress(self):
253 # connect
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700254 src_port = support.find_unused_port()
Senthil Kumaranb351a482011-07-31 09:14:17 +0800255 try:
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700256 smtp = smtplib.SMTP(self.host, self.port, local_hostname='localhost',
Victor Stinner07871b22019-12-10 20:32:59 +0100257 timeout=support.LOOPBACK_TIMEOUT,
258 source_address=(self.host, src_port))
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100259 self.addCleanup(smtp.close)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700260 self.assertEqual(smtp.source_address, (self.host, src_port))
Senthil Kumaranb351a482011-07-31 09:14:17 +0800261 self.assertEqual(smtp.local_hostname, 'localhost')
262 smtp.quit()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200263 except OSError as e:
Senthil Kumaranb351a482011-07-31 09:14:17 +0800264 if e.errno == errno.EADDRINUSE:
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700265 self.skipTest("couldn't bind to source port %d" % src_port)
Senthil Kumaranb351a482011-07-31 09:14:17 +0800266 raise
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800267
Guido van Rossum04110fb2007-08-24 16:32:05 +0000268 def testNOOP(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100269 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
270 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100271 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400272 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000273 self.assertEqual(smtp.noop(), expected)
274 smtp.quit()
275
276 def testRSET(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100277 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
278 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100279 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400280 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000281 self.assertEqual(smtp.rset(), expected)
282 smtp.quit()
283
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400284 def testELHO(self):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000285 # EHLO isn't implemented in DebuggingServer
Victor Stinner07871b22019-12-10 20:32:59 +0100286 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
287 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100288 self.addCleanup(smtp.close)
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400289 expected = (250, b'\nSIZE 33554432\nHELP')
Guido van Rossum806c2462007-08-06 23:33:07 +0000290 self.assertEqual(smtp.ehlo(), expected)
291 smtp.quit()
292
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400293 def testEXPNNotImplemented(self):
R David Murrayd1a30c92012-05-26 14:33:59 -0400294 # EXPN isn't implemented in DebuggingServer
Victor Stinner07871b22019-12-10 20:32:59 +0100295 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
296 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100297 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400298 expected = (502, b'EXPN not implemented')
299 smtp.putcmd('EXPN')
300 self.assertEqual(smtp.getreply(), expected)
301 smtp.quit()
302
303 def testVRFY(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100304 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
305 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100306 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400307 expected = (252, b'Cannot VRFY user, but will accept message ' + \
308 b'and attempt delivery')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000309 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
310 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
311 smtp.quit()
312
313 def testSecondHELO(self):
314 # check that a second HELO returns a message that it's a duplicate
315 # (this behavior is specific to smtpd.SMTPChannel)
Victor Stinner07871b22019-12-10 20:32:59 +0100316 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
317 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100318 self.addCleanup(smtp.close)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000319 smtp.helo()
320 expected = (503, b'Duplicate HELO/EHLO')
321 self.assertEqual(smtp.helo(), expected)
322 smtp.quit()
323
Guido van Rossum806c2462007-08-06 23:33:07 +0000324 def testHELP(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100325 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
326 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100327 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400328 self.assertEqual(smtp.help(), b'Supported commands: EHLO HELO MAIL ' + \
329 b'RCPT DATA RSET NOOP QUIT VRFY')
Guido van Rossum806c2462007-08-06 23:33:07 +0000330 smtp.quit()
331
332 def testSend(self):
333 # connect and send mail
334 m = 'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100335 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
336 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100337 self.addCleanup(smtp.close)
Guido van Rossum806c2462007-08-06 23:33:07 +0000338 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000339 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
340 # in asyncore. This sleep might help, but should really be fixed
341 # properly by using an Event variable.
342 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000343 smtp.quit()
344
345 self.client_evt.set()
346 self.serv_evt.wait()
347 self.output.flush()
348 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
349 self.assertEqual(self.output.getvalue(), mexpect)
350
R. David Murray7dff9e02010-11-08 17:15:13 +0000351 def testSendBinary(self):
352 m = b'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100353 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
354 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100355 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000356 smtp.sendmail('John', 'Sally', m)
357 # XXX (see comment in testSend)
358 time.sleep(0.01)
359 smtp.quit()
360
361 self.client_evt.set()
362 self.serv_evt.wait()
363 self.output.flush()
364 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
365 self.assertEqual(self.output.getvalue(), mexpect)
366
R David Murray0f663d02011-06-09 15:05:57 -0400367 def testSendNeedingDotQuote(self):
368 # Issue 12283
369 m = '.A test\n.mes.sage.'
Victor Stinner07871b22019-12-10 20:32:59 +0100370 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
371 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100372 self.addCleanup(smtp.close)
R David Murray0f663d02011-06-09 15:05:57 -0400373 smtp.sendmail('John', 'Sally', m)
374 # XXX (see comment in testSend)
375 time.sleep(0.01)
376 smtp.quit()
377
378 self.client_evt.set()
379 self.serv_evt.wait()
380 self.output.flush()
381 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
382 self.assertEqual(self.output.getvalue(), mexpect)
383
R David Murray46346762011-07-18 21:38:54 -0400384 def testSendNullSender(self):
385 m = 'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100386 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
387 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100388 self.addCleanup(smtp.close)
R David Murray46346762011-07-18 21:38:54 -0400389 smtp.sendmail('<>', 'Sally', m)
390 # XXX (see comment in testSend)
391 time.sleep(0.01)
392 smtp.quit()
393
394 self.client_evt.set()
395 self.serv_evt.wait()
396 self.output.flush()
397 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
398 self.assertEqual(self.output.getvalue(), mexpect)
399 debugout = smtpd.DEBUGSTREAM.getvalue()
400 sender = re.compile("^sender: <>$", re.MULTILINE)
401 self.assertRegex(debugout, sender)
402
R. David Murray7dff9e02010-11-08 17:15:13 +0000403 def testSendMessage(self):
404 m = email.mime.text.MIMEText('A test message')
Victor Stinner07871b22019-12-10 20:32:59 +0100405 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
406 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100407 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000408 smtp.send_message(m, from_addr='John', to_addrs='Sally')
409 # XXX (see comment in testSend)
410 time.sleep(0.01)
411 smtp.quit()
412
413 self.client_evt.set()
414 self.serv_evt.wait()
415 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700416 # Remove the X-Peer header that DebuggingServer adds as figuring out
417 # exactly what IP address format is put there is not easy (and
418 # irrelevant to our test). Typically 127.0.0.1 or ::1, but it is
419 # not always the same as socket.gethostbyname(HOST). :(
420 test_output = self.get_output_without_xpeer()
421 del m['X-Peer']
R. David Murray7dff9e02010-11-08 17:15:13 +0000422 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700423 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000424
425 def testSendMessageWithAddresses(self):
426 m = email.mime.text.MIMEText('A test message')
427 m['From'] = 'foo@bar.com'
428 m['To'] = 'John'
429 m['CC'] = 'Sally, Fred'
430 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
Victor Stinner07871b22019-12-10 20:32:59 +0100431 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
432 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100433 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000434 smtp.send_message(m)
435 # XXX (see comment in testSend)
436 time.sleep(0.01)
437 smtp.quit()
R David Murrayac4e5ab2011-07-02 21:03:19 -0400438 # make sure the Bcc header is still in the message.
439 self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
440 '<warped@silly.walks.com>')
R. David Murray7dff9e02010-11-08 17:15:13 +0000441
442 self.client_evt.set()
443 self.serv_evt.wait()
444 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700445 # Remove the X-Peer header that DebuggingServer adds.
446 test_output = self.get_output_without_xpeer()
447 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400448 # The Bcc header should not be transmitted.
R. David Murray7dff9e02010-11-08 17:15:13 +0000449 del m['Bcc']
450 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700451 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000452 debugout = smtpd.DEBUGSTREAM.getvalue()
453 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000454 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000455 for addr in ('John', 'Sally', 'Fred', 'root@localhost',
456 'warped@silly.walks.com'):
457 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
458 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000459 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000460
461 def testSendMessageWithSomeAddresses(self):
462 # Make sure nothing breaks if not all of the three 'to' headers exist
463 m = email.mime.text.MIMEText('A test message')
464 m['From'] = 'foo@bar.com'
465 m['To'] = 'John, Dinsdale'
Victor Stinner07871b22019-12-10 20:32:59 +0100466 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
467 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100468 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000469 smtp.send_message(m)
470 # XXX (see comment in testSend)
471 time.sleep(0.01)
472 smtp.quit()
473
474 self.client_evt.set()
475 self.serv_evt.wait()
476 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700477 # Remove the X-Peer header that DebuggingServer adds.
478 test_output = self.get_output_without_xpeer()
479 del m['X-Peer']
R. David Murray7dff9e02010-11-08 17:15:13 +0000480 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700481 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000482 debugout = smtpd.DEBUGSTREAM.getvalue()
483 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000484 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000485 for addr in ('John', 'Dinsdale'):
486 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
487 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000488 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000489
R David Murrayac4e5ab2011-07-02 21:03:19 -0400490 def testSendMessageWithSpecifiedAddresses(self):
491 # Make sure addresses specified in call override those in message.
492 m = email.mime.text.MIMEText('A test message')
493 m['From'] = 'foo@bar.com'
494 m['To'] = 'John, Dinsdale'
Victor Stinner07871b22019-12-10 20:32:59 +0100495 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
496 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100497 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400498 smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
499 # XXX (see comment in testSend)
500 time.sleep(0.01)
501 smtp.quit()
502
503 self.client_evt.set()
504 self.serv_evt.wait()
505 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700506 # Remove the X-Peer header that DebuggingServer adds.
507 test_output = self.get_output_without_xpeer()
508 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400509 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700510 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400511 debugout = smtpd.DEBUGSTREAM.getvalue()
512 sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
513 self.assertRegex(debugout, sender)
514 for addr in ('John', 'Dinsdale'):
515 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
516 re.MULTILINE)
517 self.assertNotRegex(debugout, to_addr)
518 recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
519 self.assertRegex(debugout, recip)
520
521 def testSendMessageWithMultipleFrom(self):
522 # Sender overrides To
523 m = email.mime.text.MIMEText('A test message')
524 m['From'] = 'Bernard, Bianca'
525 m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com'
526 m['To'] = 'John, Dinsdale'
Victor Stinner07871b22019-12-10 20:32:59 +0100527 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
528 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100529 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400530 smtp.send_message(m)
531 # XXX (see comment in testSend)
532 time.sleep(0.01)
533 smtp.quit()
534
535 self.client_evt.set()
536 self.serv_evt.wait()
537 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700538 # Remove the X-Peer header that DebuggingServer adds.
539 test_output = self.get_output_without_xpeer()
540 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400541 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700542 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400543 debugout = smtpd.DEBUGSTREAM.getvalue()
544 sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
545 self.assertRegex(debugout, sender)
546 for addr in ('John', 'Dinsdale'):
547 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
548 re.MULTILINE)
549 self.assertRegex(debugout, to_addr)
550
551 def testSendMessageResent(self):
552 m = email.mime.text.MIMEText('A test message')
553 m['From'] = 'foo@bar.com'
554 m['To'] = 'John'
555 m['CC'] = 'Sally, Fred'
556 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
557 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
558 m['Resent-From'] = 'holy@grail.net'
559 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
560 m['Resent-Bcc'] = 'doe@losthope.net'
Victor Stinner07871b22019-12-10 20:32:59 +0100561 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
562 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100563 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400564 smtp.send_message(m)
565 # XXX (see comment in testSend)
566 time.sleep(0.01)
567 smtp.quit()
568
569 self.client_evt.set()
570 self.serv_evt.wait()
571 self.output.flush()
572 # The Resent-Bcc headers are deleted before serialization.
573 del m['Bcc']
574 del m['Resent-Bcc']
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700575 # Remove the X-Peer header that DebuggingServer adds.
576 test_output = self.get_output_without_xpeer()
577 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400578 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700579 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400580 debugout = smtpd.DEBUGSTREAM.getvalue()
581 sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
582 self.assertRegex(debugout, sender)
583 for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
584 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
585 re.MULTILINE)
586 self.assertRegex(debugout, to_addr)
587
588 def testSendMessageMultipleResentRaises(self):
589 m = email.mime.text.MIMEText('A test message')
590 m['From'] = 'foo@bar.com'
591 m['To'] = 'John'
592 m['CC'] = 'Sally, Fred'
593 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
594 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
595 m['Resent-From'] = 'holy@grail.net'
596 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
597 m['Resent-Bcc'] = 'doe@losthope.net'
598 m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
599 m['Resent-To'] = 'holy@grail.net'
600 m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
Victor Stinner07871b22019-12-10 20:32:59 +0100601 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
602 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100603 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400604 with self.assertRaises(ValueError):
605 smtp.send_message(m)
606 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000607
Victor Stinner45df8202010-04-28 22:31:17 +0000608class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000609
610 def testNotConnected(self):
611 # Test various operations on an unconnected SMTP object that
612 # should raise exceptions (at present the attempt in SMTP.send
613 # to reference the nonexistent 'sock' attribute of the SMTP object
614 # causes an AttributeError)
615 smtp = smtplib.SMTP()
616 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
617 self.assertRaises(smtplib.SMTPServerDisconnected,
618 smtp.send, 'test msg')
619
620 def testNonnumericPort(self):
Andrew Svetlov0832af62012-12-18 23:10:48 +0200621 # check that non-numeric port raises OSError
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200622 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000623 "localhost", "bogus")
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200624 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000625 "localhost:bogus")
626
Romuald Brunet7b313972018-10-09 16:31:55 +0200627 def testSockAttributeExists(self):
628 # check that sock attribute is present outside of a connect() call
629 # (regression test, the previous behavior raised an
630 # AttributeError: 'SMTP' object has no attribute 'sock')
631 with smtplib.SMTP() as smtp:
632 self.assertIsNone(smtp.sock)
633
Christian Heimes380f7f22008-02-28 11:19:05 +0000634
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +0200635class DefaultArgumentsTests(unittest.TestCase):
636
637 def setUp(self):
638 self.msg = EmailMessage()
639 self.msg['From'] = 'Páolo <főo@bar.com>'
640 self.smtp = smtplib.SMTP()
641 self.smtp.ehlo = Mock(return_value=(200, 'OK'))
642 self.smtp.has_extn, self.smtp.sendmail = Mock(), Mock()
643
644 def testSendMessage(self):
645 expected_mail_options = ('SMTPUTF8', 'BODY=8BITMIME')
646 self.smtp.send_message(self.msg)
647 self.smtp.send_message(self.msg)
648 self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
649 expected_mail_options)
650 self.assertEqual(self.smtp.sendmail.call_args_list[1][0][3],
651 expected_mail_options)
652
653 def testSendMessageWithMailOptions(self):
654 mail_options = ['STARTTLS']
655 expected_mail_options = ('STARTTLS', 'SMTPUTF8', 'BODY=8BITMIME')
656 self.smtp.send_message(self.msg, None, None, mail_options)
657 self.assertEqual(mail_options, ['STARTTLS'])
658 self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
659 expected_mail_options)
660
661
Guido van Rossum04110fb2007-08-24 16:32:05 +0000662# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000663class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000664
665 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000666 smtplib.socket = mock_socket
667 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000668 self.old_stdout = sys.stdout
669 self.output = io.StringIO()
670 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000671 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000672
673 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000674 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000675 sys.stdout = self.old_stdout
676
677 def testFailingHELO(self):
678 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000679 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000680
Guido van Rossum04110fb2007-08-24 16:32:05 +0000681
Georg Brandlb38b5c42014-02-10 22:11:21 +0100682class TooLongLineTests(unittest.TestCase):
683 respdata = b'250 OK' + (b'.' * smtplib._MAXLINE * 2) + b'\n'
684
685 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100686 self.thread_key = threading_setup()
Georg Brandlb38b5c42014-02-10 22:11:21 +0100687 self.old_stdout = sys.stdout
688 self.output = io.StringIO()
689 sys.stdout = self.output
690
691 self.evt = threading.Event()
692 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
693 self.sock.settimeout(15)
694 self.port = support.bind_port(self.sock)
695 servargs = (self.evt, self.respdata, self.sock)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100696 self.thread = threading.Thread(target=server, args=servargs)
697 self.thread.start()
Georg Brandlb38b5c42014-02-10 22:11:21 +0100698 self.evt.wait()
699 self.evt.clear()
700
701 def tearDown(self):
702 self.evt.wait()
703 sys.stdout = self.old_stdout
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100704 join_thread(self.thread)
705 del self.thread
706 self.doCleanups()
707 threading_cleanup(*self.thread_key)
Georg Brandlb38b5c42014-02-10 22:11:21 +0100708
709 def testLineTooLong(self):
710 self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
711 HOST, self.port, 'localhost', 3)
712
713
Guido van Rossum04110fb2007-08-24 16:32:05 +0000714sim_users = {'Mr.A@somewhere.com':'John A',
R David Murray46346762011-07-18 21:38:54 -0400715 'Ms.B@xn--fo-fka.com':'Sally B',
Guido van Rossum04110fb2007-08-24 16:32:05 +0000716 'Mrs.C@somewhereesle.com':'Ruth C',
717 }
718
R. David Murraycaa27b72009-05-23 18:49:56 +0000719sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000720sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
721 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000722sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
R David Murray46346762011-07-18 21:38:54 -0400723 'list-2':['Ms.B@xn--fo-fka.com',],
Guido van Rossum04110fb2007-08-24 16:32:05 +0000724 }
725
726# Simulated SMTP channel & server
R David Murrayb0deeb42015-11-08 01:03:52 -0500727class ResponseException(Exception): pass
Guido van Rossum04110fb2007-08-24 16:32:05 +0000728class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000729
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400730 quit_response = None
R David Murrayd312c742013-03-20 20:36:14 -0400731 mail_response = None
732 rcpt_response = None
733 data_response = None
734 rcpt_count = 0
735 rset_count = 0
R David Murrayafb151a2014-04-14 18:21:38 -0400736 disconnect = 0
R David Murrayb0deeb42015-11-08 01:03:52 -0500737 AUTH = 99 # Add protocol state to enable auth testing.
738 authenticated_user = None
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400739
R. David Murray23ddc0e2009-05-29 18:03:16 +0000740 def __init__(self, extra_features, *args, **kw):
741 self._extrafeatures = ''.join(
742 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000743 super(SimSMTPChannel, self).__init__(*args, **kw)
744
R David Murrayb0deeb42015-11-08 01:03:52 -0500745 # AUTH related stuff. It would be nice if support for this were in smtpd.
746 def found_terminator(self):
747 if self.smtp_state == self.AUTH:
748 line = self._emptystring.join(self.received_lines)
749 print('Data:', repr(line), file=smtpd.DEBUGSTREAM)
750 self.received_lines = []
751 try:
752 self.auth_object(line)
753 except ResponseException as e:
754 self.smtp_state = self.COMMAND
755 self.push('%s %s' % (e.smtp_code, e.smtp_error))
756 return
757 super().found_terminator()
758
759
760 def smtp_AUTH(self, arg):
761 if not self.seen_greeting:
762 self.push('503 Error: send EHLO first')
763 return
764 if not self.extended_smtp or 'AUTH' not in self._extrafeatures:
765 self.push('500 Error: command "AUTH" not recognized')
766 return
767 if self.authenticated_user is not None:
768 self.push(
769 '503 Bad sequence of commands: already authenticated')
770 return
771 args = arg.split()
772 if len(args) not in [1, 2]:
773 self.push('501 Syntax: AUTH <mechanism> [initial-response]')
774 return
775 auth_object_name = '_auth_%s' % args[0].lower().replace('-', '_')
776 try:
777 self.auth_object = getattr(self, auth_object_name)
778 except AttributeError:
779 self.push('504 Command parameter not implemented: unsupported '
780 ' authentication mechanism {!r}'.format(auth_object_name))
781 return
782 self.smtp_state = self.AUTH
783 self.auth_object(args[1] if len(args) == 2 else None)
784
785 def _authenticated(self, user, valid):
786 if valid:
787 self.authenticated_user = user
788 self.push('235 Authentication Succeeded')
789 else:
790 self.push('535 Authentication credentials invalid')
791 self.smtp_state = self.COMMAND
792
793 def _decode_base64(self, string):
794 return base64.decodebytes(string.encode('ascii')).decode('utf-8')
795
796 def _auth_plain(self, arg=None):
797 if arg is None:
798 self.push('334 ')
799 else:
800 logpass = self._decode_base64(arg)
801 try:
802 *_, user, password = logpass.split('\0')
803 except ValueError as e:
804 self.push('535 Splitting response {!r} into user and password'
805 ' failed: {}'.format(logpass, e))
806 return
807 self._authenticated(user, password == sim_auth[1])
808
809 def _auth_login(self, arg=None):
810 if arg is None:
811 # base64 encoded 'Username:'
812 self.push('334 VXNlcm5hbWU6')
813 elif not hasattr(self, '_auth_login_user'):
814 self._auth_login_user = self._decode_base64(arg)
815 # base64 encoded 'Password:'
816 self.push('334 UGFzc3dvcmQ6')
817 else:
818 password = self._decode_base64(arg)
819 self._authenticated(self._auth_login_user, password == sim_auth[1])
820 del self._auth_login_user
821
822 def _auth_cram_md5(self, arg=None):
823 if arg is None:
824 self.push('334 {}'.format(sim_cram_md5_challenge))
825 else:
826 logpass = self._decode_base64(arg)
827 try:
828 user, hashed_pass = logpass.split()
829 except ValueError as e:
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +0200830 self.push('535 Splitting response {!r} into user and password '
R David Murrayb0deeb42015-11-08 01:03:52 -0500831 'failed: {}'.format(logpass, e))
832 return False
833 valid_hashed_pass = hmac.HMAC(
834 sim_auth[1].encode('ascii'),
835 self._decode_base64(sim_cram_md5_challenge).encode('ascii'),
836 'md5').hexdigest()
837 self._authenticated(user, hashed_pass == valid_hashed_pass)
838 # end AUTH related stuff.
839
Guido van Rossum04110fb2007-08-24 16:32:05 +0000840 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000841 resp = ('250-testhost\r\n'
842 '250-EXPN\r\n'
843 '250-SIZE 20000000\r\n'
844 '250-STARTTLS\r\n'
845 '250-DELIVERBY\r\n')
846 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000847 self.push(resp)
R David Murrayf1a40b42013-03-20 21:12:17 -0400848 self.seen_greeting = arg
849 self.extended_smtp = True
Guido van Rossum04110fb2007-08-24 16:32:05 +0000850
851 def smtp_VRFY(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400852 # For max compatibility smtplib should be sending the raw address.
853 if arg in sim_users:
854 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000855 else:
856 self.push('550 No such user: %s' % arg)
857
858 def smtp_EXPN(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400859 list_name = arg.lower()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000860 if list_name in sim_lists:
861 user_list = sim_lists[list_name]
862 for n, user_email in enumerate(user_list):
863 quoted_addr = smtplib.quoteaddr(user_email)
864 if n < len(user_list) - 1:
865 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
866 else:
867 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
868 else:
869 self.push('550 No access for you!')
870
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400871 def smtp_QUIT(self, arg):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400872 if self.quit_response is None:
873 super(SimSMTPChannel, self).smtp_QUIT(arg)
874 else:
875 self.push(self.quit_response)
876 self.close_when_done()
877
R David Murrayd312c742013-03-20 20:36:14 -0400878 def smtp_MAIL(self, arg):
879 if self.mail_response is None:
880 super().smtp_MAIL(arg)
881 else:
882 self.push(self.mail_response)
R David Murrayafb151a2014-04-14 18:21:38 -0400883 if self.disconnect:
884 self.close_when_done()
R David Murrayd312c742013-03-20 20:36:14 -0400885
886 def smtp_RCPT(self, arg):
887 if self.rcpt_response is None:
888 super().smtp_RCPT(arg)
889 return
R David Murrayd312c742013-03-20 20:36:14 -0400890 self.rcpt_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400891 self.push(self.rcpt_response[self.rcpt_count-1])
R David Murrayd312c742013-03-20 20:36:14 -0400892
893 def smtp_RSET(self, arg):
R David Murrayd312c742013-03-20 20:36:14 -0400894 self.rset_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400895 super().smtp_RSET(arg)
R David Murrayd312c742013-03-20 20:36:14 -0400896
897 def smtp_DATA(self, arg):
898 if self.data_response is None:
899 super().smtp_DATA(arg)
900 else:
901 self.push(self.data_response)
902
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000903 def handle_error(self):
904 raise
905
Guido van Rossum04110fb2007-08-24 16:32:05 +0000906
907class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000908
R David Murrayd312c742013-03-20 20:36:14 -0400909 channel_class = SimSMTPChannel
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400910
R. David Murray23ddc0e2009-05-29 18:03:16 +0000911 def __init__(self, *args, **kw):
912 self._extra_features = []
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +0100913 self._addresses = {}
R. David Murray23ddc0e2009-05-29 18:03:16 +0000914 smtpd.SMTPServer.__init__(self, *args, **kw)
915
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000916 def handle_accepted(self, conn, addr):
R David Murrayf1a40b42013-03-20 21:12:17 -0400917 self._SMTPchannel = self.channel_class(
R David Murray1144da52014-06-11 12:27:40 -0400918 self._extra_features, self, conn, addr,
919 decode_data=self._decode_data)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000920
921 def process_message(self, peer, mailfrom, rcpttos, data):
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +0100922 self._addresses['from'] = mailfrom
923 self._addresses['tos'] = rcpttos
Guido van Rossum04110fb2007-08-24 16:32:05 +0000924
R. David Murrayfb123912009-05-28 18:19:00 +0000925 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000926 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000927
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000928 def handle_error(self):
929 raise
930
Guido van Rossum04110fb2007-08-24 16:32:05 +0000931
932# Test various SMTP & ESMTP commands/behaviors that require a simulated server
933# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000934class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000935
936 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100937 self.thread_key = threading_setup()
Richard Jones64b02de2010-08-03 06:39:33 +0000938 self.real_getfqdn = socket.getfqdn
939 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000940 self.serv_evt = threading.Event()
941 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000942 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400943 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1), decode_data=True)
Antoine Pitrou043bad02010-04-30 23:20:15 +0000944 # Keep a note of what port was assigned
945 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000946 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000947 self.thread = threading.Thread(target=debugging_server, args=serv_args)
948 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000949
950 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000951 self.serv_evt.wait()
952 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000953
954 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000955 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000956 # indicate that the client is finished
957 self.client_evt.set()
958 # wait for the server thread to terminate
959 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100960 join_thread(self.thread)
961 del self.thread
962 self.doCleanups()
963 threading_cleanup(*self.thread_key)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000964
965 def testBasic(self):
966 # smoke test
Victor Stinner7772b1a2019-12-11 22:17:04 +0100967 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
968 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000969 smtp.quit()
970
971 def testEHLO(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +0100972 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
973 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000974
975 # no features should be present before the EHLO
976 self.assertEqual(smtp.esmtp_features, {})
977
978 # features expected from the test server
979 expected_features = {'expn':'',
980 'size': '20000000',
981 'starttls': '',
982 'deliverby': '',
983 'help': '',
984 }
985
986 smtp.ehlo()
987 self.assertEqual(smtp.esmtp_features, expected_features)
988 for k in expected_features:
989 self.assertTrue(smtp.has_extn(k))
990 self.assertFalse(smtp.has_extn('unsupported-feature'))
991 smtp.quit()
992
993 def testVRFY(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +0100994 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
995 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000996
Barry Warsawc5ea7542015-07-09 10:39:55 -0400997 for addr_spec, name in sim_users.items():
Guido van Rossum04110fb2007-08-24 16:32:05 +0000998 expected_known = (250, bytes('%s %s' %
Barry Warsawc5ea7542015-07-09 10:39:55 -0400999 (name, smtplib.quoteaddr(addr_spec)),
Guido van Rossum5a23cc52007-08-30 14:02:43 +00001000 "ascii"))
Barry Warsawc5ea7542015-07-09 10:39:55 -04001001 self.assertEqual(smtp.vrfy(addr_spec), expected_known)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001002
1003 u = 'nobody@nowhere.com'
R David Murray46346762011-07-18 21:38:54 -04001004 expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +00001005 self.assertEqual(smtp.vrfy(u), expected_unknown)
1006 smtp.quit()
1007
1008 def testEXPN(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001009 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1010 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001011
1012 for listname, members in sim_lists.items():
1013 users = []
1014 for m in members:
1015 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +00001016 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +00001017 self.assertEqual(smtp.expn(listname), expected_known)
1018
1019 u = 'PSU-Members-List'
1020 expected_unknown = (550, b'No access for you!')
1021 self.assertEqual(smtp.expn(u), expected_unknown)
1022 smtp.quit()
1023
R David Murray76e13c12014-07-03 14:47:46 -04001024 def testAUTH_PLAIN(self):
1025 self.serv.add_feature("AUTH PLAIN")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001026 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1027 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001028 resp = smtp.login(sim_auth[0], sim_auth[1])
1029 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -04001030 smtp.close()
1031
R. David Murrayfb123912009-05-28 18:19:00 +00001032 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +00001033 self.serv.add_feature("AUTH LOGIN")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001034 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1035 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001036 resp = smtp.login(sim_auth[0], sim_auth[1])
1037 self.assertEqual(resp, (235, b'Authentication Succeeded'))
Benjamin Petersond094efd2010-10-31 17:15:42 +00001038 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +00001039
Christian Heimesc64a1a62019-09-25 16:30:20 +02001040 @requires_hashdigest('md5')
R. David Murrayfb123912009-05-28 18:19:00 +00001041 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +00001042 self.serv.add_feature("AUTH CRAM-MD5")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001043 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1044 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001045 resp = smtp.login(sim_auth[0], sim_auth[1])
1046 self.assertEqual(resp, (235, b'Authentication Succeeded'))
Benjamin Petersond094efd2010-10-31 17:15:42 +00001047 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +00001048
Andrew Kuchling78591822013-11-11 14:03:23 -05001049 def testAUTH_multiple(self):
1050 # Test that multiple authentication methods are tried.
1051 self.serv.add_feature("AUTH BOGUS PLAIN LOGIN CRAM-MD5")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001052 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1053 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001054 resp = smtp.login(sim_auth[0], sim_auth[1])
1055 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -04001056 smtp.close()
1057
1058 def test_auth_function(self):
Christian Heimesc64a1a62019-09-25 16:30:20 +02001059 supported = {'PLAIN', 'LOGIN'}
1060 try:
1061 hashlib.md5()
1062 except ValueError:
1063 pass
1064 else:
1065 supported.add('CRAM-MD5')
R David Murrayb0deeb42015-11-08 01:03:52 -05001066 for mechanism in supported:
1067 self.serv.add_feature("AUTH {}".format(mechanism))
1068 for mechanism in supported:
1069 with self.subTest(mechanism=mechanism):
1070 smtp = smtplib.SMTP(HOST, self.port,
Victor Stinner7772b1a2019-12-11 22:17:04 +01001071 local_hostname='localhost',
1072 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001073 smtp.ehlo('foo')
1074 smtp.user, smtp.password = sim_auth[0], sim_auth[1]
1075 method = 'auth_' + mechanism.lower().replace('-', '_')
1076 resp = smtp.auth(mechanism, getattr(smtp, method))
1077 self.assertEqual(resp, (235, b'Authentication Succeeded'))
1078 smtp.close()
Andrew Kuchling78591822013-11-11 14:03:23 -05001079
R David Murray0cff49f2014-08-30 16:51:59 -04001080 def test_quit_resets_greeting(self):
1081 smtp = smtplib.SMTP(HOST, self.port,
1082 local_hostname='localhost',
Victor Stinner7772b1a2019-12-11 22:17:04 +01001083 timeout=support.LOOPBACK_TIMEOUT)
R David Murray0cff49f2014-08-30 16:51:59 -04001084 code, message = smtp.ehlo()
1085 self.assertEqual(code, 250)
1086 self.assertIn('size', smtp.esmtp_features)
1087 smtp.quit()
1088 self.assertNotIn('size', smtp.esmtp_features)
1089 smtp.connect(HOST, self.port)
1090 self.assertNotIn('size', smtp.esmtp_features)
1091 smtp.ehlo_or_helo_if_needed()
1092 self.assertIn('size', smtp.esmtp_features)
1093 smtp.quit()
1094
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001095 def test_with_statement(self):
1096 with smtplib.SMTP(HOST, self.port) as smtp:
1097 code, message = smtp.noop()
1098 self.assertEqual(code, 250)
1099 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
1100 with smtplib.SMTP(HOST, self.port) as smtp:
1101 smtp.close()
1102 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
1103
1104 def test_with_statement_QUIT_failure(self):
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001105 with self.assertRaises(smtplib.SMTPResponseException) as error:
1106 with smtplib.SMTP(HOST, self.port) as smtp:
1107 smtp.noop()
R David Murray6bd52022013-03-21 00:32:31 -04001108 self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001109 self.assertEqual(error.exception.smtp_code, 421)
1110 self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001111
R. David Murrayfb123912009-05-28 18:19:00 +00001112 #TODO: add tests for correct AUTH method fallback now that the
1113 #test infrastructure can support it.
1114
R David Murrayafb151a2014-04-14 18:21:38 -04001115 # Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception
1116 def test__rest_from_mail_cmd(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001117 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1118 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayafb151a2014-04-14 18:21:38 -04001119 smtp.noop()
1120 self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
1121 self.serv._SMTPchannel.disconnect = True
1122 with self.assertRaises(smtplib.SMTPSenderRefused):
1123 smtp.sendmail('John', 'Sally', 'test message')
1124 self.assertIsNone(smtp.sock)
1125
R David Murrayd312c742013-03-20 20:36:14 -04001126 # Issue 5713: make sure close, not rset, is called if we get a 421 error
1127 def test_421_from_mail_cmd(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001128 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1129 timeout=support.LOOPBACK_TIMEOUT)
R David Murray853c0f92013-03-20 21:54:05 -04001130 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001131 self.serv._SMTPchannel.mail_response = '421 closing connection'
1132 with self.assertRaises(smtplib.SMTPSenderRefused):
1133 smtp.sendmail('John', 'Sally', 'test message')
1134 self.assertIsNone(smtp.sock)
R David Murray03b01162013-03-20 22:11:40 -04001135 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
R David Murrayd312c742013-03-20 20:36:14 -04001136
1137 def test_421_from_rcpt_cmd(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001138 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1139 timeout=support.LOOPBACK_TIMEOUT)
R David Murray853c0f92013-03-20 21:54:05 -04001140 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001141 self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
1142 with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
1143 smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
1144 self.assertIsNone(smtp.sock)
1145 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
1146 self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
1147
1148 def test_421_from_data_cmd(self):
1149 class MySimSMTPChannel(SimSMTPChannel):
1150 def found_terminator(self):
1151 if self.smtp_state == self.DATA:
1152 self.push('421 closing')
1153 else:
1154 super().found_terminator()
1155 self.serv.channel_class = MySimSMTPChannel
Victor Stinner7772b1a2019-12-11 22:17:04 +01001156 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1157 timeout=support.LOOPBACK_TIMEOUT)
R David Murray853c0f92013-03-20 21:54:05 -04001158 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001159 with self.assertRaises(smtplib.SMTPDataError):
1160 smtp.sendmail('John@foo.org', ['Sally@foo.org'], 'test message')
1161 self.assertIsNone(smtp.sock)
1162 self.assertEqual(self.serv._SMTPchannel.rcpt_count, 0)
1163
R David Murraycee7cf62015-05-16 13:58:14 -04001164 def test_smtputf8_NotSupportedError_if_no_server_support(self):
1165 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001166 HOST, self.port, local_hostname='localhost',
1167 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001168 self.addCleanup(smtp.close)
1169 smtp.ehlo()
1170 self.assertTrue(smtp.does_esmtp)
1171 self.assertFalse(smtp.has_extn('smtputf8'))
1172 self.assertRaises(
1173 smtplib.SMTPNotSupportedError,
1174 smtp.sendmail,
1175 'John', 'Sally', '', mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1176 self.assertRaises(
1177 smtplib.SMTPNotSupportedError,
1178 smtp.mail, 'John', options=['BODY=8BITMIME', 'SMTPUTF8'])
1179
1180 def test_send_unicode_without_SMTPUTF8(self):
1181 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001182 HOST, self.port, local_hostname='localhost',
1183 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001184 self.addCleanup(smtp.close)
1185 self.assertRaises(UnicodeEncodeError, smtp.sendmail, 'Alice', 'Böb', '')
1186 self.assertRaises(UnicodeEncodeError, smtp.mail, 'Älice')
1187
chason48ed88a2018-07-26 04:01:28 +09001188 def test_send_message_error_on_non_ascii_addrs_if_no_smtputf8(self):
1189 # This test is located here and not in the SMTPUTF8SimTests
1190 # class because it needs a "regular" SMTP server to work
1191 msg = EmailMessage()
1192 msg['From'] = "Páolo <főo@bar.com>"
1193 msg['To'] = 'Dinsdale'
1194 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1195 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001196 HOST, self.port, local_hostname='localhost',
1197 timeout=support.LOOPBACK_TIMEOUT)
chason48ed88a2018-07-26 04:01:28 +09001198 self.addCleanup(smtp.close)
1199 with self.assertRaises(smtplib.SMTPNotSupportedError):
1200 smtp.send_message(msg)
1201
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +01001202 def test_name_field_not_included_in_envelop_addresses(self):
1203 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001204 HOST, self.port, local_hostname='localhost',
1205 timeout=support.LOOPBACK_TIMEOUT)
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +01001206 self.addCleanup(smtp.close)
1207
1208 message = EmailMessage()
1209 message['From'] = email.utils.formataddr(('Michaël', 'michael@example.com'))
1210 message['To'] = email.utils.formataddr(('René', 'rene@example.com'))
1211
1212 self.assertDictEqual(smtp.send_message(message), {})
1213
1214 self.assertEqual(self.serv._addresses['from'], 'michael@example.com')
1215 self.assertEqual(self.serv._addresses['tos'], ['rene@example.com'])
1216
R David Murraycee7cf62015-05-16 13:58:14 -04001217
1218class SimSMTPUTF8Server(SimSMTPServer):
1219
1220 def __init__(self, *args, **kw):
1221 # The base SMTP server turns these on automatically, but our test
1222 # server is set up to munge the EHLO response, so we need to provide
1223 # them as well. And yes, the call is to SMTPServer not SimSMTPServer.
1224 self._extra_features = ['SMTPUTF8', '8BITMIME']
1225 smtpd.SMTPServer.__init__(self, *args, **kw)
1226
1227 def handle_accepted(self, conn, addr):
1228 self._SMTPchannel = self.channel_class(
1229 self._extra_features, self, conn, addr,
1230 decode_data=self._decode_data,
1231 enable_SMTPUTF8=self.enable_SMTPUTF8,
1232 )
1233
1234 def process_message(self, peer, mailfrom, rcpttos, data, mail_options=None,
1235 rcpt_options=None):
1236 self.last_peer = peer
1237 self.last_mailfrom = mailfrom
1238 self.last_rcpttos = rcpttos
1239 self.last_message = data
1240 self.last_mail_options = mail_options
1241 self.last_rcpt_options = rcpt_options
1242
1243
R David Murraycee7cf62015-05-16 13:58:14 -04001244class SMTPUTF8SimTests(unittest.TestCase):
1245
R David Murray83084442015-05-17 19:27:22 -04001246 maxDiff = None
1247
R David Murraycee7cf62015-05-16 13:58:14 -04001248 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001249 self.thread_key = threading_setup()
R David Murraycee7cf62015-05-16 13:58:14 -04001250 self.real_getfqdn = socket.getfqdn
1251 socket.getfqdn = mock_socket.getfqdn
1252 self.serv_evt = threading.Event()
1253 self.client_evt = threading.Event()
1254 # Pick a random unused port by passing 0 for the port number
1255 self.serv = SimSMTPUTF8Server((HOST, 0), ('nowhere', -1),
1256 decode_data=False,
1257 enable_SMTPUTF8=True)
1258 # Keep a note of what port was assigned
1259 self.port = self.serv.socket.getsockname()[1]
1260 serv_args = (self.serv, self.serv_evt, self.client_evt)
1261 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1262 self.thread.start()
1263
1264 # wait until server thread has assigned a port number
1265 self.serv_evt.wait()
1266 self.serv_evt.clear()
1267
1268 def tearDown(self):
1269 socket.getfqdn = self.real_getfqdn
1270 # indicate that the client is finished
1271 self.client_evt.set()
1272 # wait for the server thread to terminate
1273 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001274 join_thread(self.thread)
1275 del self.thread
1276 self.doCleanups()
1277 threading_cleanup(*self.thread_key)
R David Murraycee7cf62015-05-16 13:58:14 -04001278
1279 def test_test_server_supports_extensions(self):
1280 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001281 HOST, self.port, local_hostname='localhost',
1282 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001283 self.addCleanup(smtp.close)
1284 smtp.ehlo()
1285 self.assertTrue(smtp.does_esmtp)
1286 self.assertTrue(smtp.has_extn('smtputf8'))
1287
1288 def test_send_unicode_with_SMTPUTF8_via_sendmail(self):
1289 m = '¡a test message containing unicode!'.encode('utf-8')
1290 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001291 HOST, self.port, local_hostname='localhost',
1292 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001293 self.addCleanup(smtp.close)
1294 smtp.sendmail('Jőhn', 'Sálly', m,
1295 mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1296 self.assertEqual(self.serv.last_mailfrom, 'Jőhn')
1297 self.assertEqual(self.serv.last_rcpttos, ['Sálly'])
1298 self.assertEqual(self.serv.last_message, m)
1299 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1300 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1301 self.assertEqual(self.serv.last_rcpt_options, [])
1302
1303 def test_send_unicode_with_SMTPUTF8_via_low_level_API(self):
1304 m = '¡a test message containing unicode!'.encode('utf-8')
1305 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001306 HOST, self.port, local_hostname='localhost',
1307 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001308 self.addCleanup(smtp.close)
1309 smtp.ehlo()
1310 self.assertEqual(
1311 smtp.mail('Jő', options=['BODY=8BITMIME', 'SMTPUTF8']),
1312 (250, b'OK'))
1313 self.assertEqual(smtp.rcpt('János'), (250, b'OK'))
1314 self.assertEqual(smtp.data(m), (250, b'OK'))
1315 self.assertEqual(self.serv.last_mailfrom, 'Jő')
1316 self.assertEqual(self.serv.last_rcpttos, ['János'])
1317 self.assertEqual(self.serv.last_message, m)
1318 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1319 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1320 self.assertEqual(self.serv.last_rcpt_options, [])
1321
R David Murray83084442015-05-17 19:27:22 -04001322 def test_send_message_uses_smtputf8_if_addrs_non_ascii(self):
1323 msg = EmailMessage()
1324 msg['From'] = "Páolo <főo@bar.com>"
1325 msg['To'] = 'Dinsdale'
1326 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1327 # XXX I don't know why I need two \n's here, but this is an existing
1328 # bug (if it is one) and not a problem with the new functionality.
1329 msg.set_content("oh là là, know what I mean, know what I mean?\n\n")
1330 # XXX smtpd converts received /r/n to /n, so we can't easily test that
1331 # we are successfully sending /r/n :(.
1332 expected = textwrap.dedent("""\
1333 From: Páolo <főo@bar.com>
1334 To: Dinsdale
1335 Subject: Nudge nudge, wink, wink \u1F609
1336 Content-Type: text/plain; charset="utf-8"
1337 Content-Transfer-Encoding: 8bit
1338 MIME-Version: 1.0
1339
1340 oh là là, know what I mean, know what I mean?
1341 """)
1342 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001343 HOST, self.port, local_hostname='localhost',
1344 timeout=support.LOOPBACK_TIMEOUT)
R David Murray83084442015-05-17 19:27:22 -04001345 self.addCleanup(smtp.close)
1346 self.assertEqual(smtp.send_message(msg), {})
1347 self.assertEqual(self.serv.last_mailfrom, 'főo@bar.com')
1348 self.assertEqual(self.serv.last_rcpttos, ['Dinsdale'])
1349 self.assertEqual(self.serv.last_message.decode(), expected)
1350 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1351 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1352 self.assertEqual(self.serv.last_rcpt_options, [])
1353
Guido van Rossum04110fb2007-08-24 16:32:05 +00001354
Barry Warsawc5ea7542015-07-09 10:39:55 -04001355EXPECTED_RESPONSE = encode_base64(b'\0psu\0doesnotexist', eol='')
1356
1357class SimSMTPAUTHInitialResponseChannel(SimSMTPChannel):
1358 def smtp_AUTH(self, arg):
1359 # RFC 4954's AUTH command allows for an optional initial-response.
1360 # Not all AUTH methods support this; some require a challenge. AUTH
1361 # PLAIN does those, so test that here. See issue #15014.
1362 args = arg.split()
1363 if args[0].lower() == 'plain':
1364 if len(args) == 2:
1365 # AUTH PLAIN <initial-response> with the response base 64
1366 # encoded. Hard code the expected response for the test.
1367 if args[1] == EXPECTED_RESPONSE:
1368 self.push('235 Ok')
1369 return
1370 self.push('571 Bad authentication')
1371
1372class SimSMTPAUTHInitialResponseServer(SimSMTPServer):
1373 channel_class = SimSMTPAUTHInitialResponseChannel
1374
1375
Barry Warsawc5ea7542015-07-09 10:39:55 -04001376class SMTPAUTHInitialResponseSimTests(unittest.TestCase):
1377 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001378 self.thread_key = threading_setup()
Barry Warsawc5ea7542015-07-09 10:39:55 -04001379 self.real_getfqdn = socket.getfqdn
1380 socket.getfqdn = mock_socket.getfqdn
1381 self.serv_evt = threading.Event()
1382 self.client_evt = threading.Event()
1383 # Pick a random unused port by passing 0 for the port number
1384 self.serv = SimSMTPAUTHInitialResponseServer(
1385 (HOST, 0), ('nowhere', -1), decode_data=True)
1386 # Keep a note of what port was assigned
1387 self.port = self.serv.socket.getsockname()[1]
1388 serv_args = (self.serv, self.serv_evt, self.client_evt)
1389 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1390 self.thread.start()
1391
1392 # wait until server thread has assigned a port number
1393 self.serv_evt.wait()
1394 self.serv_evt.clear()
1395
1396 def tearDown(self):
1397 socket.getfqdn = self.real_getfqdn
1398 # indicate that the client is finished
1399 self.client_evt.set()
1400 # wait for the server thread to terminate
1401 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001402 join_thread(self.thread)
1403 del self.thread
1404 self.doCleanups()
1405 threading_cleanup(*self.thread_key)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001406
1407 def testAUTH_PLAIN_initial_response_login(self):
1408 self.serv.add_feature('AUTH PLAIN')
Victor Stinner7772b1a2019-12-11 22:17:04 +01001409 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1410 timeout=support.LOOPBACK_TIMEOUT)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001411 smtp.login('psu', 'doesnotexist')
1412 smtp.close()
1413
1414 def testAUTH_PLAIN_initial_response_auth(self):
1415 self.serv.add_feature('AUTH PLAIN')
Victor Stinner7772b1a2019-12-11 22:17:04 +01001416 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1417 timeout=support.LOOPBACK_TIMEOUT)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001418 smtp.user = 'psu'
1419 smtp.password = 'doesnotexist'
1420 code, response = smtp.auth('plain', smtp.auth_plain)
1421 smtp.close()
1422 self.assertEqual(code, 235)
1423
1424
Guido van Rossumd8faa362007-04-27 19:54:29 +00001425if __name__ == '__main__':
chason48ed88a2018-07-26 04:01:28 +09001426 unittest.main()