Debian Codegraph @

tests/test_plugin_email_smtp.py

raw
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 # Disable logging for a cleaner testing output
29 import logging
30 import smtplib
31 from unittest import mock
32
33 import pytest
34
35 from apprise.exception import AppriseImproperlyConfigured
36 from apprise.plugins.email.smtp import (
37 SMTP_DEFAULT_PORTS,
38 SMTP_SECURE_MODES,
39 AppriseSMTPController,
40 SMTPSecureMode,
41 )
42
43 logging.disable(logging.CRITICAL)
44
45
46 def test_smtp_secure_mode_constants():
47 """SMTPSecureMode / SMTP_SECURE_MODES / SMTP_DEFAULT_PORTS basics."""
48
49 assert SMTPSecureMode.INSECURE == "insecure"
50 assert SMTPSecureMode.SSL == "ssl"
51 assert SMTPSecureMode.STARTTLS == "starttls"
52
53 assert set(SMTP_SECURE_MODES) == {
54 SMTPSecureMode.STARTTLS,
55 SMTPSecureMode.SSL,
56 SMTPSecureMode.INSECURE,
57 }
58
59 assert SMTP_DEFAULT_PORTS[SMTPSecureMode.STARTTLS] == 587
60 assert SMTP_DEFAULT_PORTS[SMTPSecureMode.SSL] == 465
61 assert SMTP_DEFAULT_PORTS[SMTPSecureMode.INSECURE] == 25
62
63
64 @mock.patch("smtplib.SMTP")
65 def test_smtp_controller_starttls_flow(mock_smtp):
66 """AppriseSMTPController applies STARTTLS and login in starttls mode."""
67
68 mock_socket = mock.Mock()
69 # An empty refusal map means SMTP accepted every recipient.
70 mock_socket.sendmail.return_value = {}
71 mock_smtp.return_value = mock_socket
72
73 with AppriseSMTPController(
74 host="smtp.example.com",
75 port=587,
76 secure_mode=SMTPSecureMode.STARTTLS,
77 user="user",
78 password="pass",
79 ) as smtp:
80 assert isinstance(smtp, AppriseSMTPController)
81 assert smtp.sendmail("[email protected]", ["[email protected]"], "body")
82
83 mock_smtp.assert_called_once_with(
84 "smtp.example.com", 587, None, timeout=15
85 )
86 assert mock_socket.starttls.called
87 mock_socket.login.assert_called_once_with("user", "pass")
88 mock_socket.sendmail.assert_called_once_with(
89 "[email protected]", ["[email protected]"], "body"
90 )
91 assert mock_socket.quit.called
92
93
94 @mock.patch("smtplib.SMTP_SSL")
95 def test_smtp_controller_ssl_flow(mock_smtp_ssl):
96 """SSL mode uses SMTP_SSL without STARTTLS."""
97
98 mock_socket = mock.Mock()
99 # An empty refusal map means SMTP accepted every recipient.
100 mock_socket.sendmail.return_value = {}
101 mock_smtp_ssl.return_value = mock_socket
102
103 with AppriseSMTPController(
104 host="smtp.example.com",
105 port=465,
106 secure_mode=SMTPSecureMode.SSL,
107 ) as smtp:
108 assert smtp.sendmail("[email protected]", ["[email protected]"], "body")
109
110 assert mock_smtp_ssl.called
111 assert not mock_socket.starttls.called
112 # No credentials supplied; login must not be attempted
113 assert not mock_socket.login.called
114 assert mock_socket.quit.called
115
116
117 @mock.patch("smtplib.SMTP")
118 def test_smtp_controller_insecure_flow(mock_smtp):
119 """Insecure mode uses plain SMTP."""
120
121 mock_socket = mock.Mock()
122 # An empty refusal map means SMTP accepted every recipient.
123 mock_socket.sendmail.return_value = {}
124 mock_smtp.return_value = mock_socket
125
126 with AppriseSMTPController(
127 host="smtp.example.com",
128 port=25,
129 secure_mode=SMTPSecureMode.INSECURE,
130 ) as smtp:
131 assert smtp.sendmail("[email protected]", ["[email protected]"], "body")
132
133 assert not mock_socket.starttls.called
134 assert not mock_socket.login.called
135
136
137 @mock.patch("smtplib.SMTP")
138 def test_smtp_controller_skips_partial_login(mock_smtp):
139 """Login requires both a username and password."""
140
141 mock_socket = mock.Mock()
142 # An empty refusal map means SMTP accepted every recipient.
143 mock_socket.sendmail.return_value = {}
144 mock_smtp.return_value = mock_socket
145
146 with AppriseSMTPController(
147 host="smtp.example.com",
148 port=25,
149 secure_mode=SMTPSecureMode.INSECURE,
150 user="user",
151 password=None,
152 ):
153 pass
154
155 assert not mock_socket.login.called
156
157
158 @mock.patch("smtplib.SMTP")
159 def test_smtp_controller_connect_failure(mock_smtp):
160 """A connection failure escapes without attempting to quit."""
161
162 mock_smtp.side_effect = OSError("connection refused")
163
164 with (
165 pytest.raises(OSError),
166 AppriseSMTPController(
167 host="smtp.example.com",
168 port=25,
169 secure_mode=SMTPSecureMode.INSECURE,
170 ),
171 ):
172 raise AssertionError("should never enter the with block")
173
174
175 @mock.patch("smtplib.SMTP")
176 def test_smtp_controller_starttls_cleanup(mock_smtp):
177 """A STARTTLS failure closes the partial connection."""
178
179 mock_socket = mock.Mock()
180 # An empty refusal map means SMTP accepted every recipient.
181 mock_socket.sendmail.return_value = {}
182 mock_socket.starttls.side_effect = smtplib.SMTPException("tls failed")
183 mock_smtp.return_value = mock_socket
184
185 with (
186 pytest.raises(smtplib.SMTPException),
187 AppriseSMTPController(
188 host="smtp.example.com",
189 port=587,
190 secure_mode=SMTPSecureMode.STARTTLS,
191 ),
192 ):
193 raise AssertionError("should never enter the with block")
194
195 assert mock_socket.quit.called
196
197
198 @mock.patch("smtplib.SMTP")
199 def test_smtp_controller_login_cleanup(mock_smtp):
200 """A login failure closes the established connection."""
201
202 mock_socket = mock.Mock()
203 # An empty refusal map means SMTP accepted every recipient.
204 mock_socket.sendmail.return_value = {}
205 mock_socket.login.side_effect = smtplib.SMTPAuthenticationError(
206 535, "bad credentials"
207 )
208 mock_smtp.return_value = mock_socket
209
210 with (
211 pytest.raises(smtplib.SMTPAuthenticationError),
212 AppriseSMTPController(
213 host="smtp.example.com",
214 port=587,
215 secure_mode=SMTPSecureMode.STARTTLS,
216 user="user",
217 password="pass",
218 ),
219 ):
220 raise AssertionError("should never enter the with block")
221
222 assert mock_socket.starttls.called
223 assert mock_socket.quit.called
224
225
226 @mock.patch("smtplib.SMTP")
227 def test_smtp_controller_sendmail_exceptions(mock_smtp):
228 """Delivery errors return false instead of escaping."""
229
230 mock_socket = mock.Mock()
231 # An empty refusal map means SMTP accepted every recipient.
232 mock_socket.sendmail.return_value = {}
233 mock_smtp.return_value = mock_socket
234
235 for exception in (
236 OSError("boom"),
237 smtplib.SMTPHeloError(0, "boom"),
238 smtplib.SMTPException(0, "boom"),
239 smtplib.SMTPRecipientsRefused("boom"),
240 smtplib.SMTPSenderRefused(0, "boom", "[email protected]"),
241 smtplib.SMTPDataError(0, "boom"),
242 smtplib.SMTPServerDisconnected("boom"),
243 RuntimeError("boom"),
244 ):
245 mock_socket.sendmail.side_effect = exception
246 with AppriseSMTPController(
247 host="smtp.example.com",
248 port=25,
249 secure_mode=SMTPSecureMode.INSECURE,
250 ) as smtp:
251 assert (
252 smtp.sendmail("[email protected]", ["[email protected]"], "body")
253 is False
254 )
255
256
257 @mock.patch("smtplib.SMTP")
258 def test_smtp_controller_sendmail_partial_rejection(mock_smtp):
259 """A partial recipient rejection makes the delivery fail."""
260
261 mock_socket = mock.Mock()
262 mock_socket.sendmail.return_value = {
263 "[email protected]": (550, b"Mailbox unavailable")
264 }
265 mock_smtp.return_value = mock_socket
266
267 with AppriseSMTPController(
268 host="smtp.example.com",
269 port=25,
270 secure_mode=SMTPSecureMode.INSECURE,
271 ) as smtp:
272 assert (
273 smtp.sendmail(
274 "[email protected]",
275 ["[email protected]", "[email protected]"],
276 "body",
277 )
278 is False
279 )
280
281
282 @mock.patch("smtplib.SMTP")
283 def test_smtp_controller_quit_failure_suppressed(mock_smtp):
284 """__exit__ suppresses errors raised while closing the connection."""
285
286 mock_socket = mock.Mock()
287 # An empty refusal map means SMTP accepted every recipient.
288 mock_socket.sendmail.return_value = {}
289 mock_socket.quit.side_effect = smtplib.SMTPServerDisconnected("bye")
290 mock_smtp.return_value = mock_socket
291
292 # Must not raise despite quit() failing
293 with AppriseSMTPController(
294 host="smtp.example.com",
295 port=25,
296 secure_mode=SMTPSecureMode.INSECURE,
297 ):
298 pass
299
300 assert mock_socket.quit.called
301
302
303 @mock.patch("smtplib.SMTP")
304 def test_smtp_controller_quits_on_caller_error(mock_smtp):
305 """Caller errors still close the connection and propagate."""
306
307 mock_socket = mock.Mock()
308 # An empty refusal map means SMTP accepted every recipient.
309 mock_socket.sendmail.return_value = {}
310 mock_smtp.return_value = mock_socket
311
312 with (
313 pytest.raises(ValueError),
314 AppriseSMTPController(
315 host="smtp.example.com",
316 port=25,
317 secure_mode=SMTPSecureMode.INSECURE,
318 ),
319 ):
320 raise ValueError("caller-side failure")
321
322 assert mock_socket.quit.called
323
324
325 @mock.patch("smtplib.SMTP_SSL")
326 def test_smtp_controller_disables_verification(mock_smtp_ssl):
327 """The verification option controls certificate and hostname checks."""
328
329 mock_socket = mock.Mock()
330 # An empty refusal map means SMTP accepted every recipient.
331 mock_socket.sendmail.return_value = {}
332 mock_smtp_ssl.return_value = mock_socket
333
334 with AppriseSMTPController(
335 host="smtp.example.com",
336 port=465,
337 secure_mode=SMTPSecureMode.SSL,
338 verify_certificate=False,
339 ):
340 pass
341
342 context = mock_smtp_ssl.call_args.kwargs["context"]
343 assert context.check_hostname is False
344
345 import ssl
346
347 assert context.verify_mode == ssl.CERT_NONE
348
349
350 @mock.patch("smtplib.SMTP")
351 def test_smtp_controller_connect_timeout(mock_smtp):
352 """The configured connection timeout reaches smtplib."""
353
354 mock_socket = mock.Mock()
355 # An empty refusal map means SMTP accepted every recipient.
356 mock_socket.sendmail.return_value = {}
357 mock_smtp.return_value = mock_socket
358
359 with AppriseSMTPController(
360 host="smtp.example.com",
361 port=25,
362 secure_mode=SMTPSecureMode.INSECURE,
363 socket_connect_timeout=42,
364 ):
365 pass
366
367 mock_smtp.assert_called_once_with("smtp.example.com", 25, None, timeout=42)
368
369
370 def test_smtp_controller_exit_before_enter():
371 """Exiting before entering is harmless."""
372
373 smtp = AppriseSMTPController(
374 host="smtp.example.com",
375 port=25,
376 secure_mode=SMTPSecureMode.INSECURE,
377 )
378 smtp.__exit__(None, None, None)
379
380
381 def test_smtp_controller_invalid_secure_mode_rejected():
382 """Unknown security modes cannot fall back to plain SMTP."""
383
384 with (
385 pytest.raises(AppriseImproperlyConfigured),
386 AppriseSMTPController(
387 host="smtp.example.com",
388 port=25,
389 secure_mode="bogus",
390 ),
391 ):
392 raise AssertionError("should never enter the with block")