blob: e66ae9be51c044e8124c49628627f057fb83bac3 [file] [log] [blame]
Guido van Rossum806c2462007-08-06 23:33:07 +00001import asyncore
R. David Murray7dff9e02010-11-08 17:15:13 +00002import email.mime.text
R David Murray83084442015-05-17 19:27:22 -04003from email.message import EmailMessage
Guido van Rossum04110fb2007-08-24 16:32:05 +00004import email.utils
Guido van Rossumd8faa362007-04-27 19:54:29 +00005import socket
Guido van Rossum806c2462007-08-06 23:33:07 +00006import smtpd
Guido van Rossumd8faa362007-04-27 19:54:29 +00007import smtplib
Guido van Rossum806c2462007-08-06 23:33:07 +00008import io
R. David Murray7dff9e02010-11-08 17:15:13 +00009import re
Guido van Rossum806c2462007-08-06 23:33:07 +000010import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +000011import time
Guido van Rossum806c2462007-08-06 23:33:07 +000012import select
Ross Lagerwall86407432012-03-29 18:08:48 +020013import errno
R David Murray83084442015-05-17 19:27:22 -040014import textwrap
Guido van Rossumd8faa362007-04-27 19:54:29 +000015
Victor Stinner45df8202010-04-28 22:31:17 +000016import unittest
Richard Jones64b02de2010-08-03 06:39:33 +000017from test import support, mock_socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000018
Victor Stinner45df8202010-04-28 22:31:17 +000019try:
20 import threading
21except ImportError:
22 threading = None
23
Benjamin Petersonee8712c2008-05-20 21:35:26 +000024HOST = support.HOST
Guido van Rossumd8faa362007-04-27 19:54:29 +000025
Josiah Carlsond74900e2008-07-07 04:15:08 +000026if sys.platform == 'darwin':
27 # select.poll returns a select.POLLHUP at the end of the tests
28 # on darwin, so just ignore it
29 def handle_expt(self):
30 pass
31 smtpd.SMTPChannel.handle_expt = handle_expt
32
33
Christian Heimes5e696852008-04-09 08:37:03 +000034def server(evt, buf, serv):
Charles-François Natali6e204602014-07-23 19:28:13 +010035 serv.listen()
Christian Heimes380f7f22008-02-28 11:19:05 +000036 evt.set()
Guido van Rossumd8faa362007-04-27 19:54:29 +000037 try:
38 conn, addr = serv.accept()
39 except socket.timeout:
40 pass
41 else:
Guido van Rossum806c2462007-08-06 23:33:07 +000042 n = 500
43 while buf and n > 0:
44 r, w, e = select.select([], [conn], [])
45 if w:
46 sent = conn.send(buf)
47 buf = buf[sent:]
48
49 n -= 1
Guido van Rossum806c2462007-08-06 23:33:07 +000050
Guido van Rossumd8faa362007-04-27 19:54:29 +000051 conn.close()
52 finally:
53 serv.close()
54 evt.set()
55
Victor Stinner45df8202010-04-28 22:31:17 +000056class GeneralTests(unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +000057
58 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +000059 smtplib.socket = mock_socket
60 self.port = 25
Guido van Rossumd8faa362007-04-27 19:54:29 +000061
62 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +000063 smtplib.socket = socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000064
R. David Murray7dff9e02010-11-08 17:15:13 +000065 # This method is no longer used but is retained for backward compatibility,
66 # so test to make sure it still works.
67 def testQuoteData(self):
68 teststr = "abc\n.jkl\rfoo\r\n..blue"
69 expected = "abc\r\n..jkl\r\nfoo\r\n...blue"
70 self.assertEqual(expected, smtplib.quotedata(teststr))
71
Guido van Rossum806c2462007-08-06 23:33:07 +000072 def testBasic1(self):
Richard Jones64b02de2010-08-03 06:39:33 +000073 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossumd8faa362007-04-27 19:54:29 +000074 # connects
Christian Heimes5e696852008-04-09 08:37:03 +000075 smtp = smtplib.SMTP(HOST, self.port)
Georg Brandlf78e02b2008-06-10 17:40:04 +000076 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +000077
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080078 def testSourceAddress(self):
79 mock_socket.reply_with(b"220 Hola mundo")
80 # connects
81 smtp = smtplib.SMTP(HOST, self.port,
82 source_address=('127.0.0.1',19876))
83 self.assertEqual(smtp.source_address, ('127.0.0.1', 19876))
84 smtp.close()
85
Guido van Rossum806c2462007-08-06 23:33:07 +000086 def testBasic2(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000087 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000088 # connects, include port in host name
Christian Heimes5e696852008-04-09 08:37:03 +000089 smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
Georg Brandlf78e02b2008-06-10 17:40:04 +000090 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000091
92 def testLocalHostName(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000093 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000094 # check that supplied local_hostname is used
Christian Heimes5e696852008-04-09 08:37:03 +000095 smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
Guido van Rossum806c2462007-08-06 23:33:07 +000096 self.assertEqual(smtp.local_hostname, "testhost")
Georg Brandlf78e02b2008-06-10 17:40:04 +000097 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000098
Guido van Rossumd8faa362007-04-27 19:54:29 +000099 def testTimeoutDefault(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000100 mock_socket.reply_with(b"220 Hola mundo")
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200101 self.assertIsNone(mock_socket.getdefaulttimeout())
Richard Jones64b02de2010-08-03 06:39:33 +0000102 mock_socket.setdefaulttimeout(30)
103 self.assertEqual(mock_socket.getdefaulttimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000104 try:
105 smtp = smtplib.SMTP(HOST, self.port)
106 finally:
Richard Jones64b02de2010-08-03 06:39:33 +0000107 mock_socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000108 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000109 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000110
111 def testTimeoutNone(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000112 mock_socket.reply_with(b"220 Hola mundo")
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200113 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000114 socket.setdefaulttimeout(30)
115 try:
Christian Heimes5e696852008-04-09 08:37:03 +0000116 smtp = smtplib.SMTP(HOST, self.port, timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000117 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000118 socket.setdefaulttimeout(None)
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200119 self.assertIsNone(smtp.sock.gettimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +0000120 smtp.close()
121
122 def testTimeoutValue(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000123 mock_socket.reply_with(b"220 Hola mundo")
Georg Brandlf78e02b2008-06-10 17:40:04 +0000124 smtp = smtplib.SMTP(HOST, self.port, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000125 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000126 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000127
R David Murray0c49b892015-04-16 17:14:42 -0400128 def test_debuglevel(self):
129 mock_socket.reply_with(b"220 Hello world")
130 smtp = smtplib.SMTP()
131 smtp.set_debuglevel(1)
132 with support.captured_stderr() as stderr:
133 smtp.connect(HOST, self.port)
134 smtp.close()
135 expected = re.compile(r"^connect:", re.MULTILINE)
136 self.assertRegex(stderr.getvalue(), expected)
137
138 def test_debuglevel_2(self):
139 mock_socket.reply_with(b"220 Hello world")
140 smtp = smtplib.SMTP()
141 smtp.set_debuglevel(2)
142 with support.captured_stderr() as stderr:
143 smtp.connect(HOST, self.port)
144 smtp.close()
145 expected = re.compile(r"^\d{2}:\d{2}:\d{2}\.\d{6} connect: ",
146 re.MULTILINE)
147 self.assertRegex(stderr.getvalue(), expected)
148
Guido van Rossumd8faa362007-04-27 19:54:29 +0000149
Guido van Rossum04110fb2007-08-24 16:32:05 +0000150# Test server thread using the specified SMTP server class
Christian Heimes5e696852008-04-09 08:37:03 +0000151def debugging_server(serv, serv_evt, client_evt):
Christian Heimes380f7f22008-02-28 11:19:05 +0000152 serv_evt.set()
Guido van Rossum806c2462007-08-06 23:33:07 +0000153
154 try:
155 if hasattr(select, 'poll'):
156 poll_fun = asyncore.poll2
157 else:
158 poll_fun = asyncore.poll
159
160 n = 1000
161 while asyncore.socket_map and n > 0:
162 poll_fun(0.01, asyncore.socket_map)
163
164 # when the client conversation is finished, it will
165 # set client_evt, and it's then ok to kill the server
Benjamin Peterson672b8032008-06-11 19:14:14 +0000166 if client_evt.is_set():
Guido van Rossum806c2462007-08-06 23:33:07 +0000167 serv.close()
168 break
169
170 n -= 1
171
172 except socket.timeout:
173 pass
174 finally:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000175 if not client_evt.is_set():
Christian Heimes380f7f22008-02-28 11:19:05 +0000176 # allow some time for the client to read the result
177 time.sleep(0.5)
178 serv.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000179 asyncore.close_all()
Guido van Rossum806c2462007-08-06 23:33:07 +0000180 serv_evt.set()
181
182MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
183MSG_END = '------------ END MESSAGE ------------\n'
184
Guido van Rossum04110fb2007-08-24 16:32:05 +0000185# NOTE: Some SMTP objects in the tests below are created with a non-default
186# local_hostname argument to the constructor, since (on some systems) the FQDN
187# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000188# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000189
190# Test behavior of smtpd.DebuggingServer
Victor Stinner45df8202010-04-28 22:31:17 +0000191@unittest.skipUnless(threading, 'Threading required for this test.')
192class DebuggingServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000193
R. David Murray7dff9e02010-11-08 17:15:13 +0000194 maxDiff = None
195
Guido van Rossum806c2462007-08-06 23:33:07 +0000196 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000197 self.real_getfqdn = socket.getfqdn
198 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000199 # temporarily replace sys.stdout to capture DebuggingServer output
200 self.old_stdout = sys.stdout
201 self.output = io.StringIO()
202 sys.stdout = self.output
203
204 self.serv_evt = threading.Event()
205 self.client_evt = threading.Event()
R. David Murray7dff9e02010-11-08 17:15:13 +0000206 # Capture SMTPChannel debug output
207 self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
208 smtpd.DEBUGSTREAM = io.StringIO()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000209 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400210 self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1),
211 decode_data=True)
Antoine Pitrou043bad02010-04-30 23:20:15 +0000212 # Keep a note of what port was assigned
213 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000214 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000215 self.thread = threading.Thread(target=debugging_server, args=serv_args)
216 self.thread.start()
Guido van Rossum806c2462007-08-06 23:33:07 +0000217
218 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000219 self.serv_evt.wait()
220 self.serv_evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000221
222 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000223 socket.getfqdn = self.real_getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000224 # indicate that the client is finished
225 self.client_evt.set()
226 # wait for the server thread to terminate
227 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000228 self.thread.join()
Guido van Rossum806c2462007-08-06 23:33:07 +0000229 # restore sys.stdout
230 sys.stdout = self.old_stdout
R. David Murray7dff9e02010-11-08 17:15:13 +0000231 # restore DEBUGSTREAM
232 smtpd.DEBUGSTREAM.close()
233 smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
Guido van Rossum806c2462007-08-06 23:33:07 +0000234
235 def testBasic(self):
236 # connect
Christian Heimes5e696852008-04-09 08:37:03 +0000237 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000238 smtp.quit()
239
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800240 def testSourceAddress(self):
241 # connect
Senthil Kumaranb351a482011-07-31 09:14:17 +0800242 port = support.find_unused_port()
243 try:
244 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
245 timeout=3, source_address=('127.0.0.1', port))
246 self.assertEqual(smtp.source_address, ('127.0.0.1', port))
247 self.assertEqual(smtp.local_hostname, 'localhost')
248 smtp.quit()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200249 except OSError as e:
Senthil Kumaranb351a482011-07-31 09:14:17 +0800250 if e.errno == errno.EADDRINUSE:
251 self.skipTest("couldn't bind to port %d" % port)
252 raise
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800253
Guido van Rossum04110fb2007-08-24 16:32:05 +0000254 def testNOOP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000255 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400256 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000257 self.assertEqual(smtp.noop(), expected)
258 smtp.quit()
259
260 def testRSET(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000261 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400262 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000263 self.assertEqual(smtp.rset(), expected)
264 smtp.quit()
265
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400266 def testELHO(self):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000267 # EHLO isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000268 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400269 expected = (250, b'\nSIZE 33554432\nHELP')
Guido van Rossum806c2462007-08-06 23:33:07 +0000270 self.assertEqual(smtp.ehlo(), expected)
271 smtp.quit()
272
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400273 def testEXPNNotImplemented(self):
R David Murrayd1a30c92012-05-26 14:33:59 -0400274 # EXPN isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000275 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400276 expected = (502, b'EXPN not implemented')
277 smtp.putcmd('EXPN')
278 self.assertEqual(smtp.getreply(), expected)
279 smtp.quit()
280
281 def testVRFY(self):
282 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
283 expected = (252, b'Cannot VRFY user, but will accept message ' + \
284 b'and attempt delivery')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000285 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
286 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
287 smtp.quit()
288
289 def testSecondHELO(self):
290 # check that a second HELO returns a message that it's a duplicate
291 # (this behavior is specific to smtpd.SMTPChannel)
Christian Heimes5e696852008-04-09 08:37:03 +0000292 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000293 smtp.helo()
294 expected = (503, b'Duplicate HELO/EHLO')
295 self.assertEqual(smtp.helo(), expected)
296 smtp.quit()
297
Guido van Rossum806c2462007-08-06 23:33:07 +0000298 def testHELP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000299 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400300 self.assertEqual(smtp.help(), b'Supported commands: EHLO HELO MAIL ' + \
301 b'RCPT DATA RSET NOOP QUIT VRFY')
Guido van Rossum806c2462007-08-06 23:33:07 +0000302 smtp.quit()
303
304 def testSend(self):
305 # connect and send mail
306 m = 'A test message'
Christian Heimes5e696852008-04-09 08:37:03 +0000307 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000308 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000309 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
310 # in asyncore. This sleep might help, but should really be fixed
311 # properly by using an Event variable.
312 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000313 smtp.quit()
314
315 self.client_evt.set()
316 self.serv_evt.wait()
317 self.output.flush()
318 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
319 self.assertEqual(self.output.getvalue(), mexpect)
320
R. David Murray7dff9e02010-11-08 17:15:13 +0000321 def testSendBinary(self):
322 m = b'A test message'
323 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
324 smtp.sendmail('John', 'Sally', m)
325 # XXX (see comment in testSend)
326 time.sleep(0.01)
327 smtp.quit()
328
329 self.client_evt.set()
330 self.serv_evt.wait()
331 self.output.flush()
332 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
333 self.assertEqual(self.output.getvalue(), mexpect)
334
R David Murray0f663d02011-06-09 15:05:57 -0400335 def testSendNeedingDotQuote(self):
336 # Issue 12283
337 m = '.A test\n.mes.sage.'
338 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
339 smtp.sendmail('John', 'Sally', m)
340 # XXX (see comment in testSend)
341 time.sleep(0.01)
342 smtp.quit()
343
344 self.client_evt.set()
345 self.serv_evt.wait()
346 self.output.flush()
347 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
348 self.assertEqual(self.output.getvalue(), mexpect)
349
R David Murray46346762011-07-18 21:38:54 -0400350 def testSendNullSender(self):
351 m = 'A test message'
352 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
353 smtp.sendmail('<>', 'Sally', m)
354 # XXX (see comment in testSend)
355 time.sleep(0.01)
356 smtp.quit()
357
358 self.client_evt.set()
359 self.serv_evt.wait()
360 self.output.flush()
361 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
362 self.assertEqual(self.output.getvalue(), mexpect)
363 debugout = smtpd.DEBUGSTREAM.getvalue()
364 sender = re.compile("^sender: <>$", re.MULTILINE)
365 self.assertRegex(debugout, sender)
366
R. David Murray7dff9e02010-11-08 17:15:13 +0000367 def testSendMessage(self):
368 m = email.mime.text.MIMEText('A test message')
369 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
370 smtp.send_message(m, from_addr='John', to_addrs='Sally')
371 # XXX (see comment in testSend)
372 time.sleep(0.01)
373 smtp.quit()
374
375 self.client_evt.set()
376 self.serv_evt.wait()
377 self.output.flush()
378 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400379 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000380 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
381 self.assertEqual(self.output.getvalue(), mexpect)
382
383 def testSendMessageWithAddresses(self):
384 m = email.mime.text.MIMEText('A test message')
385 m['From'] = 'foo@bar.com'
386 m['To'] = 'John'
387 m['CC'] = 'Sally, Fred'
388 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
389 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
390 smtp.send_message(m)
391 # XXX (see comment in testSend)
392 time.sleep(0.01)
393 smtp.quit()
R David Murrayac4e5ab2011-07-02 21:03:19 -0400394 # make sure the Bcc header is still in the message.
395 self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
396 '<warped@silly.walks.com>')
R. David Murray7dff9e02010-11-08 17:15:13 +0000397
398 self.client_evt.set()
399 self.serv_evt.wait()
400 self.output.flush()
401 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400402 m['X-Peer'] = socket.gethostbyname('localhost')
R David Murrayac4e5ab2011-07-02 21:03:19 -0400403 # The Bcc header should not be transmitted.
R. David Murray7dff9e02010-11-08 17:15:13 +0000404 del m['Bcc']
405 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
406 self.assertEqual(self.output.getvalue(), mexpect)
407 debugout = smtpd.DEBUGSTREAM.getvalue()
408 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000409 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000410 for addr in ('John', 'Sally', 'Fred', 'root@localhost',
411 'warped@silly.walks.com'):
412 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
413 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000414 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000415
416 def testSendMessageWithSomeAddresses(self):
417 # Make sure nothing breaks if not all of the three 'to' headers exist
418 m = email.mime.text.MIMEText('A test message')
419 m['From'] = 'foo@bar.com'
420 m['To'] = 'John, Dinsdale'
421 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
422 smtp.send_message(m)
423 # XXX (see comment in testSend)
424 time.sleep(0.01)
425 smtp.quit()
426
427 self.client_evt.set()
428 self.serv_evt.wait()
429 self.output.flush()
430 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400431 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000432 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
433 self.assertEqual(self.output.getvalue(), mexpect)
434 debugout = smtpd.DEBUGSTREAM.getvalue()
435 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000436 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000437 for addr in ('John', 'Dinsdale'):
438 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
439 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000440 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000441
R David Murrayac4e5ab2011-07-02 21:03:19 -0400442 def testSendMessageWithSpecifiedAddresses(self):
443 # Make sure addresses specified in call override those in message.
444 m = email.mime.text.MIMEText('A test message')
445 m['From'] = 'foo@bar.com'
446 m['To'] = 'John, Dinsdale'
447 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
448 smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
449 # XXX (see comment in testSend)
450 time.sleep(0.01)
451 smtp.quit()
452
453 self.client_evt.set()
454 self.serv_evt.wait()
455 self.output.flush()
456 # Add the X-Peer header that DebuggingServer adds
457 m['X-Peer'] = socket.gethostbyname('localhost')
458 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
459 self.assertEqual(self.output.getvalue(), mexpect)
460 debugout = smtpd.DEBUGSTREAM.getvalue()
461 sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
462 self.assertRegex(debugout, sender)
463 for addr in ('John', 'Dinsdale'):
464 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
465 re.MULTILINE)
466 self.assertNotRegex(debugout, to_addr)
467 recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
468 self.assertRegex(debugout, recip)
469
470 def testSendMessageWithMultipleFrom(self):
471 # Sender overrides To
472 m = email.mime.text.MIMEText('A test message')
473 m['From'] = 'Bernard, Bianca'
474 m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com'
475 m['To'] = 'John, Dinsdale'
476 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
477 smtp.send_message(m)
478 # XXX (see comment in testSend)
479 time.sleep(0.01)
480 smtp.quit()
481
482 self.client_evt.set()
483 self.serv_evt.wait()
484 self.output.flush()
485 # Add the X-Peer header that DebuggingServer adds
486 m['X-Peer'] = socket.gethostbyname('localhost')
487 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
488 self.assertEqual(self.output.getvalue(), mexpect)
489 debugout = smtpd.DEBUGSTREAM.getvalue()
490 sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
491 self.assertRegex(debugout, sender)
492 for addr in ('John', 'Dinsdale'):
493 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
494 re.MULTILINE)
495 self.assertRegex(debugout, to_addr)
496
497 def testSendMessageResent(self):
498 m = email.mime.text.MIMEText('A test message')
499 m['From'] = 'foo@bar.com'
500 m['To'] = 'John'
501 m['CC'] = 'Sally, Fred'
502 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
503 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
504 m['Resent-From'] = 'holy@grail.net'
505 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
506 m['Resent-Bcc'] = 'doe@losthope.net'
507 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
508 smtp.send_message(m)
509 # XXX (see comment in testSend)
510 time.sleep(0.01)
511 smtp.quit()
512
513 self.client_evt.set()
514 self.serv_evt.wait()
515 self.output.flush()
516 # The Resent-Bcc headers are deleted before serialization.
517 del m['Bcc']
518 del m['Resent-Bcc']
519 # Add the X-Peer header that DebuggingServer adds
520 m['X-Peer'] = socket.gethostbyname('localhost')
521 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
522 self.assertEqual(self.output.getvalue(), mexpect)
523 debugout = smtpd.DEBUGSTREAM.getvalue()
524 sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
525 self.assertRegex(debugout, sender)
526 for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
527 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
528 re.MULTILINE)
529 self.assertRegex(debugout, to_addr)
530
531 def testSendMessageMultipleResentRaises(self):
532 m = email.mime.text.MIMEText('A test message')
533 m['From'] = 'foo@bar.com'
534 m['To'] = 'John'
535 m['CC'] = 'Sally, Fred'
536 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
537 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
538 m['Resent-From'] = 'holy@grail.net'
539 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
540 m['Resent-Bcc'] = 'doe@losthope.net'
541 m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
542 m['Resent-To'] = 'holy@grail.net'
543 m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
544 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
545 with self.assertRaises(ValueError):
546 smtp.send_message(m)
547 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000548
Victor Stinner45df8202010-04-28 22:31:17 +0000549class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000550
551 def testNotConnected(self):
552 # Test various operations on an unconnected SMTP object that
553 # should raise exceptions (at present the attempt in SMTP.send
554 # to reference the nonexistent 'sock' attribute of the SMTP object
555 # causes an AttributeError)
556 smtp = smtplib.SMTP()
557 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
558 self.assertRaises(smtplib.SMTPServerDisconnected,
559 smtp.send, 'test msg')
560
561 def testNonnumericPort(self):
Andrew Svetlov0832af62012-12-18 23:10:48 +0200562 # check that non-numeric port raises OSError
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200563 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000564 "localhost", "bogus")
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200565 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000566 "localhost:bogus")
567
568
Guido van Rossum04110fb2007-08-24 16:32:05 +0000569# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000570@unittest.skipUnless(threading, 'Threading required for this test.')
571class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000572
573 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000574 smtplib.socket = mock_socket
575 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000576 self.old_stdout = sys.stdout
577 self.output = io.StringIO()
578 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000579 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000580
581 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000582 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000583 sys.stdout = self.old_stdout
584
585 def testFailingHELO(self):
586 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000587 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000588
Guido van Rossum04110fb2007-08-24 16:32:05 +0000589
Georg Brandlb38b5c42014-02-10 22:11:21 +0100590@unittest.skipUnless(threading, 'Threading required for this test.')
591class TooLongLineTests(unittest.TestCase):
592 respdata = b'250 OK' + (b'.' * smtplib._MAXLINE * 2) + b'\n'
593
594 def setUp(self):
595 self.old_stdout = sys.stdout
596 self.output = io.StringIO()
597 sys.stdout = self.output
598
599 self.evt = threading.Event()
600 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
601 self.sock.settimeout(15)
602 self.port = support.bind_port(self.sock)
603 servargs = (self.evt, self.respdata, self.sock)
604 threading.Thread(target=server, args=servargs).start()
605 self.evt.wait()
606 self.evt.clear()
607
608 def tearDown(self):
609 self.evt.wait()
610 sys.stdout = self.old_stdout
611
612 def testLineTooLong(self):
613 self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
614 HOST, self.port, 'localhost', 3)
615
616
Guido van Rossum04110fb2007-08-24 16:32:05 +0000617sim_users = {'Mr.A@somewhere.com':'John A',
R David Murray46346762011-07-18 21:38:54 -0400618 'Ms.B@xn--fo-fka.com':'Sally B',
Guido van Rossum04110fb2007-08-24 16:32:05 +0000619 'Mrs.C@somewhereesle.com':'Ruth C',
620 }
621
R. David Murraycaa27b72009-05-23 18:49:56 +0000622sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000623sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
624 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
625sim_auth_credentials = {
626 'login': 'TXIuQUBzb21ld2hlcmUuY29t',
627 'plain': 'AE1yLkFAc29tZXdoZXJlLmNvbQBzb21lcGFzc3dvcmQ=',
628 'cram-md5': ('TXIUQUBZB21LD2HLCMUUY29TIDG4OWQ0MJ'
629 'KWZGQ4ODNMNDA4NTGXMDRLZWMYZJDMODG1'),
630 }
R David Murray76e13c12014-07-03 14:47:46 -0400631sim_auth_login_user = 'TXIUQUBZB21LD2HLCMUUY29T'
632sim_auth_plain = 'AE1YLKFAC29TZXDOZXJLLMNVBQBZB21LCGFZC3DVCMQ='
R. David Murraycaa27b72009-05-23 18:49:56 +0000633
Guido van Rossum04110fb2007-08-24 16:32:05 +0000634sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
R David Murray46346762011-07-18 21:38:54 -0400635 'list-2':['Ms.B@xn--fo-fka.com',],
Guido van Rossum04110fb2007-08-24 16:32:05 +0000636 }
637
638# Simulated SMTP channel & server
639class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000640
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400641 quit_response = None
R David Murrayd312c742013-03-20 20:36:14 -0400642 mail_response = None
643 rcpt_response = None
644 data_response = None
645 rcpt_count = 0
646 rset_count = 0
R David Murrayafb151a2014-04-14 18:21:38 -0400647 disconnect = 0
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400648
R. David Murray23ddc0e2009-05-29 18:03:16 +0000649 def __init__(self, extra_features, *args, **kw):
650 self._extrafeatures = ''.join(
651 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000652 super(SimSMTPChannel, self).__init__(*args, **kw)
653
Guido van Rossum04110fb2007-08-24 16:32:05 +0000654 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000655 resp = ('250-testhost\r\n'
656 '250-EXPN\r\n'
657 '250-SIZE 20000000\r\n'
658 '250-STARTTLS\r\n'
659 '250-DELIVERBY\r\n')
660 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000661 self.push(resp)
R David Murrayf1a40b42013-03-20 21:12:17 -0400662 self.seen_greeting = arg
663 self.extended_smtp = True
Guido van Rossum04110fb2007-08-24 16:32:05 +0000664
665 def smtp_VRFY(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400666 # For max compatibility smtplib should be sending the raw address.
667 if arg in sim_users:
668 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000669 else:
670 self.push('550 No such user: %s' % arg)
671
672 def smtp_EXPN(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400673 list_name = arg.lower()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000674 if list_name in sim_lists:
675 user_list = sim_lists[list_name]
676 for n, user_email in enumerate(user_list):
677 quoted_addr = smtplib.quoteaddr(user_email)
678 if n < len(user_list) - 1:
679 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
680 else:
681 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
682 else:
683 self.push('550 No access for you!')
684
R. David Murraycaa27b72009-05-23 18:49:56 +0000685 def smtp_AUTH(self, arg):
R David Murray76e13c12014-07-03 14:47:46 -0400686 mech = arg.strip().lower()
687 if mech=='cram-md5':
R. David Murrayfb123912009-05-28 18:19:00 +0000688 self.push('334 {}'.format(sim_cram_md5_challenge))
R David Murray76e13c12014-07-03 14:47:46 -0400689 elif mech not in sim_auth_credentials:
R. David Murraycaa27b72009-05-23 18:49:56 +0000690 self.push('504 auth type unimplemented')
R. David Murrayfb123912009-05-28 18:19:00 +0000691 return
R David Murray76e13c12014-07-03 14:47:46 -0400692 elif mech=='plain':
693 self.push('334 ')
694 elif mech=='login':
695 self.push('334 ')
R. David Murrayfb123912009-05-28 18:19:00 +0000696 else:
697 self.push('550 No access for you!')
R. David Murraycaa27b72009-05-23 18:49:56 +0000698
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400699 def smtp_QUIT(self, arg):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400700 if self.quit_response is None:
701 super(SimSMTPChannel, self).smtp_QUIT(arg)
702 else:
703 self.push(self.quit_response)
704 self.close_when_done()
705
R David Murrayd312c742013-03-20 20:36:14 -0400706 def smtp_MAIL(self, arg):
707 if self.mail_response is None:
708 super().smtp_MAIL(arg)
709 else:
710 self.push(self.mail_response)
R David Murrayafb151a2014-04-14 18:21:38 -0400711 if self.disconnect:
712 self.close_when_done()
R David Murrayd312c742013-03-20 20:36:14 -0400713
714 def smtp_RCPT(self, arg):
715 if self.rcpt_response is None:
716 super().smtp_RCPT(arg)
717 return
R David Murrayd312c742013-03-20 20:36:14 -0400718 self.rcpt_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400719 self.push(self.rcpt_response[self.rcpt_count-1])
R David Murrayd312c742013-03-20 20:36:14 -0400720
721 def smtp_RSET(self, arg):
R David Murrayd312c742013-03-20 20:36:14 -0400722 self.rset_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400723 super().smtp_RSET(arg)
R David Murrayd312c742013-03-20 20:36:14 -0400724
725 def smtp_DATA(self, arg):
726 if self.data_response is None:
727 super().smtp_DATA(arg)
728 else:
729 self.push(self.data_response)
730
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000731 def handle_error(self):
732 raise
733
Guido van Rossum04110fb2007-08-24 16:32:05 +0000734
735class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000736
R David Murrayd312c742013-03-20 20:36:14 -0400737 channel_class = SimSMTPChannel
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400738
R. David Murray23ddc0e2009-05-29 18:03:16 +0000739 def __init__(self, *args, **kw):
740 self._extra_features = []
741 smtpd.SMTPServer.__init__(self, *args, **kw)
742
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000743 def handle_accepted(self, conn, addr):
R David Murrayf1a40b42013-03-20 21:12:17 -0400744 self._SMTPchannel = self.channel_class(
R David Murray1144da52014-06-11 12:27:40 -0400745 self._extra_features, self, conn, addr,
746 decode_data=self._decode_data)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000747
748 def process_message(self, peer, mailfrom, rcpttos, data):
749 pass
750
R. David Murrayfb123912009-05-28 18:19:00 +0000751 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000752 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000753
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000754 def handle_error(self):
755 raise
756
Guido van Rossum04110fb2007-08-24 16:32:05 +0000757
758# Test various SMTP & ESMTP commands/behaviors that require a simulated server
759# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000760@unittest.skipUnless(threading, 'Threading required for this test.')
761class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000762
763 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000764 self.real_getfqdn = socket.getfqdn
765 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000766 self.serv_evt = threading.Event()
767 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000768 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400769 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1), decode_data=True)
Antoine Pitrou043bad02010-04-30 23:20:15 +0000770 # Keep a note of what port was assigned
771 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000772 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000773 self.thread = threading.Thread(target=debugging_server, args=serv_args)
774 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000775
776 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000777 self.serv_evt.wait()
778 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000779
780 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000781 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000782 # indicate that the client is finished
783 self.client_evt.set()
784 # wait for the server thread to terminate
785 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000786 self.thread.join()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000787
788 def testBasic(self):
789 # smoke test
Christian Heimes5e696852008-04-09 08:37:03 +0000790 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000791 smtp.quit()
792
793 def testEHLO(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000794 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000795
796 # no features should be present before the EHLO
797 self.assertEqual(smtp.esmtp_features, {})
798
799 # features expected from the test server
800 expected_features = {'expn':'',
801 'size': '20000000',
802 'starttls': '',
803 'deliverby': '',
804 'help': '',
805 }
806
807 smtp.ehlo()
808 self.assertEqual(smtp.esmtp_features, expected_features)
809 for k in expected_features:
810 self.assertTrue(smtp.has_extn(k))
811 self.assertFalse(smtp.has_extn('unsupported-feature'))
812 smtp.quit()
813
814 def testVRFY(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000815 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000816
817 for email, name in sim_users.items():
818 expected_known = (250, bytes('%s %s' %
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000819 (name, smtplib.quoteaddr(email)),
820 "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000821 self.assertEqual(smtp.vrfy(email), expected_known)
822
823 u = 'nobody@nowhere.com'
R David Murray46346762011-07-18 21:38:54 -0400824 expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000825 self.assertEqual(smtp.vrfy(u), expected_unknown)
826 smtp.quit()
827
828 def testEXPN(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000829 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000830
831 for listname, members in sim_lists.items():
832 users = []
833 for m in members:
834 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000835 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000836 self.assertEqual(smtp.expn(listname), expected_known)
837
838 u = 'PSU-Members-List'
839 expected_unknown = (550, b'No access for you!')
840 self.assertEqual(smtp.expn(u), expected_unknown)
841 smtp.quit()
842
R David Murray76e13c12014-07-03 14:47:46 -0400843 # SimSMTPChannel doesn't fully support AUTH because it requires a
844 # synchronous read to obtain the credentials...so instead smtpd
R. David Murrayfb123912009-05-28 18:19:00 +0000845 # sees the credential sent by smtplib's login method as an unknown command,
846 # which results in smtplib raising an auth error. Fortunately the error
847 # message contains the encoded credential, so we can partially check that it
848 # was generated correctly (partially, because the 'word' is uppercased in
849 # the error message).
850
R David Murray76e13c12014-07-03 14:47:46 -0400851 def testAUTH_PLAIN(self):
852 self.serv.add_feature("AUTH PLAIN")
853 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
854 try: smtp.login(sim_auth[0], sim_auth[1])
855 except smtplib.SMTPAuthenticationError as err:
856 self.assertIn(sim_auth_plain, str(err))
857 smtp.close()
858
R. David Murrayfb123912009-05-28 18:19:00 +0000859 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000860 self.serv.add_feature("AUTH LOGIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000861 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000862 try: smtp.login(sim_auth[0], sim_auth[1])
863 except smtplib.SMTPAuthenticationError as err:
R David Murray76e13c12014-07-03 14:47:46 -0400864 self.assertIn(sim_auth_login_user, str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000865 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000866
867 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000868 self.serv.add_feature("AUTH CRAM-MD5")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000869 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000870
871 try: smtp.login(sim_auth[0], sim_auth[1])
872 except smtplib.SMTPAuthenticationError as err:
Benjamin Peterson95951662010-10-31 17:59:20 +0000873 self.assertIn(sim_auth_credentials['cram-md5'], str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000874 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000875
Andrew Kuchling78591822013-11-11 14:03:23 -0500876 def testAUTH_multiple(self):
877 # Test that multiple authentication methods are tried.
878 self.serv.add_feature("AUTH BOGUS PLAIN LOGIN CRAM-MD5")
879 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
880 try: smtp.login(sim_auth[0], sim_auth[1])
881 except smtplib.SMTPAuthenticationError as err:
R David Murray76e13c12014-07-03 14:47:46 -0400882 self.assertIn(sim_auth_login_user, str(err))
883 smtp.close()
884
885 def test_auth_function(self):
886 smtp = smtplib.SMTP(HOST, self.port,
887 local_hostname='localhost', timeout=15)
888 self.serv.add_feature("AUTH CRAM-MD5")
889 smtp.user, smtp.password = sim_auth[0], sim_auth[1]
890 supported = {'CRAM-MD5': smtp.auth_cram_md5,
891 'PLAIN': smtp.auth_plain,
892 'LOGIN': smtp.auth_login,
893 }
894 for mechanism, method in supported.items():
895 try: smtp.auth(mechanism, method)
896 except smtplib.SMTPAuthenticationError as err:
897 self.assertIn(sim_auth_credentials[mechanism.lower()].upper(),
898 str(err))
Andrew Kuchling78591822013-11-11 14:03:23 -0500899 smtp.close()
900
R David Murray0cff49f2014-08-30 16:51:59 -0400901 def test_quit_resets_greeting(self):
902 smtp = smtplib.SMTP(HOST, self.port,
903 local_hostname='localhost',
904 timeout=15)
905 code, message = smtp.ehlo()
906 self.assertEqual(code, 250)
907 self.assertIn('size', smtp.esmtp_features)
908 smtp.quit()
909 self.assertNotIn('size', smtp.esmtp_features)
910 smtp.connect(HOST, self.port)
911 self.assertNotIn('size', smtp.esmtp_features)
912 smtp.ehlo_or_helo_if_needed()
913 self.assertIn('size', smtp.esmtp_features)
914 smtp.quit()
915
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400916 def test_with_statement(self):
917 with smtplib.SMTP(HOST, self.port) as smtp:
918 code, message = smtp.noop()
919 self.assertEqual(code, 250)
920 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
921 with smtplib.SMTP(HOST, self.port) as smtp:
922 smtp.close()
923 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
924
925 def test_with_statement_QUIT_failure(self):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400926 with self.assertRaises(smtplib.SMTPResponseException) as error:
927 with smtplib.SMTP(HOST, self.port) as smtp:
928 smtp.noop()
R David Murray6bd52022013-03-21 00:32:31 -0400929 self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400930 self.assertEqual(error.exception.smtp_code, 421)
931 self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400932
R. David Murrayfb123912009-05-28 18:19:00 +0000933 #TODO: add tests for correct AUTH method fallback now that the
934 #test infrastructure can support it.
935
R David Murrayafb151a2014-04-14 18:21:38 -0400936 # Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception
937 def test__rest_from_mail_cmd(self):
938 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
939 smtp.noop()
940 self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
941 self.serv._SMTPchannel.disconnect = True
942 with self.assertRaises(smtplib.SMTPSenderRefused):
943 smtp.sendmail('John', 'Sally', 'test message')
944 self.assertIsNone(smtp.sock)
945
R David Murrayd312c742013-03-20 20:36:14 -0400946 # Issue 5713: make sure close, not rset, is called if we get a 421 error
947 def test_421_from_mail_cmd(self):
948 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -0400949 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -0400950 self.serv._SMTPchannel.mail_response = '421 closing connection'
951 with self.assertRaises(smtplib.SMTPSenderRefused):
952 smtp.sendmail('John', 'Sally', 'test message')
953 self.assertIsNone(smtp.sock)
R David Murray03b01162013-03-20 22:11:40 -0400954 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
R David Murrayd312c742013-03-20 20:36:14 -0400955
956 def test_421_from_rcpt_cmd(self):
957 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -0400958 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -0400959 self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
960 with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
961 smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
962 self.assertIsNone(smtp.sock)
963 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
964 self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
965
966 def test_421_from_data_cmd(self):
967 class MySimSMTPChannel(SimSMTPChannel):
968 def found_terminator(self):
969 if self.smtp_state == self.DATA:
970 self.push('421 closing')
971 else:
972 super().found_terminator()
973 self.serv.channel_class = MySimSMTPChannel
974 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -0400975 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -0400976 with self.assertRaises(smtplib.SMTPDataError):
977 smtp.sendmail('John@foo.org', ['Sally@foo.org'], 'test message')
978 self.assertIsNone(smtp.sock)
979 self.assertEqual(self.serv._SMTPchannel.rcpt_count, 0)
980
R David Murraycee7cf62015-05-16 13:58:14 -0400981 def test_smtputf8_NotSupportedError_if_no_server_support(self):
982 smtp = smtplib.SMTP(
983 HOST, self.port, local_hostname='localhost', timeout=3)
984 self.addCleanup(smtp.close)
985 smtp.ehlo()
986 self.assertTrue(smtp.does_esmtp)
987 self.assertFalse(smtp.has_extn('smtputf8'))
988 self.assertRaises(
989 smtplib.SMTPNotSupportedError,
990 smtp.sendmail,
991 'John', 'Sally', '', mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
992 self.assertRaises(
993 smtplib.SMTPNotSupportedError,
994 smtp.mail, 'John', options=['BODY=8BITMIME', 'SMTPUTF8'])
995
996 def test_send_unicode_without_SMTPUTF8(self):
997 smtp = smtplib.SMTP(
998 HOST, self.port, local_hostname='localhost', timeout=3)
999 self.addCleanup(smtp.close)
1000 self.assertRaises(UnicodeEncodeError, smtp.sendmail, 'Alice', 'Böb', '')
1001 self.assertRaises(UnicodeEncodeError, smtp.mail, 'Älice')
1002
1003
1004class SimSMTPUTF8Server(SimSMTPServer):
1005
1006 def __init__(self, *args, **kw):
1007 # The base SMTP server turns these on automatically, but our test
1008 # server is set up to munge the EHLO response, so we need to provide
1009 # them as well. And yes, the call is to SMTPServer not SimSMTPServer.
1010 self._extra_features = ['SMTPUTF8', '8BITMIME']
1011 smtpd.SMTPServer.__init__(self, *args, **kw)
1012
1013 def handle_accepted(self, conn, addr):
1014 self._SMTPchannel = self.channel_class(
1015 self._extra_features, self, conn, addr,
1016 decode_data=self._decode_data,
1017 enable_SMTPUTF8=self.enable_SMTPUTF8,
1018 )
1019
1020 def process_message(self, peer, mailfrom, rcpttos, data, mail_options=None,
1021 rcpt_options=None):
1022 self.last_peer = peer
1023 self.last_mailfrom = mailfrom
1024 self.last_rcpttos = rcpttos
1025 self.last_message = data
1026 self.last_mail_options = mail_options
1027 self.last_rcpt_options = rcpt_options
1028
1029
1030@unittest.skipUnless(threading, 'Threading required for this test.')
1031class SMTPUTF8SimTests(unittest.TestCase):
1032
R David Murray83084442015-05-17 19:27:22 -04001033 maxDiff = None
1034
R David Murraycee7cf62015-05-16 13:58:14 -04001035 def setUp(self):
1036 self.real_getfqdn = socket.getfqdn
1037 socket.getfqdn = mock_socket.getfqdn
1038 self.serv_evt = threading.Event()
1039 self.client_evt = threading.Event()
1040 # Pick a random unused port by passing 0 for the port number
1041 self.serv = SimSMTPUTF8Server((HOST, 0), ('nowhere', -1),
1042 decode_data=False,
1043 enable_SMTPUTF8=True)
1044 # Keep a note of what port was assigned
1045 self.port = self.serv.socket.getsockname()[1]
1046 serv_args = (self.serv, self.serv_evt, self.client_evt)
1047 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1048 self.thread.start()
1049
1050 # wait until server thread has assigned a port number
1051 self.serv_evt.wait()
1052 self.serv_evt.clear()
1053
1054 def tearDown(self):
1055 socket.getfqdn = self.real_getfqdn
1056 # indicate that the client is finished
1057 self.client_evt.set()
1058 # wait for the server thread to terminate
1059 self.serv_evt.wait()
1060 self.thread.join()
1061
1062 def test_test_server_supports_extensions(self):
1063 smtp = smtplib.SMTP(
1064 HOST, self.port, local_hostname='localhost', timeout=3)
1065 self.addCleanup(smtp.close)
1066 smtp.ehlo()
1067 self.assertTrue(smtp.does_esmtp)
1068 self.assertTrue(smtp.has_extn('smtputf8'))
1069
1070 def test_send_unicode_with_SMTPUTF8_via_sendmail(self):
1071 m = '¡a test message containing unicode!'.encode('utf-8')
1072 smtp = smtplib.SMTP(
1073 HOST, self.port, local_hostname='localhost', timeout=3)
1074 self.addCleanup(smtp.close)
1075 smtp.sendmail('Jőhn', 'Sálly', m,
1076 mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1077 self.assertEqual(self.serv.last_mailfrom, 'Jőhn')
1078 self.assertEqual(self.serv.last_rcpttos, ['Sálly'])
1079 self.assertEqual(self.serv.last_message, m)
1080 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1081 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1082 self.assertEqual(self.serv.last_rcpt_options, [])
1083
1084 def test_send_unicode_with_SMTPUTF8_via_low_level_API(self):
1085 m = '¡a test message containing unicode!'.encode('utf-8')
1086 smtp = smtplib.SMTP(
1087 HOST, self.port, local_hostname='localhost', timeout=3)
1088 self.addCleanup(smtp.close)
1089 smtp.ehlo()
1090 self.assertEqual(
1091 smtp.mail('Jő', options=['BODY=8BITMIME', 'SMTPUTF8']),
1092 (250, b'OK'))
1093 self.assertEqual(smtp.rcpt('János'), (250, b'OK'))
1094 self.assertEqual(smtp.data(m), (250, b'OK'))
1095 self.assertEqual(self.serv.last_mailfrom, 'Jő')
1096 self.assertEqual(self.serv.last_rcpttos, ['János'])
1097 self.assertEqual(self.serv.last_message, m)
1098 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1099 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1100 self.assertEqual(self.serv.last_rcpt_options, [])
1101
R David Murray83084442015-05-17 19:27:22 -04001102 def test_send_message_uses_smtputf8_if_addrs_non_ascii(self):
1103 msg = EmailMessage()
1104 msg['From'] = "Páolo <főo@bar.com>"
1105 msg['To'] = 'Dinsdale'
1106 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1107 # XXX I don't know why I need two \n's here, but this is an existing
1108 # bug (if it is one) and not a problem with the new functionality.
1109 msg.set_content("oh là là, know what I mean, know what I mean?\n\n")
1110 # XXX smtpd converts received /r/n to /n, so we can't easily test that
1111 # we are successfully sending /r/n :(.
1112 expected = textwrap.dedent("""\
1113 From: Páolo <főo@bar.com>
1114 To: Dinsdale
1115 Subject: Nudge nudge, wink, wink \u1F609
1116 Content-Type: text/plain; charset="utf-8"
1117 Content-Transfer-Encoding: 8bit
1118 MIME-Version: 1.0
1119
1120 oh là là, know what I mean, know what I mean?
1121 """)
1122 smtp = smtplib.SMTP(
1123 HOST, self.port, local_hostname='localhost', timeout=3)
1124 self.addCleanup(smtp.close)
1125 self.assertEqual(smtp.send_message(msg), {})
1126 self.assertEqual(self.serv.last_mailfrom, 'főo@bar.com')
1127 self.assertEqual(self.serv.last_rcpttos, ['Dinsdale'])
1128 self.assertEqual(self.serv.last_message.decode(), expected)
1129 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1130 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1131 self.assertEqual(self.serv.last_rcpt_options, [])
1132
1133 def test_send_message_error_on_non_ascii_addrs_if_no_smtputf8(self):
1134 msg = EmailMessage()
1135 msg['From'] = "Páolo <főo@bar.com>"
1136 msg['To'] = 'Dinsdale'
1137 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1138 smtp = smtplib.SMTP(
1139 HOST, self.port, local_hostname='localhost', timeout=3)
1140 self.addCleanup(smtp.close)
1141 self.assertRaises(smtplib.SMTPNotSupportedError,
1142 smtp.send_message(msg))
1143
Guido van Rossum04110fb2007-08-24 16:32:05 +00001144
Antoine Pitroud54fa552011-08-28 01:23:52 +02001145@support.reap_threads
Guido van Rossumd8faa362007-04-27 19:54:29 +00001146def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001147 support.run_unittest(GeneralTests, DebuggingServerTests,
Christian Heimes380f7f22008-02-28 11:19:05 +00001148 NonConnectingTests,
Georg Brandlb38b5c42014-02-10 22:11:21 +01001149 BadHELOServerTests, SMTPSimTests,
1150 TooLongLineTests)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001151
1152if __name__ == '__main__':
1153 test_main()