blob: cc5c4b13464887b8d61098ff6db7e7ebb5364d79 [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
Dong-hee Na62e39732020-01-14 16:49:59 +0900125 def testTimeoutZero(self):
126 mock_socket.reply_with(b"220 Hola mundo")
127 with self.assertRaises(ValueError):
128 smtplib.SMTP(HOST, self.port, timeout=0)
129
Georg Brandlf78e02b2008-06-10 17:40:04 +0000130 def testTimeoutValue(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000131 mock_socket.reply_with(b"220 Hola mundo")
Georg Brandlf78e02b2008-06-10 17:40:04 +0000132 smtp = smtplib.SMTP(HOST, self.port, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000133 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000134 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000135
R David Murray0c49b892015-04-16 17:14:42 -0400136 def test_debuglevel(self):
137 mock_socket.reply_with(b"220 Hello world")
138 smtp = smtplib.SMTP()
139 smtp.set_debuglevel(1)
140 with support.captured_stderr() as stderr:
141 smtp.connect(HOST, self.port)
142 smtp.close()
143 expected = re.compile(r"^connect:", re.MULTILINE)
144 self.assertRegex(stderr.getvalue(), expected)
145
146 def test_debuglevel_2(self):
147 mock_socket.reply_with(b"220 Hello world")
148 smtp = smtplib.SMTP()
149 smtp.set_debuglevel(2)
150 with support.captured_stderr() as stderr:
151 smtp.connect(HOST, self.port)
152 smtp.close()
153 expected = re.compile(r"^\d{2}:\d{2}:\d{2}\.\d{6} connect: ",
154 re.MULTILINE)
155 self.assertRegex(stderr.getvalue(), expected)
156
Guido van Rossumd8faa362007-04-27 19:54:29 +0000157
Guido van Rossum04110fb2007-08-24 16:32:05 +0000158# Test server thread using the specified SMTP server class
Christian Heimes5e696852008-04-09 08:37:03 +0000159def debugging_server(serv, serv_evt, client_evt):
Christian Heimes380f7f22008-02-28 11:19:05 +0000160 serv_evt.set()
Guido van Rossum806c2462007-08-06 23:33:07 +0000161
162 try:
163 if hasattr(select, 'poll'):
164 poll_fun = asyncore.poll2
165 else:
166 poll_fun = asyncore.poll
167
168 n = 1000
169 while asyncore.socket_map and n > 0:
170 poll_fun(0.01, asyncore.socket_map)
171
172 # when the client conversation is finished, it will
173 # set client_evt, and it's then ok to kill the server
Benjamin Peterson672b8032008-06-11 19:14:14 +0000174 if client_evt.is_set():
Guido van Rossum806c2462007-08-06 23:33:07 +0000175 serv.close()
176 break
177
178 n -= 1
179
180 except socket.timeout:
181 pass
182 finally:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000183 if not client_evt.is_set():
Christian Heimes380f7f22008-02-28 11:19:05 +0000184 # allow some time for the client to read the result
185 time.sleep(0.5)
186 serv.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000187 asyncore.close_all()
Guido van Rossum806c2462007-08-06 23:33:07 +0000188 serv_evt.set()
189
190MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
191MSG_END = '------------ END MESSAGE ------------\n'
192
Guido van Rossum04110fb2007-08-24 16:32:05 +0000193# NOTE: Some SMTP objects in the tests below are created with a non-default
194# local_hostname argument to the constructor, since (on some systems) the FQDN
195# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000196# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000197
198# Test behavior of smtpd.DebuggingServer
Victor Stinner45df8202010-04-28 22:31:17 +0000199class DebuggingServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000200
R. David Murray7dff9e02010-11-08 17:15:13 +0000201 maxDiff = None
202
Guido van Rossum806c2462007-08-06 23:33:07 +0000203 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100204 self.thread_key = threading_setup()
Richard Jones64b02de2010-08-03 06:39:33 +0000205 self.real_getfqdn = socket.getfqdn
206 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000207 # temporarily replace sys.stdout to capture DebuggingServer output
208 self.old_stdout = sys.stdout
209 self.output = io.StringIO()
210 sys.stdout = self.output
211
212 self.serv_evt = threading.Event()
213 self.client_evt = threading.Event()
R. David Murray7dff9e02010-11-08 17:15:13 +0000214 # Capture SMTPChannel debug output
215 self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
216 smtpd.DEBUGSTREAM = io.StringIO()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000217 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400218 self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1),
219 decode_data=True)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700220 # Keep a note of what server host and port were assigned
221 self.host, self.port = self.serv.socket.getsockname()[:2]
Christian Heimes5e696852008-04-09 08:37:03 +0000222 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000223 self.thread = threading.Thread(target=debugging_server, args=serv_args)
224 self.thread.start()
Guido van Rossum806c2462007-08-06 23:33:07 +0000225
226 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000227 self.serv_evt.wait()
228 self.serv_evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000229
230 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000231 socket.getfqdn = self.real_getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000232 # indicate that the client is finished
233 self.client_evt.set()
234 # wait for the server thread to terminate
235 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100236 join_thread(self.thread)
Guido van Rossum806c2462007-08-06 23:33:07 +0000237 # restore sys.stdout
238 sys.stdout = self.old_stdout
R. David Murray7dff9e02010-11-08 17:15:13 +0000239 # restore DEBUGSTREAM
240 smtpd.DEBUGSTREAM.close()
241 smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100242 del self.thread
243 self.doCleanups()
244 threading_cleanup(*self.thread_key)
Guido van Rossum806c2462007-08-06 23:33:07 +0000245
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700246 def get_output_without_xpeer(self):
247 test_output = self.output.getvalue()
248 return re.sub(r'(.*?)^X-Peer:\s*\S+\n(.*)', r'\1\2',
249 test_output, flags=re.MULTILINE|re.DOTALL)
250
Guido van Rossum806c2462007-08-06 23:33:07 +0000251 def testBasic(self):
252 # connect
Victor Stinner07871b22019-12-10 20:32:59 +0100253 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
254 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum806c2462007-08-06 23:33:07 +0000255 smtp.quit()
256
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800257 def testSourceAddress(self):
258 # connect
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700259 src_port = support.find_unused_port()
Senthil Kumaranb351a482011-07-31 09:14:17 +0800260 try:
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700261 smtp = smtplib.SMTP(self.host, self.port, local_hostname='localhost',
Victor Stinner07871b22019-12-10 20:32:59 +0100262 timeout=support.LOOPBACK_TIMEOUT,
263 source_address=(self.host, src_port))
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100264 self.addCleanup(smtp.close)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700265 self.assertEqual(smtp.source_address, (self.host, src_port))
Senthil Kumaranb351a482011-07-31 09:14:17 +0800266 self.assertEqual(smtp.local_hostname, 'localhost')
267 smtp.quit()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200268 except OSError as e:
Senthil Kumaranb351a482011-07-31 09:14:17 +0800269 if e.errno == errno.EADDRINUSE:
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700270 self.skipTest("couldn't bind to source port %d" % src_port)
Senthil Kumaranb351a482011-07-31 09:14:17 +0800271 raise
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800272
Guido van Rossum04110fb2007-08-24 16:32:05 +0000273 def testNOOP(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100274 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
275 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100276 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400277 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000278 self.assertEqual(smtp.noop(), expected)
279 smtp.quit()
280
281 def testRSET(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100282 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
283 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100284 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400285 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000286 self.assertEqual(smtp.rset(), expected)
287 smtp.quit()
288
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400289 def testELHO(self):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000290 # EHLO isn't implemented in DebuggingServer
Victor Stinner07871b22019-12-10 20:32:59 +0100291 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
292 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100293 self.addCleanup(smtp.close)
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400294 expected = (250, b'\nSIZE 33554432\nHELP')
Guido van Rossum806c2462007-08-06 23:33:07 +0000295 self.assertEqual(smtp.ehlo(), expected)
296 smtp.quit()
297
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400298 def testEXPNNotImplemented(self):
R David Murrayd1a30c92012-05-26 14:33:59 -0400299 # EXPN isn't implemented in DebuggingServer
Victor Stinner07871b22019-12-10 20:32:59 +0100300 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
301 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100302 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400303 expected = (502, b'EXPN not implemented')
304 smtp.putcmd('EXPN')
305 self.assertEqual(smtp.getreply(), expected)
306 smtp.quit()
307
308 def testVRFY(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100309 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
310 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100311 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400312 expected = (252, b'Cannot VRFY user, but will accept message ' + \
313 b'and attempt delivery')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000314 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
315 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
316 smtp.quit()
317
318 def testSecondHELO(self):
319 # check that a second HELO returns a message that it's a duplicate
320 # (this behavior is specific to smtpd.SMTPChannel)
Victor Stinner07871b22019-12-10 20:32:59 +0100321 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
322 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100323 self.addCleanup(smtp.close)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000324 smtp.helo()
325 expected = (503, b'Duplicate HELO/EHLO')
326 self.assertEqual(smtp.helo(), expected)
327 smtp.quit()
328
Guido van Rossum806c2462007-08-06 23:33:07 +0000329 def testHELP(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100330 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
331 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100332 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400333 self.assertEqual(smtp.help(), b'Supported commands: EHLO HELO MAIL ' + \
334 b'RCPT DATA RSET NOOP QUIT VRFY')
Guido van Rossum806c2462007-08-06 23:33:07 +0000335 smtp.quit()
336
337 def testSend(self):
338 # connect and send mail
339 m = 'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100340 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
341 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100342 self.addCleanup(smtp.close)
Guido van Rossum806c2462007-08-06 23:33:07 +0000343 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000344 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
345 # in asyncore. This sleep might help, but should really be fixed
346 # properly by using an Event variable.
347 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000348 smtp.quit()
349
350 self.client_evt.set()
351 self.serv_evt.wait()
352 self.output.flush()
353 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
354 self.assertEqual(self.output.getvalue(), mexpect)
355
R. David Murray7dff9e02010-11-08 17:15:13 +0000356 def testSendBinary(self):
357 m = b'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100358 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
359 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100360 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000361 smtp.sendmail('John', 'Sally', m)
362 # XXX (see comment in testSend)
363 time.sleep(0.01)
364 smtp.quit()
365
366 self.client_evt.set()
367 self.serv_evt.wait()
368 self.output.flush()
369 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
370 self.assertEqual(self.output.getvalue(), mexpect)
371
R David Murray0f663d02011-06-09 15:05:57 -0400372 def testSendNeedingDotQuote(self):
373 # Issue 12283
374 m = '.A test\n.mes.sage.'
Victor Stinner07871b22019-12-10 20:32:59 +0100375 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
376 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100377 self.addCleanup(smtp.close)
R David Murray0f663d02011-06-09 15:05:57 -0400378 smtp.sendmail('John', 'Sally', m)
379 # XXX (see comment in testSend)
380 time.sleep(0.01)
381 smtp.quit()
382
383 self.client_evt.set()
384 self.serv_evt.wait()
385 self.output.flush()
386 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
387 self.assertEqual(self.output.getvalue(), mexpect)
388
R David Murray46346762011-07-18 21:38:54 -0400389 def testSendNullSender(self):
390 m = 'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100391 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
392 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100393 self.addCleanup(smtp.close)
R David Murray46346762011-07-18 21:38:54 -0400394 smtp.sendmail('<>', 'Sally', m)
395 # XXX (see comment in testSend)
396 time.sleep(0.01)
397 smtp.quit()
398
399 self.client_evt.set()
400 self.serv_evt.wait()
401 self.output.flush()
402 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
403 self.assertEqual(self.output.getvalue(), mexpect)
404 debugout = smtpd.DEBUGSTREAM.getvalue()
405 sender = re.compile("^sender: <>$", re.MULTILINE)
406 self.assertRegex(debugout, sender)
407
R. David Murray7dff9e02010-11-08 17:15:13 +0000408 def testSendMessage(self):
409 m = email.mime.text.MIMEText('A test message')
Victor Stinner07871b22019-12-10 20:32:59 +0100410 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
411 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100412 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000413 smtp.send_message(m, from_addr='John', to_addrs='Sally')
414 # XXX (see comment in testSend)
415 time.sleep(0.01)
416 smtp.quit()
417
418 self.client_evt.set()
419 self.serv_evt.wait()
420 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700421 # Remove the X-Peer header that DebuggingServer adds as figuring out
422 # exactly what IP address format is put there is not easy (and
423 # irrelevant to our test). Typically 127.0.0.1 or ::1, but it is
424 # not always the same as socket.gethostbyname(HOST). :(
425 test_output = self.get_output_without_xpeer()
426 del m['X-Peer']
R. David Murray7dff9e02010-11-08 17:15:13 +0000427 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700428 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000429
430 def testSendMessageWithAddresses(self):
431 m = email.mime.text.MIMEText('A test message')
432 m['From'] = 'foo@bar.com'
433 m['To'] = 'John'
434 m['CC'] = 'Sally, Fred'
435 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
Victor Stinner07871b22019-12-10 20:32:59 +0100436 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
437 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100438 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000439 smtp.send_message(m)
440 # XXX (see comment in testSend)
441 time.sleep(0.01)
442 smtp.quit()
R David Murrayac4e5ab2011-07-02 21:03:19 -0400443 # make sure the Bcc header is still in the message.
444 self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
445 '<warped@silly.walks.com>')
R. David Murray7dff9e02010-11-08 17:15:13 +0000446
447 self.client_evt.set()
448 self.serv_evt.wait()
449 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700450 # Remove the X-Peer header that DebuggingServer adds.
451 test_output = self.get_output_without_xpeer()
452 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400453 # The Bcc header should not be transmitted.
R. David Murray7dff9e02010-11-08 17:15:13 +0000454 del m['Bcc']
455 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700456 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000457 debugout = smtpd.DEBUGSTREAM.getvalue()
458 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000459 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000460 for addr in ('John', 'Sally', 'Fred', 'root@localhost',
461 'warped@silly.walks.com'):
462 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
463 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000464 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000465
466 def testSendMessageWithSomeAddresses(self):
467 # Make sure nothing breaks if not all of the three 'to' headers exist
468 m = email.mime.text.MIMEText('A test message')
469 m['From'] = 'foo@bar.com'
470 m['To'] = 'John, Dinsdale'
Victor Stinner07871b22019-12-10 20:32:59 +0100471 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
472 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100473 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000474 smtp.send_message(m)
475 # XXX (see comment in testSend)
476 time.sleep(0.01)
477 smtp.quit()
478
479 self.client_evt.set()
480 self.serv_evt.wait()
481 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700482 # Remove the X-Peer header that DebuggingServer adds.
483 test_output = self.get_output_without_xpeer()
484 del m['X-Peer']
R. David Murray7dff9e02010-11-08 17:15:13 +0000485 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700486 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000487 debugout = smtpd.DEBUGSTREAM.getvalue()
488 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000489 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000490 for addr in ('John', 'Dinsdale'):
491 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
492 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000493 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000494
R David Murrayac4e5ab2011-07-02 21:03:19 -0400495 def testSendMessageWithSpecifiedAddresses(self):
496 # Make sure addresses specified in call override those in message.
497 m = email.mime.text.MIMEText('A test message')
498 m['From'] = 'foo@bar.com'
499 m['To'] = 'John, Dinsdale'
Victor Stinner07871b22019-12-10 20:32:59 +0100500 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
501 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100502 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400503 smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
504 # XXX (see comment in testSend)
505 time.sleep(0.01)
506 smtp.quit()
507
508 self.client_evt.set()
509 self.serv_evt.wait()
510 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700511 # Remove the X-Peer header that DebuggingServer adds.
512 test_output = self.get_output_without_xpeer()
513 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400514 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700515 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400516 debugout = smtpd.DEBUGSTREAM.getvalue()
517 sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
518 self.assertRegex(debugout, sender)
519 for addr in ('John', 'Dinsdale'):
520 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
521 re.MULTILINE)
522 self.assertNotRegex(debugout, to_addr)
523 recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
524 self.assertRegex(debugout, recip)
525
526 def testSendMessageWithMultipleFrom(self):
527 # Sender overrides To
528 m = email.mime.text.MIMEText('A test message')
529 m['From'] = 'Bernard, Bianca'
530 m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com'
531 m['To'] = 'John, Dinsdale'
Victor Stinner07871b22019-12-10 20:32:59 +0100532 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
533 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100534 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400535 smtp.send_message(m)
536 # XXX (see comment in testSend)
537 time.sleep(0.01)
538 smtp.quit()
539
540 self.client_evt.set()
541 self.serv_evt.wait()
542 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700543 # Remove the X-Peer header that DebuggingServer adds.
544 test_output = self.get_output_without_xpeer()
545 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400546 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700547 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400548 debugout = smtpd.DEBUGSTREAM.getvalue()
549 sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
550 self.assertRegex(debugout, sender)
551 for addr in ('John', 'Dinsdale'):
552 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
553 re.MULTILINE)
554 self.assertRegex(debugout, to_addr)
555
556 def testSendMessageResent(self):
557 m = email.mime.text.MIMEText('A test message')
558 m['From'] = 'foo@bar.com'
559 m['To'] = 'John'
560 m['CC'] = 'Sally, Fred'
561 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
562 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
563 m['Resent-From'] = 'holy@grail.net'
564 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
565 m['Resent-Bcc'] = 'doe@losthope.net'
Victor Stinner07871b22019-12-10 20:32:59 +0100566 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
567 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100568 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400569 smtp.send_message(m)
570 # XXX (see comment in testSend)
571 time.sleep(0.01)
572 smtp.quit()
573
574 self.client_evt.set()
575 self.serv_evt.wait()
576 self.output.flush()
577 # The Resent-Bcc headers are deleted before serialization.
578 del m['Bcc']
579 del m['Resent-Bcc']
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700580 # Remove the X-Peer header that DebuggingServer adds.
581 test_output = self.get_output_without_xpeer()
582 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400583 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700584 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400585 debugout = smtpd.DEBUGSTREAM.getvalue()
586 sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
587 self.assertRegex(debugout, sender)
588 for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
589 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
590 re.MULTILINE)
591 self.assertRegex(debugout, to_addr)
592
593 def testSendMessageMultipleResentRaises(self):
594 m = email.mime.text.MIMEText('A test message')
595 m['From'] = 'foo@bar.com'
596 m['To'] = 'John'
597 m['CC'] = 'Sally, Fred'
598 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
599 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
600 m['Resent-From'] = 'holy@grail.net'
601 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
602 m['Resent-Bcc'] = 'doe@losthope.net'
603 m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
604 m['Resent-To'] = 'holy@grail.net'
605 m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
Victor Stinner07871b22019-12-10 20:32:59 +0100606 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
607 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100608 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400609 with self.assertRaises(ValueError):
610 smtp.send_message(m)
611 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000612
Victor Stinner45df8202010-04-28 22:31:17 +0000613class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000614
615 def testNotConnected(self):
616 # Test various operations on an unconnected SMTP object that
617 # should raise exceptions (at present the attempt in SMTP.send
618 # to reference the nonexistent 'sock' attribute of the SMTP object
619 # causes an AttributeError)
620 smtp = smtplib.SMTP()
621 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
622 self.assertRaises(smtplib.SMTPServerDisconnected,
623 smtp.send, 'test msg')
624
625 def testNonnumericPort(self):
Andrew Svetlov0832af62012-12-18 23:10:48 +0200626 # check that non-numeric port raises OSError
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200627 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000628 "localhost", "bogus")
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200629 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000630 "localhost:bogus")
631
Romuald Brunet7b313972018-10-09 16:31:55 +0200632 def testSockAttributeExists(self):
633 # check that sock attribute is present outside of a connect() call
634 # (regression test, the previous behavior raised an
635 # AttributeError: 'SMTP' object has no attribute 'sock')
636 with smtplib.SMTP() as smtp:
637 self.assertIsNone(smtp.sock)
638
Christian Heimes380f7f22008-02-28 11:19:05 +0000639
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +0200640class DefaultArgumentsTests(unittest.TestCase):
641
642 def setUp(self):
643 self.msg = EmailMessage()
644 self.msg['From'] = 'Páolo <főo@bar.com>'
645 self.smtp = smtplib.SMTP()
646 self.smtp.ehlo = Mock(return_value=(200, 'OK'))
647 self.smtp.has_extn, self.smtp.sendmail = Mock(), Mock()
648
649 def testSendMessage(self):
650 expected_mail_options = ('SMTPUTF8', 'BODY=8BITMIME')
651 self.smtp.send_message(self.msg)
652 self.smtp.send_message(self.msg)
653 self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
654 expected_mail_options)
655 self.assertEqual(self.smtp.sendmail.call_args_list[1][0][3],
656 expected_mail_options)
657
658 def testSendMessageWithMailOptions(self):
659 mail_options = ['STARTTLS']
660 expected_mail_options = ('STARTTLS', 'SMTPUTF8', 'BODY=8BITMIME')
661 self.smtp.send_message(self.msg, None, None, mail_options)
662 self.assertEqual(mail_options, ['STARTTLS'])
663 self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
664 expected_mail_options)
665
666
Guido van Rossum04110fb2007-08-24 16:32:05 +0000667# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000668class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000669
670 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000671 smtplib.socket = mock_socket
672 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000673 self.old_stdout = sys.stdout
674 self.output = io.StringIO()
675 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000676 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000677
678 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000679 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000680 sys.stdout = self.old_stdout
681
682 def testFailingHELO(self):
683 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000684 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000685
Guido van Rossum04110fb2007-08-24 16:32:05 +0000686
Georg Brandlb38b5c42014-02-10 22:11:21 +0100687class TooLongLineTests(unittest.TestCase):
688 respdata = b'250 OK' + (b'.' * smtplib._MAXLINE * 2) + b'\n'
689
690 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100691 self.thread_key = threading_setup()
Georg Brandlb38b5c42014-02-10 22:11:21 +0100692 self.old_stdout = sys.stdout
693 self.output = io.StringIO()
694 sys.stdout = self.output
695
696 self.evt = threading.Event()
697 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
698 self.sock.settimeout(15)
699 self.port = support.bind_port(self.sock)
700 servargs = (self.evt, self.respdata, self.sock)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100701 self.thread = threading.Thread(target=server, args=servargs)
702 self.thread.start()
Georg Brandlb38b5c42014-02-10 22:11:21 +0100703 self.evt.wait()
704 self.evt.clear()
705
706 def tearDown(self):
707 self.evt.wait()
708 sys.stdout = self.old_stdout
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100709 join_thread(self.thread)
710 del self.thread
711 self.doCleanups()
712 threading_cleanup(*self.thread_key)
Georg Brandlb38b5c42014-02-10 22:11:21 +0100713
714 def testLineTooLong(self):
715 self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
716 HOST, self.port, 'localhost', 3)
717
718
Guido van Rossum04110fb2007-08-24 16:32:05 +0000719sim_users = {'Mr.A@somewhere.com':'John A',
R David Murray46346762011-07-18 21:38:54 -0400720 'Ms.B@xn--fo-fka.com':'Sally B',
Guido van Rossum04110fb2007-08-24 16:32:05 +0000721 'Mrs.C@somewhereesle.com':'Ruth C',
722 }
723
R. David Murraycaa27b72009-05-23 18:49:56 +0000724sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000725sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
726 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000727sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
R David Murray46346762011-07-18 21:38:54 -0400728 'list-2':['Ms.B@xn--fo-fka.com',],
Guido van Rossum04110fb2007-08-24 16:32:05 +0000729 }
730
731# Simulated SMTP channel & server
R David Murrayb0deeb42015-11-08 01:03:52 -0500732class ResponseException(Exception): pass
Guido van Rossum04110fb2007-08-24 16:32:05 +0000733class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000734
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400735 quit_response = None
R David Murrayd312c742013-03-20 20:36:14 -0400736 mail_response = None
737 rcpt_response = None
738 data_response = None
739 rcpt_count = 0
740 rset_count = 0
R David Murrayafb151a2014-04-14 18:21:38 -0400741 disconnect = 0
R David Murrayb0deeb42015-11-08 01:03:52 -0500742 AUTH = 99 # Add protocol state to enable auth testing.
743 authenticated_user = None
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400744
R. David Murray23ddc0e2009-05-29 18:03:16 +0000745 def __init__(self, extra_features, *args, **kw):
746 self._extrafeatures = ''.join(
747 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000748 super(SimSMTPChannel, self).__init__(*args, **kw)
749
R David Murrayb0deeb42015-11-08 01:03:52 -0500750 # AUTH related stuff. It would be nice if support for this were in smtpd.
751 def found_terminator(self):
752 if self.smtp_state == self.AUTH:
753 line = self._emptystring.join(self.received_lines)
754 print('Data:', repr(line), file=smtpd.DEBUGSTREAM)
755 self.received_lines = []
756 try:
757 self.auth_object(line)
758 except ResponseException as e:
759 self.smtp_state = self.COMMAND
760 self.push('%s %s' % (e.smtp_code, e.smtp_error))
761 return
762 super().found_terminator()
763
764
765 def smtp_AUTH(self, arg):
766 if not self.seen_greeting:
767 self.push('503 Error: send EHLO first')
768 return
769 if not self.extended_smtp or 'AUTH' not in self._extrafeatures:
770 self.push('500 Error: command "AUTH" not recognized')
771 return
772 if self.authenticated_user is not None:
773 self.push(
774 '503 Bad sequence of commands: already authenticated')
775 return
776 args = arg.split()
777 if len(args) not in [1, 2]:
778 self.push('501 Syntax: AUTH <mechanism> [initial-response]')
779 return
780 auth_object_name = '_auth_%s' % args[0].lower().replace('-', '_')
781 try:
782 self.auth_object = getattr(self, auth_object_name)
783 except AttributeError:
784 self.push('504 Command parameter not implemented: unsupported '
785 ' authentication mechanism {!r}'.format(auth_object_name))
786 return
787 self.smtp_state = self.AUTH
788 self.auth_object(args[1] if len(args) == 2 else None)
789
790 def _authenticated(self, user, valid):
791 if valid:
792 self.authenticated_user = user
793 self.push('235 Authentication Succeeded')
794 else:
795 self.push('535 Authentication credentials invalid')
796 self.smtp_state = self.COMMAND
797
798 def _decode_base64(self, string):
799 return base64.decodebytes(string.encode('ascii')).decode('utf-8')
800
801 def _auth_plain(self, arg=None):
802 if arg is None:
803 self.push('334 ')
804 else:
805 logpass = self._decode_base64(arg)
806 try:
807 *_, user, password = logpass.split('\0')
808 except ValueError as e:
809 self.push('535 Splitting response {!r} into user and password'
810 ' failed: {}'.format(logpass, e))
811 return
812 self._authenticated(user, password == sim_auth[1])
813
814 def _auth_login(self, arg=None):
815 if arg is None:
816 # base64 encoded 'Username:'
817 self.push('334 VXNlcm5hbWU6')
818 elif not hasattr(self, '_auth_login_user'):
819 self._auth_login_user = self._decode_base64(arg)
820 # base64 encoded 'Password:'
821 self.push('334 UGFzc3dvcmQ6')
822 else:
823 password = self._decode_base64(arg)
824 self._authenticated(self._auth_login_user, password == sim_auth[1])
825 del self._auth_login_user
826
827 def _auth_cram_md5(self, arg=None):
828 if arg is None:
829 self.push('334 {}'.format(sim_cram_md5_challenge))
830 else:
831 logpass = self._decode_base64(arg)
832 try:
833 user, hashed_pass = logpass.split()
834 except ValueError as e:
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +0200835 self.push('535 Splitting response {!r} into user and password '
R David Murrayb0deeb42015-11-08 01:03:52 -0500836 'failed: {}'.format(logpass, e))
837 return False
838 valid_hashed_pass = hmac.HMAC(
839 sim_auth[1].encode('ascii'),
840 self._decode_base64(sim_cram_md5_challenge).encode('ascii'),
841 'md5').hexdigest()
842 self._authenticated(user, hashed_pass == valid_hashed_pass)
843 # end AUTH related stuff.
844
Guido van Rossum04110fb2007-08-24 16:32:05 +0000845 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000846 resp = ('250-testhost\r\n'
847 '250-EXPN\r\n'
848 '250-SIZE 20000000\r\n'
849 '250-STARTTLS\r\n'
850 '250-DELIVERBY\r\n')
851 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000852 self.push(resp)
R David Murrayf1a40b42013-03-20 21:12:17 -0400853 self.seen_greeting = arg
854 self.extended_smtp = True
Guido van Rossum04110fb2007-08-24 16:32:05 +0000855
856 def smtp_VRFY(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400857 # For max compatibility smtplib should be sending the raw address.
858 if arg in sim_users:
859 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000860 else:
861 self.push('550 No such user: %s' % arg)
862
863 def smtp_EXPN(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400864 list_name = arg.lower()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000865 if list_name in sim_lists:
866 user_list = sim_lists[list_name]
867 for n, user_email in enumerate(user_list):
868 quoted_addr = smtplib.quoteaddr(user_email)
869 if n < len(user_list) - 1:
870 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
871 else:
872 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
873 else:
874 self.push('550 No access for you!')
875
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400876 def smtp_QUIT(self, arg):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400877 if self.quit_response is None:
878 super(SimSMTPChannel, self).smtp_QUIT(arg)
879 else:
880 self.push(self.quit_response)
881 self.close_when_done()
882
R David Murrayd312c742013-03-20 20:36:14 -0400883 def smtp_MAIL(self, arg):
884 if self.mail_response is None:
885 super().smtp_MAIL(arg)
886 else:
887 self.push(self.mail_response)
R David Murrayafb151a2014-04-14 18:21:38 -0400888 if self.disconnect:
889 self.close_when_done()
R David Murrayd312c742013-03-20 20:36:14 -0400890
891 def smtp_RCPT(self, arg):
892 if self.rcpt_response is None:
893 super().smtp_RCPT(arg)
894 return
R David Murrayd312c742013-03-20 20:36:14 -0400895 self.rcpt_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400896 self.push(self.rcpt_response[self.rcpt_count-1])
R David Murrayd312c742013-03-20 20:36:14 -0400897
898 def smtp_RSET(self, arg):
R David Murrayd312c742013-03-20 20:36:14 -0400899 self.rset_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400900 super().smtp_RSET(arg)
R David Murrayd312c742013-03-20 20:36:14 -0400901
902 def smtp_DATA(self, arg):
903 if self.data_response is None:
904 super().smtp_DATA(arg)
905 else:
906 self.push(self.data_response)
907
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000908 def handle_error(self):
909 raise
910
Guido van Rossum04110fb2007-08-24 16:32:05 +0000911
912class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000913
R David Murrayd312c742013-03-20 20:36:14 -0400914 channel_class = SimSMTPChannel
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400915
R. David Murray23ddc0e2009-05-29 18:03:16 +0000916 def __init__(self, *args, **kw):
917 self._extra_features = []
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +0100918 self._addresses = {}
R. David Murray23ddc0e2009-05-29 18:03:16 +0000919 smtpd.SMTPServer.__init__(self, *args, **kw)
920
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000921 def handle_accepted(self, conn, addr):
R David Murrayf1a40b42013-03-20 21:12:17 -0400922 self._SMTPchannel = self.channel_class(
R David Murray1144da52014-06-11 12:27:40 -0400923 self._extra_features, self, conn, addr,
924 decode_data=self._decode_data)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000925
926 def process_message(self, peer, mailfrom, rcpttos, data):
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +0100927 self._addresses['from'] = mailfrom
928 self._addresses['tos'] = rcpttos
Guido van Rossum04110fb2007-08-24 16:32:05 +0000929
R. David Murrayfb123912009-05-28 18:19:00 +0000930 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000931 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000932
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000933 def handle_error(self):
934 raise
935
Guido van Rossum04110fb2007-08-24 16:32:05 +0000936
937# Test various SMTP & ESMTP commands/behaviors that require a simulated server
938# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000939class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000940
941 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100942 self.thread_key = threading_setup()
Richard Jones64b02de2010-08-03 06:39:33 +0000943 self.real_getfqdn = socket.getfqdn
944 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000945 self.serv_evt = threading.Event()
946 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000947 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400948 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1), decode_data=True)
Antoine Pitrou043bad02010-04-30 23:20:15 +0000949 # Keep a note of what port was assigned
950 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000951 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000952 self.thread = threading.Thread(target=debugging_server, args=serv_args)
953 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000954
955 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000956 self.serv_evt.wait()
957 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000958
959 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000960 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000961 # indicate that the client is finished
962 self.client_evt.set()
963 # wait for the server thread to terminate
964 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100965 join_thread(self.thread)
966 del self.thread
967 self.doCleanups()
968 threading_cleanup(*self.thread_key)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000969
970 def testBasic(self):
971 # smoke test
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 smtp.quit()
975
976 def testEHLO(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +0100977 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
978 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000979
980 # no features should be present before the EHLO
981 self.assertEqual(smtp.esmtp_features, {})
982
983 # features expected from the test server
984 expected_features = {'expn':'',
985 'size': '20000000',
986 'starttls': '',
987 'deliverby': '',
988 'help': '',
989 }
990
991 smtp.ehlo()
992 self.assertEqual(smtp.esmtp_features, expected_features)
993 for k in expected_features:
994 self.assertTrue(smtp.has_extn(k))
995 self.assertFalse(smtp.has_extn('unsupported-feature'))
996 smtp.quit()
997
998 def testVRFY(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +0100999 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1000 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001001
Barry Warsawc5ea7542015-07-09 10:39:55 -04001002 for addr_spec, name in sim_users.items():
Guido van Rossum04110fb2007-08-24 16:32:05 +00001003 expected_known = (250, bytes('%s %s' %
Barry Warsawc5ea7542015-07-09 10:39:55 -04001004 (name, smtplib.quoteaddr(addr_spec)),
Guido van Rossum5a23cc52007-08-30 14:02:43 +00001005 "ascii"))
Barry Warsawc5ea7542015-07-09 10:39:55 -04001006 self.assertEqual(smtp.vrfy(addr_spec), expected_known)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001007
1008 u = 'nobody@nowhere.com'
R David Murray46346762011-07-18 21:38:54 -04001009 expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +00001010 self.assertEqual(smtp.vrfy(u), expected_unknown)
1011 smtp.quit()
1012
1013 def testEXPN(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001014 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1015 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001016
1017 for listname, members in sim_lists.items():
1018 users = []
1019 for m in members:
1020 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +00001021 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +00001022 self.assertEqual(smtp.expn(listname), expected_known)
1023
1024 u = 'PSU-Members-List'
1025 expected_unknown = (550, b'No access for you!')
1026 self.assertEqual(smtp.expn(u), expected_unknown)
1027 smtp.quit()
1028
R David Murray76e13c12014-07-03 14:47:46 -04001029 def testAUTH_PLAIN(self):
1030 self.serv.add_feature("AUTH PLAIN")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001031 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1032 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001033 resp = smtp.login(sim_auth[0], sim_auth[1])
1034 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -04001035 smtp.close()
1036
R. David Murrayfb123912009-05-28 18:19:00 +00001037 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +00001038 self.serv.add_feature("AUTH LOGIN")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001039 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1040 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001041 resp = smtp.login(sim_auth[0], sim_auth[1])
1042 self.assertEqual(resp, (235, b'Authentication Succeeded'))
Benjamin Petersond094efd2010-10-31 17:15:42 +00001043 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +00001044
Christian Heimesc64a1a62019-09-25 16:30:20 +02001045 @requires_hashdigest('md5')
R. David Murrayfb123912009-05-28 18:19:00 +00001046 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +00001047 self.serv.add_feature("AUTH CRAM-MD5")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001048 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1049 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001050 resp = smtp.login(sim_auth[0], sim_auth[1])
1051 self.assertEqual(resp, (235, b'Authentication Succeeded'))
Benjamin Petersond094efd2010-10-31 17:15:42 +00001052 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +00001053
Andrew Kuchling78591822013-11-11 14:03:23 -05001054 def testAUTH_multiple(self):
1055 # Test that multiple authentication methods are tried.
1056 self.serv.add_feature("AUTH BOGUS PLAIN LOGIN CRAM-MD5")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001057 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1058 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001059 resp = smtp.login(sim_auth[0], sim_auth[1])
1060 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -04001061 smtp.close()
1062
1063 def test_auth_function(self):
Christian Heimesc64a1a62019-09-25 16:30:20 +02001064 supported = {'PLAIN', 'LOGIN'}
1065 try:
1066 hashlib.md5()
1067 except ValueError:
1068 pass
1069 else:
1070 supported.add('CRAM-MD5')
R David Murrayb0deeb42015-11-08 01:03:52 -05001071 for mechanism in supported:
1072 self.serv.add_feature("AUTH {}".format(mechanism))
1073 for mechanism in supported:
1074 with self.subTest(mechanism=mechanism):
1075 smtp = smtplib.SMTP(HOST, self.port,
Victor Stinner7772b1a2019-12-11 22:17:04 +01001076 local_hostname='localhost',
1077 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001078 smtp.ehlo('foo')
1079 smtp.user, smtp.password = sim_auth[0], sim_auth[1]
1080 method = 'auth_' + mechanism.lower().replace('-', '_')
1081 resp = smtp.auth(mechanism, getattr(smtp, method))
1082 self.assertEqual(resp, (235, b'Authentication Succeeded'))
1083 smtp.close()
Andrew Kuchling78591822013-11-11 14:03:23 -05001084
R David Murray0cff49f2014-08-30 16:51:59 -04001085 def test_quit_resets_greeting(self):
1086 smtp = smtplib.SMTP(HOST, self.port,
1087 local_hostname='localhost',
Victor Stinner7772b1a2019-12-11 22:17:04 +01001088 timeout=support.LOOPBACK_TIMEOUT)
R David Murray0cff49f2014-08-30 16:51:59 -04001089 code, message = smtp.ehlo()
1090 self.assertEqual(code, 250)
1091 self.assertIn('size', smtp.esmtp_features)
1092 smtp.quit()
1093 self.assertNotIn('size', smtp.esmtp_features)
1094 smtp.connect(HOST, self.port)
1095 self.assertNotIn('size', smtp.esmtp_features)
1096 smtp.ehlo_or_helo_if_needed()
1097 self.assertIn('size', smtp.esmtp_features)
1098 smtp.quit()
1099
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001100 def test_with_statement(self):
1101 with smtplib.SMTP(HOST, self.port) as smtp:
1102 code, message = smtp.noop()
1103 self.assertEqual(code, 250)
1104 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
1105 with smtplib.SMTP(HOST, self.port) as smtp:
1106 smtp.close()
1107 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
1108
1109 def test_with_statement_QUIT_failure(self):
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001110 with self.assertRaises(smtplib.SMTPResponseException) as error:
1111 with smtplib.SMTP(HOST, self.port) as smtp:
1112 smtp.noop()
R David Murray6bd52022013-03-21 00:32:31 -04001113 self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001114 self.assertEqual(error.exception.smtp_code, 421)
1115 self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001116
R. David Murrayfb123912009-05-28 18:19:00 +00001117 #TODO: add tests for correct AUTH method fallback now that the
1118 #test infrastructure can support it.
1119
R David Murrayafb151a2014-04-14 18:21:38 -04001120 # Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception
1121 def test__rest_from_mail_cmd(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001122 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1123 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayafb151a2014-04-14 18:21:38 -04001124 smtp.noop()
1125 self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
1126 self.serv._SMTPchannel.disconnect = True
1127 with self.assertRaises(smtplib.SMTPSenderRefused):
1128 smtp.sendmail('John', 'Sally', 'test message')
1129 self.assertIsNone(smtp.sock)
1130
R David Murrayd312c742013-03-20 20:36:14 -04001131 # Issue 5713: make sure close, not rset, is called if we get a 421 error
1132 def test_421_from_mail_cmd(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001133 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1134 timeout=support.LOOPBACK_TIMEOUT)
R David Murray853c0f92013-03-20 21:54:05 -04001135 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001136 self.serv._SMTPchannel.mail_response = '421 closing connection'
1137 with self.assertRaises(smtplib.SMTPSenderRefused):
1138 smtp.sendmail('John', 'Sally', 'test message')
1139 self.assertIsNone(smtp.sock)
R David Murray03b01162013-03-20 22:11:40 -04001140 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
R David Murrayd312c742013-03-20 20:36:14 -04001141
1142 def test_421_from_rcpt_cmd(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001143 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1144 timeout=support.LOOPBACK_TIMEOUT)
R David Murray853c0f92013-03-20 21:54:05 -04001145 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001146 self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
1147 with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
1148 smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
1149 self.assertIsNone(smtp.sock)
1150 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
1151 self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
1152
1153 def test_421_from_data_cmd(self):
1154 class MySimSMTPChannel(SimSMTPChannel):
1155 def found_terminator(self):
1156 if self.smtp_state == self.DATA:
1157 self.push('421 closing')
1158 else:
1159 super().found_terminator()
1160 self.serv.channel_class = MySimSMTPChannel
Victor Stinner7772b1a2019-12-11 22:17:04 +01001161 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1162 timeout=support.LOOPBACK_TIMEOUT)
R David Murray853c0f92013-03-20 21:54:05 -04001163 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001164 with self.assertRaises(smtplib.SMTPDataError):
1165 smtp.sendmail('John@foo.org', ['Sally@foo.org'], 'test message')
1166 self.assertIsNone(smtp.sock)
1167 self.assertEqual(self.serv._SMTPchannel.rcpt_count, 0)
1168
R David Murraycee7cf62015-05-16 13:58:14 -04001169 def test_smtputf8_NotSupportedError_if_no_server_support(self):
1170 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001171 HOST, self.port, local_hostname='localhost',
1172 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001173 self.addCleanup(smtp.close)
1174 smtp.ehlo()
1175 self.assertTrue(smtp.does_esmtp)
1176 self.assertFalse(smtp.has_extn('smtputf8'))
1177 self.assertRaises(
1178 smtplib.SMTPNotSupportedError,
1179 smtp.sendmail,
1180 'John', 'Sally', '', mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1181 self.assertRaises(
1182 smtplib.SMTPNotSupportedError,
1183 smtp.mail, 'John', options=['BODY=8BITMIME', 'SMTPUTF8'])
1184
1185 def test_send_unicode_without_SMTPUTF8(self):
1186 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001187 HOST, self.port, local_hostname='localhost',
1188 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001189 self.addCleanup(smtp.close)
1190 self.assertRaises(UnicodeEncodeError, smtp.sendmail, 'Alice', 'Böb', '')
1191 self.assertRaises(UnicodeEncodeError, smtp.mail, 'Älice')
1192
chason48ed88a2018-07-26 04:01:28 +09001193 def test_send_message_error_on_non_ascii_addrs_if_no_smtputf8(self):
1194 # This test is located here and not in the SMTPUTF8SimTests
1195 # class because it needs a "regular" SMTP server to work
1196 msg = EmailMessage()
1197 msg['From'] = "Páolo <főo@bar.com>"
1198 msg['To'] = 'Dinsdale'
1199 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1200 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001201 HOST, self.port, local_hostname='localhost',
1202 timeout=support.LOOPBACK_TIMEOUT)
chason48ed88a2018-07-26 04:01:28 +09001203 self.addCleanup(smtp.close)
1204 with self.assertRaises(smtplib.SMTPNotSupportedError):
1205 smtp.send_message(msg)
1206
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +01001207 def test_name_field_not_included_in_envelop_addresses(self):
1208 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001209 HOST, self.port, local_hostname='localhost',
1210 timeout=support.LOOPBACK_TIMEOUT)
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +01001211 self.addCleanup(smtp.close)
1212
1213 message = EmailMessage()
1214 message['From'] = email.utils.formataddr(('Michaël', 'michael@example.com'))
1215 message['To'] = email.utils.formataddr(('René', 'rene@example.com'))
1216
1217 self.assertDictEqual(smtp.send_message(message), {})
1218
1219 self.assertEqual(self.serv._addresses['from'], 'michael@example.com')
1220 self.assertEqual(self.serv._addresses['tos'], ['rene@example.com'])
1221
R David Murraycee7cf62015-05-16 13:58:14 -04001222
1223class SimSMTPUTF8Server(SimSMTPServer):
1224
1225 def __init__(self, *args, **kw):
1226 # The base SMTP server turns these on automatically, but our test
1227 # server is set up to munge the EHLO response, so we need to provide
1228 # them as well. And yes, the call is to SMTPServer not SimSMTPServer.
1229 self._extra_features = ['SMTPUTF8', '8BITMIME']
1230 smtpd.SMTPServer.__init__(self, *args, **kw)
1231
1232 def handle_accepted(self, conn, addr):
1233 self._SMTPchannel = self.channel_class(
1234 self._extra_features, self, conn, addr,
1235 decode_data=self._decode_data,
1236 enable_SMTPUTF8=self.enable_SMTPUTF8,
1237 )
1238
1239 def process_message(self, peer, mailfrom, rcpttos, data, mail_options=None,
1240 rcpt_options=None):
1241 self.last_peer = peer
1242 self.last_mailfrom = mailfrom
1243 self.last_rcpttos = rcpttos
1244 self.last_message = data
1245 self.last_mail_options = mail_options
1246 self.last_rcpt_options = rcpt_options
1247
1248
R David Murraycee7cf62015-05-16 13:58:14 -04001249class SMTPUTF8SimTests(unittest.TestCase):
1250
R David Murray83084442015-05-17 19:27:22 -04001251 maxDiff = None
1252
R David Murraycee7cf62015-05-16 13:58:14 -04001253 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001254 self.thread_key = threading_setup()
R David Murraycee7cf62015-05-16 13:58:14 -04001255 self.real_getfqdn = socket.getfqdn
1256 socket.getfqdn = mock_socket.getfqdn
1257 self.serv_evt = threading.Event()
1258 self.client_evt = threading.Event()
1259 # Pick a random unused port by passing 0 for the port number
1260 self.serv = SimSMTPUTF8Server((HOST, 0), ('nowhere', -1),
1261 decode_data=False,
1262 enable_SMTPUTF8=True)
1263 # Keep a note of what port was assigned
1264 self.port = self.serv.socket.getsockname()[1]
1265 serv_args = (self.serv, self.serv_evt, self.client_evt)
1266 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1267 self.thread.start()
1268
1269 # wait until server thread has assigned a port number
1270 self.serv_evt.wait()
1271 self.serv_evt.clear()
1272
1273 def tearDown(self):
1274 socket.getfqdn = self.real_getfqdn
1275 # indicate that the client is finished
1276 self.client_evt.set()
1277 # wait for the server thread to terminate
1278 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001279 join_thread(self.thread)
1280 del self.thread
1281 self.doCleanups()
1282 threading_cleanup(*self.thread_key)
R David Murraycee7cf62015-05-16 13:58:14 -04001283
1284 def test_test_server_supports_extensions(self):
1285 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001286 HOST, self.port, local_hostname='localhost',
1287 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001288 self.addCleanup(smtp.close)
1289 smtp.ehlo()
1290 self.assertTrue(smtp.does_esmtp)
1291 self.assertTrue(smtp.has_extn('smtputf8'))
1292
1293 def test_send_unicode_with_SMTPUTF8_via_sendmail(self):
1294 m = '¡a test message containing unicode!'.encode('utf-8')
1295 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001296 HOST, self.port, local_hostname='localhost',
1297 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001298 self.addCleanup(smtp.close)
1299 smtp.sendmail('Jőhn', 'Sálly', m,
1300 mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1301 self.assertEqual(self.serv.last_mailfrom, 'Jőhn')
1302 self.assertEqual(self.serv.last_rcpttos, ['Sálly'])
1303 self.assertEqual(self.serv.last_message, m)
1304 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1305 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1306 self.assertEqual(self.serv.last_rcpt_options, [])
1307
1308 def test_send_unicode_with_SMTPUTF8_via_low_level_API(self):
1309 m = '¡a test message containing unicode!'.encode('utf-8')
1310 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001311 HOST, self.port, local_hostname='localhost',
1312 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001313 self.addCleanup(smtp.close)
1314 smtp.ehlo()
1315 self.assertEqual(
1316 smtp.mail('Jő', options=['BODY=8BITMIME', 'SMTPUTF8']),
1317 (250, b'OK'))
1318 self.assertEqual(smtp.rcpt('János'), (250, b'OK'))
1319 self.assertEqual(smtp.data(m), (250, b'OK'))
1320 self.assertEqual(self.serv.last_mailfrom, 'Jő')
1321 self.assertEqual(self.serv.last_rcpttos, ['János'])
1322 self.assertEqual(self.serv.last_message, m)
1323 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1324 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1325 self.assertEqual(self.serv.last_rcpt_options, [])
1326
R David Murray83084442015-05-17 19:27:22 -04001327 def test_send_message_uses_smtputf8_if_addrs_non_ascii(self):
1328 msg = EmailMessage()
1329 msg['From'] = "Páolo <főo@bar.com>"
1330 msg['To'] = 'Dinsdale'
1331 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1332 # XXX I don't know why I need two \n's here, but this is an existing
1333 # bug (if it is one) and not a problem with the new functionality.
1334 msg.set_content("oh là là, know what I mean, know what I mean?\n\n")
1335 # XXX smtpd converts received /r/n to /n, so we can't easily test that
1336 # we are successfully sending /r/n :(.
1337 expected = textwrap.dedent("""\
1338 From: Páolo <főo@bar.com>
1339 To: Dinsdale
1340 Subject: Nudge nudge, wink, wink \u1F609
1341 Content-Type: text/plain; charset="utf-8"
1342 Content-Transfer-Encoding: 8bit
1343 MIME-Version: 1.0
1344
1345 oh là là, know what I mean, know what I mean?
1346 """)
1347 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001348 HOST, self.port, local_hostname='localhost',
1349 timeout=support.LOOPBACK_TIMEOUT)
R David Murray83084442015-05-17 19:27:22 -04001350 self.addCleanup(smtp.close)
1351 self.assertEqual(smtp.send_message(msg), {})
1352 self.assertEqual(self.serv.last_mailfrom, 'főo@bar.com')
1353 self.assertEqual(self.serv.last_rcpttos, ['Dinsdale'])
1354 self.assertEqual(self.serv.last_message.decode(), expected)
1355 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1356 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1357 self.assertEqual(self.serv.last_rcpt_options, [])
1358
Guido van Rossum04110fb2007-08-24 16:32:05 +00001359
Barry Warsawc5ea7542015-07-09 10:39:55 -04001360EXPECTED_RESPONSE = encode_base64(b'\0psu\0doesnotexist', eol='')
1361
1362class SimSMTPAUTHInitialResponseChannel(SimSMTPChannel):
1363 def smtp_AUTH(self, arg):
1364 # RFC 4954's AUTH command allows for an optional initial-response.
1365 # Not all AUTH methods support this; some require a challenge. AUTH
1366 # PLAIN does those, so test that here. See issue #15014.
1367 args = arg.split()
1368 if args[0].lower() == 'plain':
1369 if len(args) == 2:
1370 # AUTH PLAIN <initial-response> with the response base 64
1371 # encoded. Hard code the expected response for the test.
1372 if args[1] == EXPECTED_RESPONSE:
1373 self.push('235 Ok')
1374 return
1375 self.push('571 Bad authentication')
1376
1377class SimSMTPAUTHInitialResponseServer(SimSMTPServer):
1378 channel_class = SimSMTPAUTHInitialResponseChannel
1379
1380
Barry Warsawc5ea7542015-07-09 10:39:55 -04001381class SMTPAUTHInitialResponseSimTests(unittest.TestCase):
1382 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001383 self.thread_key = threading_setup()
Barry Warsawc5ea7542015-07-09 10:39:55 -04001384 self.real_getfqdn = socket.getfqdn
1385 socket.getfqdn = mock_socket.getfqdn
1386 self.serv_evt = threading.Event()
1387 self.client_evt = threading.Event()
1388 # Pick a random unused port by passing 0 for the port number
1389 self.serv = SimSMTPAUTHInitialResponseServer(
1390 (HOST, 0), ('nowhere', -1), decode_data=True)
1391 # Keep a note of what port was assigned
1392 self.port = self.serv.socket.getsockname()[1]
1393 serv_args = (self.serv, self.serv_evt, self.client_evt)
1394 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1395 self.thread.start()
1396
1397 # wait until server thread has assigned a port number
1398 self.serv_evt.wait()
1399 self.serv_evt.clear()
1400
1401 def tearDown(self):
1402 socket.getfqdn = self.real_getfqdn
1403 # indicate that the client is finished
1404 self.client_evt.set()
1405 # wait for the server thread to terminate
1406 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001407 join_thread(self.thread)
1408 del self.thread
1409 self.doCleanups()
1410 threading_cleanup(*self.thread_key)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001411
1412 def testAUTH_PLAIN_initial_response_login(self):
1413 self.serv.add_feature('AUTH PLAIN')
Victor Stinner7772b1a2019-12-11 22:17:04 +01001414 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1415 timeout=support.LOOPBACK_TIMEOUT)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001416 smtp.login('psu', 'doesnotexist')
1417 smtp.close()
1418
1419 def testAUTH_PLAIN_initial_response_auth(self):
1420 self.serv.add_feature('AUTH PLAIN')
Victor Stinner7772b1a2019-12-11 22:17:04 +01001421 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1422 timeout=support.LOOPBACK_TIMEOUT)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001423 smtp.user = 'psu'
1424 smtp.password = 'doesnotexist'
1425 code, response = smtp.auth('plain', smtp.auth_plain)
1426 smtp.close()
1427 self.assertEqual(code, 235)
1428
1429
Guido van Rossumd8faa362007-04-27 19:54:29 +00001430if __name__ == '__main__':
chason48ed88a2018-07-26 04:01:28 +09001431 unittest.main()