Debian Codegraph @

tests/test_plugin_email.py

raw symbols SCIP
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 from datetime import datetime
29 from email.header import decode_header
30 from inspect import cleandoc
31 import logging
32 import os
33 import re
34 import shutil
35 import smtplib
36 import ssl
37 import sys
38 from unittest import mock
39
40 import pytest
41
42 from apprise import (
43 Apprise,
44 AppriseAsset,
45 AppriseAttachment,
46 AttachBase,
47 NotifyBase,
48 NotifyType,
49 PersistentStoreMode,
50 utils,
51 )
52 from apprise.attachment.memory import AttachMemory
53 from apprise.config import ConfigBase
54 from apprise.exception import AppriseException
55 from apprise.plugins import email
56
57 try:
58 import pgpy
59 except ImportError:
60 pgpy = None
61
62 # Disable logging for a cleaner testing output
63 logging.disable(logging.CRITICAL)
64
65 # Attachment Directory
66 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
67
68 TEST_URLS = (
69 ##################################
70 # NotifyEmail
71 ##################################
72 (
73 "mailto://",
74 {
75 "instance": TypeError,
76 },
77 ),
78 (
79 "mailtos://",
80 {
81 "instance": TypeError,
82 },
83 ),
84 (
85 "mailto://:@/",
86 {
87 "instance": TypeError,
88 },
89 ),
90 # No Username
91 (
92 "mailtos://:[email protected]:567",
93 {
94 # Can't prepare a To address using this expression
95 "instance": TypeError,
96 },
97 ),
98 (
99 # invalid Timezone
100 "mailto://user:[email protected]?tz=invalid",
101 {
102 # An error is thrown for this
103 "instance": TypeError,
104 },
105 ),
106 # Pre-Configured Email Services
107 (
108 "mailto://user:[email protected]",
109 {
110 "instance": email.NotifyEmail,
111 },
112 ),
113 (
114 "mailto://user:[email protected]",
115 {
116 "instance": email.NotifyEmail,
117 },
118 ),
119 (
120 "mailto://user:[email protected]",
121 {
122 "instance": email.NotifyEmail,
123 },
124 ),
125 (
126 "mailto://user:[email protected]",
127 {
128 "instance": email.NotifyEmail,
129 },
130 ),
131 (
132 "mailto://user:[email protected]",
133 {
134 "instance": email.NotifyEmail,
135 },
136 ),
137 (
138 "mailto://user:[email protected]",
139 {
140 "instance": email.NotifyEmail,
141 },
142 ),
143 (
144 "mailto://user:[email protected]?tz=UTC",
145 {
146 "instance": email.NotifyEmail,
147 },
148 ),
149 (
150 "mailto://user:[email protected]",
151 {
152 "instance": email.NotifyEmail,
153 },
154 ),
155 # GMX Support
156 (
157 "mailto://user:[email protected]",
158 {
159 "instance": email.NotifyEmail,
160 "privacy_url": "mailtos://user:****@gmx.net",
161 },
162 ),
163 (
164 "mailto://user:[email protected]",
165 {
166 "instance": email.NotifyEmail,
167 "privacy_url": "mailtos://user:****@gmx.com",
168 },
169 ),
170 (
171 "mailto://user:[email protected]",
172 {
173 "instance": email.NotifyEmail,
174 "privacy_url": "mailtos://user:****@gmx.de",
175 },
176 ),
177 (
178 # STARTTLS flag checking (and privacy URL expectation)
179 "mailtos://user:[email protected]?mode=starttls",
180 {
181 "instance": email.NotifyEmail,
182 "privacy_url": "mailtos://user:****@gmx.net",
183 },
184 ),
185 # Yandex
186 (
187 "mailto://user:[email protected]",
188 {
189 "instance": email.NotifyEmail,
190 },
191 ),
192 (
193 "mailto://user:[email protected]",
194 {
195 "instance": email.NotifyEmail,
196 },
197 ),
198 (
199 "mailto://user:[email protected]",
200 {
201 "instance": email.NotifyEmail,
202 },
203 ),
204 # Custom Emails
205 (
206 "mailtos://user:[email protected]:567",
207 {
208 "instance": email.NotifyEmail,
209 },
210 ),
211 (
212 "mailto://user:[email protected]?mode=ssl",
213 {
214 # mailto:// with mode=ssl causes us to convert to ssl
215 "instance": email.NotifyEmail,
216 # Our expected url(privacy=True) startswith() response:
217 "privacy_url": "mailtos://user:****@nuxref.com",
218 },
219 ),
220 (
221 "mailto://user:[email protected]:567?format=html",
222 {
223 "instance": email.NotifyEmail,
224 },
225 ),
226 (
227 "mailtos://user:[email protected]:[email protected]",
228 {
229 "instance": email.NotifyEmail,
230 },
231 ),
232 (
233 "mailtos://user:[email protected][email protected]",
234 {
235 "instance": email.NotifyEmail,
236 },
237 ),
238 (
239 "mailtos://%[email protected][email protected]",
240 {
241 "instance": email.NotifyEmail,
242 },
243 ),
244 (
245 "mailtos://%[email protected][email protected]&pgp=yes",
246 {
247 # Test deprecated pgp=yes flag (backward compat); notify() fails
248 # because no key is provided and PGP requires one to be useful.
249 "instance": email.NotifyEmail,
250 "response": False,
251 },
252 ),
253 (
254 "mailtos://%[email protected][email protected]&pgp=encrypt",
255 {
256 # Test canonical pgp=encrypt mode string; notify() fails because
257 # no public key is available to encrypt with.
258 "instance": email.NotifyEmail,
259 "response": False,
260 },
261 ),
262 (
263 "mailtos://%[email protected][email protected]&pgp=e",
264 {
265 # Test pgp= prefix shorthand ('e' -> 'encrypt'); notify() fails
266 # because no public key is available to encrypt with.
267 "instance": email.NotifyEmail,
268 "response": False,
269 },
270 ),
271 (
272 "mailtos://%[email protected][email protected]&pgp=sign",
273 {
274 # Test pgp=sign mode string; notify() fails because no private key
275 # is provided and signing requires one.
276 "instance": email.NotifyEmail,
277 "response": False,
278 },
279 ),
280 (
281 "mailtos://%[email protected][email protected]&pgp=s",
282 {
283 # Test pgp= prefix shorthand ('s' -> 'sign'); notify() fails
284 # because no private key is provided.
285 "instance": email.NotifyEmail,
286 "response": False,
287 },
288 ),
289 (
290 "mailtos://%[email protected][email protected]&wkd=yes",
291 {
292 # wkd=yes implies pgp=encrypt; notify() fails because no public
293 # key can be discovered (no WKD server behind this test address).
294 "instance": email.NotifyEmail,
295 "response": False,
296 },
297 ),
298 (
299 "mailtos://%[email protected][email protected]"
300 "&pgp=encrypt&pgpkey=%2Fpath%2Fto%2Fpub.asc",
301 {
302 # Test deprecated pgpkey= alias; exercises the deprecation
303 # warning branch in parse_url() and maps to pgp_key.
304 # notify() returns False because the key path does not exist.
305 "instance": email.NotifyEmail,
306 "response": False,
307 },
308 ),
309 (
310 "mailtos://%[email protected][email protected]"
311 "&pgp=encrypt&pgppub=%2Fpath%2Fto%2Fpub.asc"
312 "&pgpkey=%2Fold%2Fpath.asc",
313 {
314 # Test pgppub= wins over deprecated pgpkey= when both present.
315 # notify() returns False because the key path does not exist.
316 "instance": email.NotifyEmail,
317 "response": False,
318 },
319 ),
320 (
321 "mailtos://user:[email protected]:567/[email protected]",
322 {
323 "instance": email.NotifyEmail,
324 },
325 ),
326 (
327 (
328 "mailto://user:[email protected]:[email protected]"
329 "&pass=l2g@apprise!is!Awesome"
330 ),
331 {
332 "instance": email.NotifyEmail,
333 },
334 ),
335 (
336 (
337 "mailto://user:[email protected]:[email protected]"
338 "&pass=l2g@apprise!is!Awesome&format=text"
339 ),
340 {
341 "instance": email.NotifyEmail,
342 },
343 ),
344 (
345 # Test Carbon Copy
346 (
347 "mailtos://user:[email protected]?smtp=smtp.example.com"
348 "&name=l2g&[email protected],[email protected]"
349 ),
350 {
351 "instance": email.NotifyEmail,
352 },
353 ),
354 (
355 # Test Blind Carbon Copy
356 (
357 "mailtos://user:[email protected]?smtp=smtp.example.com"
358 "&name=l2g&[email protected],[email protected]"
359 ),
360 {
361 "instance": email.NotifyEmail,
362 },
363 ),
364 (
365 # Test Carbon Copy with bad email
366 (
367 "mailtos://user:[email protected]?smtp=smtp.example.com"
368 "&name=l2g&[email protected],@"
369 ),
370 {
371 "instance": email.NotifyEmail,
372 },
373 ),
374 (
375 # Test Blind Carbon Copy with bad email
376 (
377 "mailtos://user:[email protected]?smtp=smtp.example.com"
378 "&name=l2g&[email protected],@"
379 ),
380 {
381 "instance": email.NotifyEmail,
382 },
383 ),
384 (
385 # Test Reply To
386 (
387 "mailtos://user:[email protected]?smtp=smtp.example.com"
388 "&name=l2g&[email protected],[email protected]"
389 ),
390 {
391 "instance": email.NotifyEmail,
392 },
393 ),
394 (
395 # Test Reply To with bad email
396 (
397 "mailtos://user:[email protected]?smtp=smtp.example.com"
398 "&name=l2g&[email protected],@"
399 ),
400 {
401 "instance": email.NotifyEmail,
402 },
403 ),
404 # headers
405 (
406 (
407 "mailto://user:[email protected]"
408 "?+X-Customer-Campaign-ID=Apprise"
409 ),
410 {
411 "instance": email.NotifyEmail,
412 },
413 ),
414 # No Password
415 (
416 "mailtos://user:@nuxref.com",
417 {
418 "instance": email.NotifyEmail,
419 },
420 ),
421 # Invalid From Address; but just gets put as the from name instead
422 # Hence the below generats From: "@ <[email protected]>"
423 (
424 "mailtos://user:[email protected]?from=@",
425 {
426 "instance": email.NotifyEmail,
427 },
428 ),
429 # Invalid From Address
430 (
431 "mailtos://nuxref.com?user=&pass=.",
432 {
433 "instance": TypeError,
434 },
435 ),
436 # Invalid To Address is accepted, but we won't be able to properly email
437 # using the notify() call
438 (
439 "mailtos://user:[email protected]?to=@",
440 {
441 "instance": email.NotifyEmail,
442 "response": False,
443 },
444 ),
445 # Valid URL, but can't structure a proper email
446 (
447 'mailtos://nuxref.com?user=%20"&pass=.',
448 {
449 "instance": TypeError,
450 },
451 ),
452 # Invalid From (and To) Address
453 (
454 "mailtos://nuxref.com?to=test",
455 {
456 "instance": TypeError,
457 },
458 ),
459 # Invalid Secure Mode
460 (
461 "mailtos://user:[email protected]?mode=notamode",
462 {
463 "instance": TypeError,
464 },
465 ),
466 # STARTTLS flag checking
467 (
468 "mailtos://user:[email protected]?mode=starttls",
469 {
470 "instance": email.NotifyEmail,
471 # Our expected url(privacy=True) startswith() response:
472 "privacy_url": "mailtos://user:****@gmail.com",
473 },
474 ),
475 # SSL flag checking
476 (
477 "mailtos://user:[email protected]?mode=ssl",
478 {
479 "instance": email.NotifyEmail,
480 },
481 ),
482 # Can make a To address using what we have ([email protected])
483 (
484 "mailtos://nuxref.com?user=l2g&pass=.",
485 {
486 "instance": email.NotifyEmail,
487 # Our expected url(privacy=True) startswith() response:
488 "privacy_url": "mailtos://l2g:****@nuxref.com",
489 },
490 ),
491 (
492 "mailto://user:pass@localhost:2525",
493 {
494 "instance": email.NotifyEmail,
495 # Throws a series of i/o exceptions with this flag
496 # is set and tests that we gracefully handle them
497 "test_smtplib_exceptions": True,
498 },
499 ),
500 # Use of both 'name' and 'from' together; these are synonymous
501 (
502 (
503 "mailtos://user:[email protected]?"
504 "[email protected]&name=Jason<[email protected]>"
505 ),
506 {"instance": email.NotifyEmail},
507 ),
508 # Test no auth at all
509 (
510 "mailto://[email protected]&[email protected]",
511 {
512 "instance": email.NotifyEmail,
513 "privacy_url": "mailto://localhost",
514 },
515 ),
516 # Test multi-emails where some are bad
517 (
518 "mailto://user:pass@localhost/[email protected]/test2@/$@!/",
519 {
520 "instance": email.NotifyEmail,
521 "privacy_url": "mailto://user:****@localhost/",
522 },
523 ),
524 (
525 "mailto://user:pass@localhost/?bcc=test2@,$@!/",
526 {
527 "instance": email.NotifyEmail,
528 },
529 ),
530 (
531 "mailto://user:pass@localhost/?cc=test2@,$@!/",
532 {
533 "instance": email.NotifyEmail,
534 },
535 ),
536 (
537 "mailto://user:pass@localhost/?reply=test2@,$@!/",
538 {
539 "instance": email.NotifyEmail,
540 },
541 ),
542 )
543
544
545 @mock.patch("smtplib.SMTP")
546 @mock.patch("smtplib.SMTP_SSL")
547 def test_plugin_email(mock_smtp, mock_smtpssl):
548 """NotifyEmail() General Checks."""
549
550 # iterate over our dictionary and test it out
551 for url, meta in TEST_URLS:
552 # Our expected instance
553 instance = meta.get("instance", None)
554
555 # Our expected server objects
556 self = meta.get("self", None)
557
558 # Our expected Query response (True, False, or exception type)
559 response = meta.get("response", True)
560
561 # Our expected privacy url
562 # Don't set this if don't need to check it's value
563 privacy_url = meta.get("privacy_url")
564
565 test_smtplib_exceptions = meta.get("test_smtplib_exceptions", False)
566
567 # Our mock of our socket action
568 mock_socket = mock.Mock()
569 mock_socket.starttls.return_value = True
570 mock_socket.login.return_value = True
571
572 # Create a mock SMTP Object
573 mock_smtp.return_value = mock_socket
574 mock_smtpssl.return_value = mock_socket
575
576 if test_smtplib_exceptions:
577 # Handle exception testing; first we turn the boolean flag ito
578 # a list of exceptions
579 test_smtplib_exceptions = (
580 smtplib.SMTPHeloError(
581 0, "smtplib.SMTPHeloError() not handled"
582 ),
583 smtplib.SMTPException(
584 0, "smtplib.SMTPException() not handled"
585 ),
586 RuntimeError(0, "smtplib.HTTPError() not handled"),
587 smtplib.SMTPRecipientsRefused(
588 "smtplib.SMTPRecipientsRefused() not handled"
589 ),
590 smtplib.SMTPSenderRefused(
591 0,
592 "smtplib.SMTPSenderRefused() not handled",
593 "[email protected]",
594 ),
595 smtplib.SMTPDataError(
596 0, "smtplib.SMTPDataError() not handled"
597 ),
598 smtplib.SMTPServerDisconnected(
599 "smtplib.SMTPServerDisconnected() not handled"
600 ),
601 )
602
603 try:
604 obj = Apprise.instantiate(url, suppress_exceptions=False)
605
606 if obj is None:
607 # We're done (assuming this is what we were expecting)
608 assert instance is None
609 continue
610
611 if instance is None:
612 # Expected None but didn't get it
613 raise AssertionError()
614
615 assert isinstance(obj, instance)
616
617 if isinstance(obj, NotifyBase):
618 # We loaded okay; now lets make sure we can reverse this url
619 assert isinstance(obj.url(), str)
620
621 # Get our URL Identifier
622 assert isinstance(obj.url_id(), str)
623
624 # Verify we can acquire a target count as an integer
625 assert isinstance(len(obj), int)
626
627 # Test url() with privacy=True
628 assert isinstance(obj.url(privacy=True), str)
629
630 # Some Simple Invalid Instance Testing
631 assert instance.parse_url(None) is None
632 assert instance.parse_url(object) is None
633 assert instance.parse_url(42) is None
634
635 if privacy_url and not obj.url(privacy=True).startswith(
636 # Assess that our privacy url is as expected
637 privacy_url
638 ):
639 raise AssertionError(
640 f"URL: {url} Privacy URL:"
641 f" '{obj.url(privacy=True)[: len(privacy_url)]}' !="
642 f" expected '{privacy_url}'"
643 )
644
645 # Instantiate the exact same object again using the URL from
646 # the one that was already created properly
647 obj_cmp = Apprise.instantiate(obj.url())
648
649 # Our object should be the same instance as what we had
650 # originally expected above.
651 if not isinstance(obj_cmp, NotifyBase):
652 # Assert messages are hard to trace back with the way
653 # these tests work. Just printing before throwing our
654 # assertion failure makes things easier to debug later on
655 raise AssertionError()
656
657 # Verify there is no change from the old and the new
658 assert len(obj) == len(obj_cmp), (
659 f"{len(obj)} targets found in "
660 f"{obj.url(privacy=True)}, "
661 f"But {len(obj_cmp)} targets found in "
662 f"{obj_cmp.url(privacy=True)}"
663 )
664 if self:
665 # Iterate over our expected entries inside of our object
666 for key, val in self.items():
667 # Test that our object has the desired key
668 assert hasattr(key, obj)
669 assert getattr(key, obj) == val
670
671 try:
672 if test_smtplib_exceptions is False:
673 # Verify we can acquire a target count as an integer
674 targets = len(obj)
675
676 # check that we're as expected
677 assert (
678 obj.notify(
679 title="test",
680 body="body",
681 notify_type=NotifyType.INFO,
682 )
683 == response
684 )
685
686 if response:
687 # If we successfully got a response, there must have
688 # been at least 1 target present
689 assert targets > 0
690
691 else:
692 for exception in test_smtplib_exceptions:
693 mock_socket.sendmail.side_effect = exception
694 try:
695 assert (
696 obj.notify(
697 title="test",
698 body="body",
699 notify_type=NotifyType.INFO,
700 )
701 is False
702 )
703
704 except AssertionError:
705 # Don't mess with these entries
706 raise
707
708 except Exception:
709 # We can't handle this exception type
710 raise
711
712 except AssertionError:
713 # Don't mess with these entries
714 raise
715
716 except Exception as e:
717 # Check that we were expecting this exception to happen
718 if not isinstance(e, response):
719 raise
720
721 except AssertionError:
722 # Don't mess with these entries
723 raise
724
725 except Exception as e:
726 # Handle our exception
727 if instance is None:
728 raise
729
730 if not isinstance(e, instance):
731 raise
732
733
734 @mock.patch("smtplib.SMTP")
735 @mock.patch("smtplib.SMTP_SSL")
736 def test_plugin_email_webbase_lookup(mock_smtp, mock_smtpssl):
737 """NotifyEmail() Web Based Lookup Tests."""
738
739 # Insert a test email at the head of our table
740 email.templates.EMAIL_TEMPLATES = (
741 *(
742 (
743 "Testing Lookup",
744 re.compile(r"^(?P<id>[^@]+)@(?P<domain>l2g\.com)$", re.I),
745 {
746 "port": 123,
747 "smtp_host": "smtp.l2g.com",
748 "secure": True,
749 "login_type": (email.WebBaseLogin.USERID,),
750 },
751 ),
752 ),
753 *email.templates.EMAIL_TEMPLATES,
754 )
755
756 obj = Apprise.instantiate(
757 "mailto://user:[email protected]",
758 suppress_exceptions=True,
759 )
760
761 assert isinstance(obj, email.NotifyEmail)
762 assert len(obj.targets) == 1
763 assert (False, "[email protected]") in obj.targets
764 assert obj.from_addr[0] == obj.app_id
765 assert obj.from_addr[1] == "[email protected]"
766 assert obj.password == "pass"
767 assert obj.user == "user"
768 assert obj.secure is True
769 assert obj.port == 123
770 assert obj.smtp_host == "smtp.l2g.com"
771
772 # We get the same results if an email is identified as the username
773 # because the USERID variable forces that we can't use an email
774 obj = Apprise.instantiate(
775 "mailto://_:[email protected][email protected]", suppress_exceptions=True
776 )
777 assert obj.user == "user"
778
779
780 @mock.patch("smtplib.SMTP")
781 def test_plugin_email_smtplib_init_fail(mock_smtplib):
782 """NotifyEmail() Test exception handling when calling smtplib.SMTP()"""
783
784 obj = Apprise.instantiate(
785 "mailto://user:[email protected]", suppress_exceptions=False
786 )
787 assert isinstance(obj, email.NotifyEmail)
788
789 # Support Exception handling of smtplib.SMTP
790 mock_smtplib.side_effect = RuntimeError("Test")
791
792 assert (
793 obj.notify(body="body", title="test", notify_type=NotifyType.INFO)
794 is False
795 )
796
797 # A handled and expected exception
798 mock_smtplib.side_effect = smtplib.SMTPException("Test")
799 assert (
800 obj.notify(body="body", title="test", notify_type=NotifyType.INFO)
801 is False
802 )
803
804
805 @mock.patch("smtplib.SMTP")
806 def test_plugin_email_smtplib_send_okay(mock_smtplib):
807 """NotifyEmail() Test a successfully sent email."""
808
809 # Defaults to HTML
810 obj = Apprise.instantiate(
811 "mailto://user:[email protected]", suppress_exceptions=False
812 )
813 assert isinstance(obj, email.NotifyEmail)
814
815 # Support an email simulation where we can correctly quit
816 mock_smtplib.starttls.return_value = True
817 mock_smtplib.login.return_value = True
818 mock_smtplib.sendmail.return_value = True
819 mock_smtplib.quit.return_value = True
820
821 assert (
822 obj.notify(body="body", title="test", notify_type=NotifyType.INFO)
823 is True
824 )
825
826 # Set Text
827 obj = Apprise.instantiate(
828 "mailto://user:[email protected]?format=text", suppress_exceptions=False
829 )
830 assert isinstance(obj, email.NotifyEmail)
831
832 assert (
833 obj.notify(body="body", title="test", notify_type=NotifyType.INFO)
834 is True
835 )
836
837 # Create an apprise object to work with as well
838 a = Apprise()
839 assert a.add("mailto://user:[email protected]?format=text")
840
841 # Send Attachment with success
842 attach = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
843 assert (
844 obj.notify(
845 body="body",
846 title="test",
847 notify_type=NotifyType.INFO,
848 attach=attach,
849 )
850 is True
851 )
852
853 # same results happen from our Apprise object
854 assert a.notify(body="body", title="test", attach=attach) is True
855
856 # test using an Apprise Attachment object
857 assert (
858 obj.notify(
859 body="body",
860 title="test",
861 notify_type=NotifyType.INFO,
862 attach=AppriseAttachment(attach),
863 )
864 is True
865 )
866
867 # same results happen from our Apprise object
868 assert (
869 a.notify(body="body", title="test", attach=AppriseAttachment(attach))
870 is True
871 )
872
873 # test using an Apprise in memory attachement object
874 attachment = AppriseAttachment()
875 attachment.add(
876 AttachMemory(
877 content="attachment",
878 name="attached.txt",
879 mimetype="text/plain",
880 )
881 )
882 assert (
883 obj.notify(
884 body="body",
885 title="test",
886 notify_type=NotifyType.INFO,
887 attach=attachment,
888 )
889 is True
890 )
891
892 # same results happen from our Apprise object
893 assert a.notify(body="body", title="test", attach=attachment) is True
894
895 max_file_size = AttachBase.max_file_size
896 # Now do a case where the file can't be sent
897
898 AttachBase.max_file_size = 1
899 assert (
900 obj.notify(
901 body="body",
902 title="test",
903 notify_type=NotifyType.INFO,
904 attach=attach,
905 )
906 is False
907 )
908
909 # same results happen from our Apprise object
910 assert a.notify(body="body", title="test", attach=attach) is False
911
912 # Restore value
913 AttachBase.max_file_size = max_file_size
914
915
916 @mock.patch("smtplib.SMTP")
917 def test_plugin_email_smtplib_send_multiple_recipients(mock_smtplib):
918 """Verify that NotifyEmail() will use a single SMTP session for submitting
919 multiple emails."""
920
921 # Defaults to HTML
922 obj = Apprise.instantiate(
923 "mailto://user:[email protected]?"
924 "[email protected],[email protected]&"
925 "[email protected]&[email protected]",
926 suppress_exceptions=False,
927 )
928 assert isinstance(obj, email.NotifyEmail)
929
930 assert (
931 obj.notify(body="body", title="test", notify_type=NotifyType.INFO)
932 is True
933 )
934
935 assert mock_smtplib.mock_calls == [
936 mock.call("mail.example.org", 25, None, timeout=15),
937 mock.call().login("user", "pass"),
938 mock.call().sendmail(
939 "[email protected]",
940 ["[email protected]", "[email protected]", "[email protected]"],
941 mock.ANY,
942 ),
943 mock.call().sendmail(
944 "[email protected]",
945 ["[email protected]", "[email protected]", "[email protected]"],
946 mock.ANY,
947 ),
948 mock.call().quit(),
949 ]
950
951 # No from= used in the above
952 assert re.match(r".*from=.*", obj.url()) is None
953 # No mode= as this isn't a secure connection
954 assert re.match(r".*mode=.*", obj.url()) is None
955 # No smtp= as the SMTP server is the same as the hostname in this case
956 assert re.match(r".*smtp=.*", obj.url()) is None
957 # URL is assembled based on provided user
958 assert (
959 re.match(r"^mailto://user:pass\@mail.example.org/.*", obj.url())
960 is not None
961 )
962
963 # Verify our added emails are still part of the URL
964 assert re.match(r".*/foo%40example.net[/?].*", obj.url()) is not None
965 assert re.match(r".*/bar%40example.com[/?].*", obj.url()) is not None
966
967 assert re.match(r".*bcc=qux%40example.org.*", obj.url()) is not None
968 assert re.match(r".*cc=baz%40example.org.*", obj.url()) is not None
969
970
971 @mock.patch("smtplib.SMTP")
972 def test_plugin_email_timezone(mock_smtp):
973 """NotifyEmail() Timezone Handling"""
974
975 response = mock.Mock()
976 mock_smtp.return_value = response
977
978 # Loads America/Toronto
979 results = email.NotifyEmail.parse_url(
980 "mailtos://user:[email protected]:123?tz=Toronto"
981 )
982 assert isinstance(results, dict)
983 # timezone is detected
984 assert "tz" in results
985
986 # Instantiate the object
987 obj = email.NotifyEmail(**results)
988 assert isinstance(obj, email.NotifyEmail)
989 assert obj.tzinfo.key == "America/Toronto"
990 # Verify our URL has defined our timezone
991 # %2F = escaped '/'
992 assert "tz=America%2FToronto" in obj.url()
993
994 # No Timezone setup/default
995 results = email.NotifyEmail.parse_url(
996 "mailtos://user:[email protected]:1235"
997 )
998 assert "tz" not in results
999
1000 # Instantiate the object
1001 obj = email.NotifyEmail(**results)
1002 assert isinstance(obj, email.NotifyEmail)
1003 # Defaults to our system
1004 assert obj.tzinfo == datetime.now().astimezone().tzinfo
1005 assert "tz=" not in obj.url()
1006
1007 # Now we'll work with an Asset to identify how it can hold
1008 # our default global variable (initialization proves case
1009 # insensitive initialization is supported)
1010 asset = AppriseAsset(timezone="aMErica/vanCOUver")
1011
1012 # Instatiate our object once again using the same variable set
1013 # as above
1014 obj = email.NotifyEmail(**results, asset=asset)
1015 # Defaults to our system
1016 # lower() is required since Mac and Window are not case sensitive and will
1017 # See output as it was passed in and not corrected per IANA
1018 assert obj.tzinfo.key.lower() == "america/vancouver"
1019 assert "tz=" not in obj.url()
1020
1021 # Having ourselves a default variable also does not prevent
1022 # anyone from defining their own over-ride is still supported:
1023
1024 # Loads America/Montreal
1025 results = email.NotifyEmail.parse_url(
1026 "mailtos://user:[email protected]:321?tz=Montreal"
1027 )
1028 assert isinstance(results, dict)
1029 # timezone is detected
1030 assert "tz" in results
1031
1032 # Instantiate the object
1033 obj = email.NotifyEmail(**results)
1034 assert isinstance(obj, email.NotifyEmail)
1035 assert obj.tzinfo.key == "America/Montreal"
1036 # Verify our URL has defined our timezone
1037 # %2F = escaped '/'
1038 assert "tz=America%2FMontreal" in obj.url()
1039
1040
1041 @mock.patch("smtplib.SMTP")
1042 def test_plugin_email_smtplib_internationalization(mock_smtp):
1043 """NotifyEmail() Internationalization Handling."""
1044
1045 # i18n test
1046 email_url = "".join(
1047 [
1048 "mailto://user:[email protected]?",
1049 "name=Например%20так", # noqa: RUF001
1050 ]
1051 )
1052
1053 obj = Apprise.instantiate(
1054 email_url,
1055 suppress_exceptions=False,
1056 )
1057
1058 assert isinstance(obj, email.NotifyEmail)
1059
1060 class SMTPMock:
1061 def sendmail(self, *args, **kwargs):
1062 """Over-ride sendmail calls so we can check our our
1063 internationalization formatting went."""
1064
1065 match_subject = re.search(
1066 r"\n?(?P<line>Subject: (?P<subject>(.+?)))\n(?:[a-z0-9-]+:)",
1067 args[2],
1068 re.I | re.M | re.S,
1069 )
1070 assert match_subject is not None
1071
1072 match_from = re.search(
1073 r"^(?P<line>From: (?P<name>.+) <(?P<email>[^>]+)>)$",
1074 args[2],
1075 re.I | re.M,
1076 )
1077 assert match_from is not None
1078
1079 # Verify our output was correctly stored
1080 assert match_from.group("email") == "[email protected]"
1081
1082 assert (
1083 decode_header(match_from.group("name"))[0][0].decode("utf-8")
1084 == "Например так"
1085 )
1086
1087 assert (
1088 decode_header(match_subject.group("subject"))[0][0].decode(
1089 "utf-8"
1090 )
1091 == "دعونا نجعل العالم مكانا أفضل."
1092 )
1093
1094 # Dummy Function
1095 def quit(self, *args, **kwargs):
1096 return True
1097
1098 # Dummy Function
1099 def starttls(self, *args, **kwargs):
1100 return True
1101
1102 # Dummy Function
1103 def login(self, *args, **kwargs):
1104 return True
1105
1106 # Prepare our object we will test our generated email against
1107 mock_smtp.return_value = SMTPMock()
1108
1109 # Further test encoding through the message content as well
1110 assert (
1111 obj.notify(
1112 # Google Translated to Arabic:
1113 # "Let's make the world a better place."
1114 title="دعونا نجعل العالم مكانا أفضل.",
1115 # Google Translated to Hungarian: "One line of code at a time.'
1116 body="Egy sor kódot egyszerre.",
1117 notify_type=NotifyType.INFO,
1118 )
1119 is True
1120 )
1121
1122
1123 def test_plugin_email_url_escaping():
1124 """NotifyEmail() Test that user/passwords are properly escaped from URL."""
1125 # quote(' %20')
1126 passwd = "%20%2520"
1127
1128 # Basically we want to check that ' ' equates to %20 and % equates to %25
1129 # So the above translates to ' %20' (a space in front of %20). We want
1130 # to verify the handling of the password escaping and when it happens.
1131 # a very bad response would be ' ' (double space)
1132 obj = email.NotifyEmail.parse_url(
1133 f"mailto://user:{passwd}@gmail.com?format=text"
1134 )
1135
1136 assert isinstance(obj, dict)
1137 assert "password" in obj
1138
1139 # Escaping doesn't happen at this stage because we want to leave this to
1140 # the plugins discretion
1141 assert obj.get("password") == "%20%2520"
1142
1143 obj = Apprise.instantiate(
1144 f"mailto://user:{passwd}@gmail.com?format=text",
1145 suppress_exceptions=False,
1146 )
1147 assert isinstance(obj, email.NotifyEmail)
1148
1149 # The password is escaped only 'once'
1150 assert obj.password == " %20"
1151
1152
1153 def test_plugin_email_url_variations():
1154 """NotifyEmail() Test URL variations to ensure parsing is correct."""
1155 # Test variations of username required to be an email address
1156 # [email protected]
1157 obj = Apprise.instantiate(
1158 "mailto://{user}:{passwd}@example.com?smtp=example.com".format(
1159 user="apprise%40example21.ca", passwd="abcd123"
1160 ),
1161 suppress_exceptions=False,
1162 )
1163 assert isinstance(obj, email.NotifyEmail)
1164
1165 assert obj.password == "abcd123"
1166 assert obj.user == "[email protected]"
1167
1168 # No from= used in the above
1169 assert re.match(r".*from=.*", obj.url()) is None
1170 # No mode= as this isn't a secure connection
1171 assert re.match(r".*mode=.*", obj.url()) is None
1172 # No smtp= as the SMTP server is the same as the hostname in this case
1173 # even though it was explicitly specified
1174 assert re.match(r".*smtp=.*", obj.url()) is None
1175 # URL is assembled based on provided user
1176 assert (
1177 re.match(r"^mailto://apprise:abcd123\@example.com/.*", obj.url())
1178 is not None
1179 )
1180
1181 # test username specified in the url body (as an argument)
1182 # this always over-rides the entry at the front of the url
1183 obj = Apprise.instantiate(
1184 "mailto://_:{passwd}@example.com?user={user}".format(
1185 user="apprise%40example21.ca", passwd="abcd123"
1186 ),
1187 suppress_exceptions=False,
1188 )
1189 assert isinstance(obj, email.NotifyEmail)
1190
1191 assert obj.password == "abcd123"
1192 assert obj.user == "[email protected]"
1193
1194 # No from= used in the above
1195 assert re.match(r".*from=.*", obj.url()) is None
1196 # No mode= as this isn't a secure connection
1197 assert re.match(r".*mode=.*", obj.url()) is None
1198 # No smtp= as the SMTP server is the same as the hostname in this case
1199 assert re.match(r".*smtp=.*", obj.url()) is None
1200 # URL is assembled based on provided user
1201 assert (
1202 re.match(r"^mailto://apprise:abcd123\@example.com/.*", obj.url())
1203 is not None
1204 )
1205
1206 # test user and password specified in the url body (as an argument)
1207 # this always over-rides the entries at the front of the url
1208 obj = Apprise.instantiate(
1209 "mailtos://_:[email protected]?user={user}&pass={passwd}".format(
1210 user="apprise%40example21.ca", passwd="abcd123"
1211 ),
1212 suppress_exceptions=False,
1213 )
1214 assert isinstance(obj, email.NotifyEmail)
1215
1216 assert obj.password == "abcd123"
1217 assert obj.user == "[email protected]"
1218 assert len(obj.targets) == 1
1219 assert (False, "[email protected]") in obj.targets
1220 assert obj.from_addr[0] == obj.app_id
1221 assert obj.from_addr[1] == "[email protected]"
1222 assert obj.targets[0][0] is False
1223 assert obj.targets[0][1] == obj.from_addr[1]
1224
1225 # No from= used in the above
1226 assert re.match(r".*from=.*", obj.url()) is None
1227 # Default mode is starttls
1228 assert re.match(r".*mode=starttls.*", obj.url()) is not None
1229 # No smtp= as the SMTP server is the same as the hostname in this case
1230 assert re.match(r".*smtp=.*", obj.url()) is None
1231 # URL is assembled based on provided user
1232 assert (
1233 re.match(r"^mailtos://apprise:abcd123\@example.com/.*", obj.url())
1234 is not None
1235 )
1236
1237 # test user and password specified in the url body (as an argument)
1238 # this always over-rides the entries at the front of the url
1239 # this is similar to the previous test except we're only specifying
1240 # this information in the kwargs
1241 obj = Apprise.instantiate(
1242 "mailto://example.com?user={user}&pass={passwd}".format(
1243 user="apprise%40example21.ca", passwd="abcd123"
1244 ),
1245 suppress_exceptions=False,
1246 )
1247 assert isinstance(obj, email.NotifyEmail)
1248
1249 assert obj.password == "abcd123"
1250 assert obj.user == "[email protected]"
1251 assert len(obj.targets) == 1
1252 assert (False, "[email protected]") in obj.targets
1253 assert obj.from_addr[0] == obj.app_id
1254 assert obj.from_addr[1] == "[email protected]"
1255 assert obj.targets[0][0] is False
1256 assert obj.targets[0][1] == obj.from_addr[1]
1257 assert obj.smtp_host == "example.com"
1258
1259 # No from= used in the above
1260 assert re.match(r".*from=.*", obj.url()) is None
1261 # No mode= as this isn't a secure connection
1262 assert re.match(r".*mode=.*", obj.url()) is None
1263 # No smtp= as the SMTP server is the same as the hostname in this case
1264 assert re.match(r".*smtp=.*", obj.url()) is None
1265 # URL is assembled based on provided user
1266 assert (
1267 re.match(r"^mailto://apprise:abcd123\@example.com/.*", obj.url())
1268 is not None
1269 )
1270
1271 # test a complicated example
1272 obj = Apprise.instantiate(
1273 "mailtos://{user}:{passwd}@{host}:{port}"
1274 "?smtp={smtp_host}&format=text&from=Charles<{this}>&to={that}".format(
1275 user="apprise%40example21.ca",
1276 passwd="abcd123",
1277 host="example.com",
1278 port=1234,
1279 this="[email protected]",
1280 that="[email protected]",
1281 smtp_host="smtp.example.edu",
1282 ),
1283 suppress_exceptions=False,
1284 )
1285 assert isinstance(obj, email.NotifyEmail)
1286
1287 assert obj.password == "abcd123"
1288 assert obj.user == "[email protected]"
1289 assert obj.host == "example.com"
1290 assert obj.port == 1234
1291 assert obj.smtp_host == "smtp.example.edu"
1292 assert len(obj.targets) == 1
1293 assert (False, "[email protected]") in obj.targets
1294 assert obj.from_addr[0] == "Charles"
1295 assert obj.from_addr[1] == "[email protected]"
1296 assert (
1297 re.match(r".*from=Charles%20%3Cfrom%40example.jp%3E.*", obj.url())
1298 is not None
1299 )
1300
1301 # Test Tagging under various urll encodings
1302 for toaddr in (
1303 "/[email protected]",
1304 "[email protected]",
1305 "/john.smith%[email protected]",
1306 "?to=john.smith%[email protected]",
1307 ):
1308 obj = Apprise.instantiate(f"mailto://user:[email protected]{toaddr}")
1309 assert isinstance(obj, email.NotifyEmail)
1310 assert obj.password == "pass"
1311 assert obj.user == "user"
1312 assert obj.host == "domain.com"
1313 assert obj.from_addr[0] == obj.app_id
1314 assert obj.from_addr[1] == "[email protected]"
1315 assert len(obj.targets) == 1
1316 assert obj.targets[0][0] is False
1317 assert obj.targets[0][1] == "[email protected]"
1318
1319
1320 def test_plugin_email_dict_variations():
1321 """NotifyEmail() Test email dictionary variations to ensure parsing is
1322 correct."""
1323 # Test variations of username required to be an email address
1324 # [email protected]
1325 obj = Apprise.instantiate(
1326 {
1327 "schema": "mailto",
1328 "user": "[email protected]",
1329 "password": "abd123",
1330 "host": "example.com",
1331 },
1332 suppress_exceptions=False,
1333 )
1334 assert isinstance(obj, email.NotifyEmail)
1335
1336
1337 @mock.patch("smtplib.SMTP_SSL")
1338 @mock.patch("smtplib.SMTP")
1339 def test_plugin_email_url_parsing(mock_smtp, mock_smtp_ssl):
1340 """NotifyEmail() Test email url parsing."""
1341
1342 response = mock.Mock()
1343 mock_smtp_ssl.return_value = response
1344 mock_smtp.return_value = response
1345
1346 # Test variations of username required to be an email address
1347 # [email protected]; we also test an over-ride port on a template driven
1348 # mailto:// entry
1349 results = email.NotifyEmail.parse_url(
1350 "mailtos://user:[email protected]:444"
1351 "[email protected]&name=test%20name"
1352 )
1353 assert isinstance(results, dict)
1354 assert results["from_addr"] == "test name"
1355 assert results["user"] == "user"
1356 assert results["port"] == 444
1357 assert results["host"] == "hotmail.com"
1358 assert results["password"] == "pass123"
1359 assert "[email protected]" in results["targets"]
1360
1361 obj = Apprise.instantiate(results, suppress_exceptions=False)
1362 assert isinstance(obj, email.NotifyEmail)
1363
1364 assert mock_smtp.call_count == 0
1365 assert mock_smtp_ssl.call_count == 0
1366 assert obj.notify("test") is True
1367 assert mock_smtp.call_count == 1
1368 assert mock_smtp_ssl.call_count == 0
1369 assert response.starttls.call_count == 1
1370 assert response.login.call_count == 1
1371 assert response.sendmail.call_count == 1
1372 # Store our Sent Arguments
1373 # Syntax is:
1374 # sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
1375 # [0] [1] [2]
1376 from_ = response.sendmail.call_args[0][0]
1377 to = response.sendmail.call_args[0][1]
1378 msg = response.sendmail.call_args[0][2]
1379 assert from_ == "[email protected]"
1380 assert isinstance(to, list)
1381 assert len(to) == 1
1382 assert to[0] == "[email protected]"
1383 assert msg.split("\n")[-3] == "test"
1384
1385 # Our URL port was over-ridden (on template) to use 444
1386 # We can verify that this was correctly saved
1387 assert obj.url().startswith(
1388 "mailtos://user:[email protected]:444/user2%40yahoo.com"
1389 )
1390 assert "mode=starttls" in obj.url()
1391 assert "smtp=smtp-mail.outlook.com" in obj.url()
1392
1393 mock_smtp.reset_mock()
1394 mock_smtp_ssl.reset_mock()
1395 response.reset_mock()
1396
1397 # The below switches the `name` with the `to` to verify the results
1398 # are the same; it also verfies that the mode gets changed to SSL
1399 # instead of STARTTLS
1400 results = email.NotifyEmail.parse_url(
1401 "mailtos://user:[email protected]?smtp=override.com"
1402 "&name=test%20name&[email protected]&mode=ssl"
1403 )
1404 assert isinstance(results, dict)
1405 assert results["from_addr"] == "test name"
1406 assert results["user"] == "user"
1407 assert results["host"] == "hotmail.com"
1408 assert results["password"] == "pass123"
1409 assert "[email protected]" in results["targets"]
1410 assert results["secure_mode"] == "ssl"
1411 obj = Apprise.instantiate(results, suppress_exceptions=False)
1412 assert isinstance(obj, email.NotifyEmail)
1413
1414 assert mock_smtp.call_count == 0
1415 assert mock_smtp_ssl.call_count == 0
1416 assert obj.notify("test") is True
1417 assert mock_smtp.call_count == 0
1418 assert mock_smtp_ssl.call_count == 1
1419 assert response.starttls.call_count == 0
1420 assert response.login.call_count == 1
1421 assert response.sendmail.call_count == 1
1422 # Store our Sent Arguments
1423 # Syntax is:
1424 # sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
1425 # [0] [1] [2]
1426 from_ = response.sendmail.call_args[0][0]
1427 to = response.sendmail.call_args[0][1]
1428 msg = response.sendmail.call_args[0][2]
1429 assert from_ == "[email protected]"
1430 assert isinstance(to, list)
1431 assert len(to) == 1
1432 assert to[0] == "[email protected]"
1433 assert msg.split("\n")[-3] == "test"
1434
1435 user, pw = response.login.call_args[0]
1436 # the SMTP Server was ovr
1437 assert pw == "pass123"
1438 assert user == "user"
1439
1440 assert obj.url().startswith(
1441 "mailtos://user:[email protected]/user2%40yahoo.com"
1442 )
1443 # Test that our template over-ride worked
1444 assert "mode=ssl" in obj.url()
1445 assert "smtp=override.com" in obj.url()
1446 # No reply address specified
1447 assert "reply=" not in obj.url()
1448
1449 mock_smtp.reset_mock()
1450 mock_smtp_ssl.reset_mock()
1451 response.reset_mock()
1452
1453 #
1454 # Test outlook/hotmail lookups
1455 #
1456 results = email.NotifyEmail.parse_url("mailtos://user:[email protected]")
1457 obj = Apprise.instantiate(results, suppress_exceptions=False)
1458 assert isinstance(obj, email.NotifyEmail)
1459 assert obj.smtp_host == "smtp-mail.outlook.com"
1460 # No entries in the reply_to
1461 assert not obj.reply_to
1462
1463 assert mock_smtp.call_count == 0
1464 assert mock_smtp_ssl.call_count == 0
1465 assert response.starttls.call_count == 0
1466 assert obj.notify("test") is True
1467 assert mock_smtp.call_count == 1
1468 assert mock_smtp_ssl.call_count == 0
1469 assert response.starttls.call_count == 1
1470 assert response.login.call_count == 1
1471 assert response.sendmail.call_count == 1
1472
1473 user, pw = response.login.call_args[0]
1474 assert pw == "pass123"
1475 assert user == "[email protected]"
1476
1477 mock_smtp.reset_mock()
1478 mock_smtp_ssl.reset_mock()
1479 response.reset_mock()
1480
1481 results = email.NotifyEmail.parse_url("mailtos://user:[email protected]")
1482 obj = Apprise.instantiate(results, suppress_exceptions=False)
1483 assert isinstance(obj, email.NotifyEmail)
1484 assert obj.smtp_host == "smtp.outlook.com"
1485 # No entries in the reply_to
1486 assert not obj.reply_to
1487
1488 assert mock_smtp.call_count == 0
1489 assert mock_smtp_ssl.call_count == 0
1490 assert response.starttls.call_count == 0
1491 assert obj.notify("test") is True
1492 assert mock_smtp.call_count == 1
1493 assert mock_smtp_ssl.call_count == 0
1494 assert response.starttls.call_count == 1
1495 assert response.login.call_count == 1
1496 assert response.sendmail.call_count == 1
1497
1498 user, pw = response.login.call_args[0]
1499 assert pw == "pass123"
1500 assert user == "[email protected]"
1501
1502 mock_smtp.reset_mock()
1503 mock_smtp_ssl.reset_mock()
1504 response.reset_mock()
1505
1506 results = email.NotifyEmail.parse_url(
1507 "mailtos://user:[email protected]"
1508 )
1509 obj = Apprise.instantiate(results, suppress_exceptions=False)
1510 assert isinstance(obj, email.NotifyEmail)
1511 assert obj.smtp_host == "smtp.outlook.com"
1512 # No entries in the reply_to
1513 assert not obj.reply_to
1514
1515 assert mock_smtp.call_count == 0
1516 assert mock_smtp_ssl.call_count == 0
1517 assert response.starttls.call_count == 0
1518 assert obj.notify("test") is True
1519 assert mock_smtp.call_count == 1
1520 assert mock_smtp_ssl.call_count == 0
1521 assert response.starttls.call_count == 1
1522 assert response.login.call_count == 1
1523 assert response.sendmail.call_count == 1
1524
1525 user, pw = response.login.call_args[0]
1526 assert pw == "pass123"
1527 assert user == "[email protected]"
1528
1529 mock_smtp.reset_mock()
1530 mock_smtp_ssl.reset_mock()
1531 response.reset_mock()
1532
1533 # Consisitency Checks
1534 results = email.NotifyEmail.parse_url(
1535 "mailtos://outlook.com?smtp=smtp.outlook.com"
1536 "&[email protected]&pass=app.pw"
1537 )
1538 obj1 = Apprise.instantiate(results, suppress_exceptions=False)
1539 assert isinstance(obj1, email.NotifyEmail)
1540 assert obj1.smtp_host == "smtp.outlook.com"
1541 assert obj1.user == "[email protected]"
1542 assert obj1.password == "app.pw"
1543 assert obj1.secure_mode == "starttls"
1544 assert obj1.port == 587
1545
1546 assert mock_smtp.call_count == 0
1547 assert mock_smtp_ssl.call_count == 0
1548 assert response.starttls.call_count == 0
1549 assert obj1.notify("test") is True
1550 assert mock_smtp.call_count == 1
1551 assert mock_smtp_ssl.call_count == 0
1552 assert response.starttls.call_count == 1
1553 assert response.login.call_count == 1
1554 assert response.sendmail.call_count == 1
1555
1556 user, pw = response.login.call_args[0]
1557 assert pw == "app.pw"
1558 assert user == "[email protected]"
1559
1560 mock_smtp.reset_mock()
1561 mock_smtp_ssl.reset_mock()
1562 response.reset_mock()
1563
1564 results = email.NotifyEmail.parse_url("mailtos://user:[email protected]")
1565 obj2 = Apprise.instantiate(results, suppress_exceptions=False)
1566 assert isinstance(obj2, email.NotifyEmail)
1567 assert obj2.smtp_host == obj1.smtp_host
1568 assert obj2.user == obj1.user
1569 assert obj2.password == obj1.password
1570 assert obj2.secure_mode == obj1.secure_mode
1571 assert obj2.port == obj1.port
1572
1573 assert mock_smtp.call_count == 0
1574 assert mock_smtp_ssl.call_count == 0
1575 assert response.starttls.call_count == 0
1576 assert obj2.notify("test") is True
1577 assert mock_smtp.call_count == 1
1578 assert mock_smtp_ssl.call_count == 0
1579 assert response.starttls.call_count == 1
1580 assert response.login.call_count == 1
1581 assert response.sendmail.call_count == 1
1582
1583 user, pw = response.login.call_args[0]
1584 assert pw == "app.pw"
1585 assert user == "[email protected]"
1586
1587 mock_smtp.reset_mock()
1588 mock_smtp_ssl.reset_mock()
1589 response.reset_mock()
1590
1591 results = email.NotifyEmail.parse_url("mailto://user:[email protected]")
1592 obj = Apprise.instantiate(results, suppress_exceptions=False)
1593 assert isinstance(obj, email.NotifyEmail)
1594 assert obj.smtp_host == "smtp.comcast.net"
1595 assert obj.user == "[email protected]"
1596 assert obj.password == "pass"
1597 assert obj.secure_mode == "ssl"
1598 assert obj.port == 465
1599
1600 assert mock_smtp.call_count == 0
1601 assert mock_smtp_ssl.call_count == 0
1602 assert response.starttls.call_count == 0
1603 assert obj.notify("test") is True
1604 assert mock_smtp.call_count == 0
1605 assert mock_smtp_ssl.call_count == 1
1606 assert response.starttls.call_count == 0
1607 assert response.login.call_count == 1
1608 assert response.sendmail.call_count == 1
1609
1610 user, pw = response.login.call_args[0]
1611 assert pw == "pass"
1612 assert user == "[email protected]"
1613
1614 mock_smtp.reset_mock()
1615 mock_smtp_ssl.reset_mock()
1616 response.reset_mock()
1617
1618 results = email.NotifyEmail.parse_url("mailtos://user:[email protected]")
1619 obj = Apprise.instantiate(results, suppress_exceptions=False)
1620 assert isinstance(obj, email.NotifyEmail)
1621 # No entries in the reply_to
1622 assert not obj.reply_to
1623
1624 assert mock_smtp.call_count == 0
1625 assert mock_smtp_ssl.call_count == 0
1626 assert response.starttls.call_count == 0
1627 assert obj.notify("test") is True
1628 assert mock_smtp.call_count == 1
1629 assert mock_smtp_ssl.call_count == 0
1630 assert response.starttls.call_count == 1
1631 assert response.login.call_count == 1
1632 assert response.sendmail.call_count == 1
1633
1634 user, pw = response.login.call_args[0]
1635 assert pw == "pass123"
1636 assert user == "[email protected]"
1637
1638 mock_smtp.reset_mock()
1639 mock_smtp_ssl.reset_mock()
1640 response.reset_mock()
1641
1642 results = email.NotifyEmail.parse_url("mailtos://user:[email protected]")
1643 obj = Apprise.instantiate(results, suppress_exceptions=False)
1644 assert isinstance(obj, email.NotifyEmail)
1645 # No entries in the reply_to
1646 assert not obj.reply_to
1647
1648 assert mock_smtp.call_count == 0
1649 assert mock_smtp_ssl.call_count == 0
1650 assert response.starttls.call_count == 0
1651 assert obj.notify("test") is True
1652 assert mock_smtp.call_count == 1
1653 assert mock_smtp_ssl.call_count == 0
1654 assert response.starttls.call_count == 1
1655 assert response.login.call_count == 1
1656 assert response.sendmail.call_count == 1
1657
1658 user, pw = response.login.call_args[0]
1659 assert pw == "pass123"
1660 assert user == "[email protected]"
1661
1662 mock_smtp.reset_mock()
1663 mock_smtp_ssl.reset_mock()
1664 response.reset_mock()
1665
1666 #
1667 # Test Port Over-Riding
1668 #
1669 results = email.NotifyEmail.parse_url(
1670 "mailtos://abc:[email protected]:465?smtp=smtp.exmail.qq.com&mode=ssl"
1671 )
1672 obj = Apprise.instantiate(results, suppress_exceptions=False)
1673 assert isinstance(obj, email.NotifyEmail)
1674
1675 # Verify our over-rides are in place
1676 assert obj.smtp_host == "smtp.exmail.qq.com"
1677 assert obj.port == 465
1678 assert obj.from_addr[0] == obj.app_id
1679 assert obj.from_addr[1] == "[email protected]"
1680 assert obj.secure_mode == "ssl"
1681 # No entries in the reply_to
1682 assert not obj.reply_to
1683
1684 # No from= used in the above
1685 assert re.match(r".*from=.*", obj.url()) is None
1686 # No Our secure connection is SSL
1687 assert re.match(r".*mode=ssl.*", obj.url()) is not None
1688 # No smtp= as the SMTP server is the same as the hostname in this case
1689 assert re.match(r".*smtp=smtp.exmail.qq.com.*", obj.url()) is not None
1690 # URL is assembled based on provided user (:465 is dropped because it
1691 # is a default port when using xyz.cn)
1692 assert (
1693 re.match(r"^mailtos://abc:[email protected]/.*", obj.url()) is not None
1694 )
1695
1696 assert mock_smtp.call_count == 0
1697 assert mock_smtp_ssl.call_count == 0
1698 assert response.starttls.call_count == 0
1699 assert obj.notify("test") is True
1700 assert mock_smtp.call_count == 0
1701 assert mock_smtp_ssl.call_count == 1
1702 assert response.starttls.call_count == 0
1703 assert response.login.call_count == 1
1704 assert response.sendmail.call_count == 1
1705
1706 user, pw = response.login.call_args[0]
1707 assert pw == "password"
1708 assert user == "abc"
1709
1710 mock_smtp.reset_mock()
1711 mock_smtp_ssl.reset_mock()
1712 response.reset_mock()
1713
1714 results = email.NotifyEmail.parse_url(
1715 "mailtos://abc:[email protected]?"
1716 "smtp=smtp.exmail.qq.com&mode=ssl&port=465"
1717 )
1718 obj = Apprise.instantiate(results, suppress_exceptions=False)
1719 assert isinstance(obj, email.NotifyEmail)
1720
1721 # Verify our over-rides are in place
1722 assert obj.smtp_host == "smtp.exmail.qq.com"
1723 assert obj.port == 465
1724 assert obj.from_addr[0] == obj.app_id
1725 assert obj.from_addr[1] == "[email protected]"
1726 assert obj.secure_mode == "ssl"
1727 # No entries in the reply_to
1728 assert not obj.reply_to
1729
1730 assert mock_smtp.call_count == 0
1731 assert mock_smtp_ssl.call_count == 0
1732 assert response.starttls.call_count == 0
1733 assert obj.notify("test") is True
1734 assert mock_smtp.call_count == 0
1735 assert mock_smtp_ssl.call_count == 1
1736 assert response.starttls.call_count == 0
1737 assert response.login.call_count == 1
1738 assert response.sendmail.call_count == 1
1739
1740 user, pw = response.login.call_args[0]
1741 assert pw == "password"
1742 assert user == "abc"
1743
1744 mock_smtp.reset_mock()
1745 mock_smtp_ssl.reset_mock()
1746 response.reset_mock()
1747
1748 #
1749 # Test Reply-To Email
1750 #
1751 results = email.NotifyEmail.parse_url(
1752 "mailtos://user:[email protected][email protected]"
1753 )
1754 obj = Apprise.instantiate(results, suppress_exceptions=False)
1755 assert isinstance(obj, email.NotifyEmail)
1756 # Verify our over-rides are in place
1757 assert obj.smtp_host == "example.com"
1758 assert obj.from_addr[0] == obj.app_id
1759 assert obj.from_addr[1] == "[email protected]"
1760 assert obj.secure_mode == "starttls"
1761 assert obj.url().startswith("mailtos://user:[email protected]")
1762 # Test that our template over-ride worked
1763 assert "reply=noreply%40example.com" in obj.url()
1764
1765 assert mock_smtp.call_count == 0
1766 assert mock_smtp_ssl.call_count == 0
1767 assert response.starttls.call_count == 0
1768 assert obj.notify("test") is True
1769 assert mock_smtp.call_count == 1
1770 assert mock_smtp_ssl.call_count == 0
1771 assert response.starttls.call_count == 1
1772 assert response.login.call_count == 1
1773 assert response.sendmail.call_count == 1
1774
1775 user, pw = response.login.call_args[0]
1776 assert pw == "pass"
1777 assert user == "user"
1778
1779 mock_smtp.reset_mock()
1780 mock_smtp_ssl.reset_mock()
1781 response.reset_mock()
1782
1783 #
1784 # Test Reply-To Email with Name Inline
1785 #
1786 results = email.NotifyEmail.parse_url(
1787 "mailtos://user:[email protected]?reply=Chris<[email protected]>"
1788 )
1789 obj = Apprise.instantiate(results, suppress_exceptions=False)
1790 assert isinstance(obj, email.NotifyEmail)
1791 # Verify our over-rides are in place
1792 assert obj.smtp_host == "example.com"
1793 assert obj.from_addr[0] == obj.app_id
1794 assert obj.from_addr[1] == "[email protected]"
1795 assert obj.secure_mode == "starttls"
1796 assert obj.url().startswith("mailtos://user:[email protected]")
1797 # Test that our template over-ride worked
1798 assert "reply=Chris%20%3Cnoreply%40example.ca%3E" in obj.url()
1799
1800 assert mock_smtp.call_count == 0
1801 assert mock_smtp_ssl.call_count == 0
1802 assert response.starttls.call_count == 0
1803 assert obj.notify("test") is True
1804 assert mock_smtp.call_count == 1
1805 assert mock_smtp_ssl.call_count == 0
1806 assert response.starttls.call_count == 1
1807 assert response.login.call_count == 1
1808 assert response.sendmail.call_count == 1
1809
1810 user, pw = response.login.call_args[0]
1811 assert pw == "pass"
1812 assert user == "user"
1813
1814 mock_smtp.reset_mock()
1815 mock_smtp_ssl.reset_mock()
1816 response.reset_mock()
1817
1818 # Fast Mail Handling
1819
1820 # Test variations of username required to be an email address
1821 # [email protected]; we also test an over-ride port on a template driven
1822 # mailto:// entry
1823 results = email.NotifyEmail.parse_url(
1824 "mailto://fastmail.com/[email protected]"
1825 "&[email protected]&pass=abc123"
1826 "&from=Concordium Explorer Bot<[email protected]>"
1827 )
1828 assert isinstance(results, dict)
1829 assert (
1830 results["from_addr"]
1831 == "Concordium Explorer Bot<[email protected]>"
1832 )
1833 assert results["user"] == "[email protected]"
1834 assert results["port"] is None
1835 assert results["host"] == "fastmail.com"
1836 assert results["password"] == "abc123"
1837 assert "[email protected]" in results["targets"]
1838
1839 obj = Apprise.instantiate(results, suppress_exceptions=False)
1840 assert isinstance(obj, email.NotifyEmail)
1841
1842 assert mock_smtp.call_count == 0
1843 assert mock_smtp_ssl.call_count == 0
1844 assert obj.notify("test") is True
1845 assert mock_smtp.call_count == 0
1846 assert mock_smtp_ssl.call_count == 1
1847 assert response.starttls.call_count == 0
1848 assert response.login.call_count == 1
1849 assert response.sendmail.call_count == 1
1850 # Store our Sent Arguments
1851 # Syntax is:
1852 # sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
1853 # [0] [1] [2]
1854 from_ = response.sendmail.call_args[0][0]
1855 to = response.sendmail.call_args[0][1]
1856 msg = response.sendmail.call_args[0][2]
1857 assert from_ == "[email protected]"
1858 assert isinstance(to, list)
1859 assert len(to) == 1
1860 assert to[0] == "[email protected]"
1861 assert msg.split("\n")[-3] == "test"
1862
1863 user, pw = response.login.call_args[0]
1864 assert pw == "abc123"
1865 assert user == "[email protected]"
1866
1867 mock_smtp.reset_mock()
1868 mock_smtp_ssl.reset_mock()
1869 response.reset_mock()
1870
1871 # Issue github.com/caronc/apprise/issue/1040
1872 # mailto://[email protected] \
1873 # &[email protected]&pass=password123
1874 #
1875 # should just have to be written like (to= omitted)
1876 # mailto://[email protected]&pass=password123
1877 #
1878 results = email.NotifyEmail.parse_url(
1879 "mailto://[email protected]&pass=password123"
1880 )
1881 assert isinstance(results, dict)
1882 assert results["user"] == "[email protected]"
1883 assert results["from_addr"] == ""
1884 assert results["port"] is None
1885 assert results["host"] == "fastmail.com"
1886 assert results["password"] == "password123"
1887 assert results["smtp_host"] == ""
1888
1889 obj = Apprise.instantiate(results, suppress_exceptions=False)
1890 assert isinstance(obj, email.NotifyEmail)
1891 # During instantiation, our variables get detected
1892 assert obj.smtp_host == "smtp.fastmail.com"
1893 assert obj.from_addr == ["Apprise", "[email protected]"]
1894 assert obj.host == "customdomain.com"
1895 # detected from
1896 assert (False, "[email protected]") in obj.targets
1897
1898 assert mock_smtp.call_count == 0
1899 assert mock_smtp_ssl.call_count == 0
1900 assert obj.notify("test") is True
1901 assert mock_smtp.call_count == 0
1902 assert mock_smtp_ssl.call_count == 1
1903 assert response.starttls.call_count == 0
1904 assert response.login.call_count == 1
1905 assert response.sendmail.call_count == 1
1906 # Store our Sent Arguments
1907 # Syntax is:
1908 # sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
1909 # [0] [1] [2]
1910 from_ = response.sendmail.call_args[0][0]
1911 to = response.sendmail.call_args[0][1]
1912 msg = response.sendmail.call_args[0][2]
1913 assert from_ == "[email protected]"
1914 assert isinstance(to, list)
1915 assert len(to) == 1
1916 assert to[0] == "[email protected]"
1917 assert msg.split("\n")[-3] == "test"
1918
1919 user, pw = response.login.call_args[0]
1920 assert pw == "password123"
1921 assert user == "[email protected]"
1922
1923 mock_smtp.reset_mock()
1924 mock_smtp_ssl.reset_mock()
1925 response.reset_mock()
1926
1927 # Similar test as above, just showing that we can over-ride the From=
1928 # with these custom URLs as well and not require a full email
1929 results = email.NotifyEmail.parse_url(
1930 "mailto://[email protected]"
1931 "&pass=password123&from=Custom"
1932 )
1933 assert isinstance(results, dict)
1934 assert results["user"] == "[email protected]"
1935 assert results["from_addr"] == "Custom"
1936 assert results["port"] is None
1937 assert results["host"] == "fastmail.com"
1938 assert results["password"] == "password123"
1939 assert results["smtp_host"] == ""
1940
1941 obj = Apprise.instantiate(results, suppress_exceptions=False)
1942 assert isinstance(obj, email.NotifyEmail)
1943 # During instantiation, our variables get detected
1944 assert obj.smtp_host == "smtp.fastmail.com"
1945 assert obj.from_addr == ["Custom", "[email protected]"]
1946 assert obj.host == "customdomain.com"
1947 # detected from
1948 assert (False, "[email protected]") in obj.targets
1949
1950 assert mock_smtp.call_count == 0
1951 assert mock_smtp_ssl.call_count == 0
1952 assert obj.notify("test") is True
1953 assert mock_smtp.call_count == 0
1954 assert mock_smtp_ssl.call_count == 1
1955 assert response.starttls.call_count == 0
1956 assert response.login.call_count == 1
1957 assert response.sendmail.call_count == 1
1958 # Store our Sent Arguments
1959 # Syntax is:
1960 # sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
1961 # [0] [1] [2]
1962 from_ = response.sendmail.call_args[0][0]
1963 to = response.sendmail.call_args[0][1]
1964 msg = response.sendmail.call_args[0][2]
1965 assert from_ == "[email protected]"
1966 assert isinstance(to, list)
1967 assert len(to) == 1
1968 assert to[0] == "[email protected]"
1969 assert msg.split("\n")[-3] == "test"
1970
1971 user, pw = response.login.call_args[0]
1972 assert pw == "password123"
1973 assert user == "[email protected]"
1974
1975 mock_smtp.reset_mock()
1976 mock_smtp_ssl.reset_mock()
1977 response.reset_mock()
1978
1979 # Issue github.com/caronc/apprise/issue/941
1980
1981 # mail domain = mail-domain.com
1982 # host domain = domain.subdomain.com
1983 # PASSWORD needs to be fetched since a user= was provided
1984 # - this is an edge case that is tested here
1985 results = email.NotifyEmail.parse_url(
1986 "mailtos://[email protected]:587?"
1987 "[email protected]&[email protected]"
1988 )
1989 assert isinstance(results, dict)
1990 # From_Addr could not be detected at this stage, but will be
1991 # handled during instantiation
1992 assert results["from_addr"] == ""
1993 assert results["user"] == "[email protected]"
1994 assert results["port"] == 587
1995 assert results["host"] == "domain.subdomain.com"
1996 assert results["password"] == "PASSWORD"
1997 assert "[email protected]" in results["targets"]
1998
1999 obj = Apprise.instantiate(results, suppress_exceptions=False)
2000 assert isinstance(obj, email.NotifyEmail)
2001
2002 # Not that our from_address takes on '[email protected]'
2003 assert obj.from_addr == ["Apprise", "[email protected]"]
2004
2005 assert mock_smtp.call_count == 0
2006 assert mock_smtp_ssl.call_count == 0
2007 assert response.starttls.call_count == 0
2008 assert obj.notify("test") is True
2009 assert mock_smtp.call_count == 1
2010 assert response.starttls.call_count == 1
2011 assert mock_smtp_ssl.call_count == 0
2012 assert response.login.call_count == 1
2013 assert response.sendmail.call_count == 1
2014 # Store our Sent Arguments
2015 # Syntax is:
2016 # sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
2017 # [0] [1] [2]
2018 from_ = response.sendmail.call_args[0][0]
2019 to = response.sendmail.call_args[0][1]
2020 msg = response.sendmail.call_args[0][2]
2021 assert from_ == "[email protected]"
2022 assert isinstance(to, list)
2023 assert len(to) == 1
2024 assert to[0] == "[email protected]"
2025 assert msg.split("\n")[-3] == "test"
2026
2027 user, pw = response.login.call_args[0]
2028 assert user == "[email protected]"
2029 assert pw == "PASSWORD"
2030
2031
2032 @mock.patch("smtplib.SMTP_SSL")
2033 @mock.patch("smtplib.SMTP")
2034 def test_plugin_email_plus_in_toemail(mock_smtp, mock_smtp_ssl):
2035 """NotifyEmail() support + in To Email address."""
2036
2037 response = mock.Mock()
2038 mock_smtp_ssl.return_value = response
2039 mock_smtp.return_value = response
2040
2041 # We want to test the case where a + is found in the To address; we want to
2042 # ensure that it is supported
2043 results = email.NotifyEmail.parse_url(
2044 "mailtos://user:[email protected]"
2045 "?to=Plus Support<[email protected]>"
2046 )
2047 assert isinstance(results, dict)
2048 assert results["user"] == "user"
2049 assert results["host"] == "gmail.com"
2050 assert results["password"] == "pass123"
2051 assert results["port"] is None
2052 assert "Plus Support<[email protected]>" in results["targets"]
2053
2054 obj = Apprise.instantiate(results, suppress_exceptions=False)
2055 assert isinstance(obj, email.NotifyEmail)
2056
2057 assert len(obj.targets) == 1
2058 assert ("Plus Support", "[email protected]") in obj.targets
2059 assert obj.smtp_host == "smtp.gmail.com"
2060 assert obj.from_addr == ["Apprise", "[email protected]"]
2061 assert obj.host == "gmail.com"
2062
2063 assert mock_smtp.call_count == 0
2064 assert mock_smtp_ssl.call_count == 0
2065 assert obj.notify("test") is True
2066 assert mock_smtp.call_count == 1
2067 assert mock_smtp_ssl.call_count == 0
2068 assert response.starttls.call_count == 1
2069 assert response.login.call_count == 1
2070 assert response.sendmail.call_count == 1
2071 # Store our Sent Arguments
2072 # Syntax is:
2073 # sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
2074 # [0] [1] [2]
2075 from_ = response.sendmail.call_args[0][0]
2076 to = response.sendmail.call_args[0][1]
2077 msg = response.sendmail.call_args[0][2]
2078 assert from_ == "[email protected]"
2079 assert isinstance(to, list)
2080 assert len(to) == 1
2081 assert to[0] == "[email protected]"
2082 assert msg.split("\n")[-3] == "test"
2083
2084 mock_smtp.reset_mock()
2085 mock_smtp_ssl.reset_mock()
2086 response.reset_mock()
2087
2088 #
2089 # Perform the same test where the To field jsut contains the + in the
2090 # address
2091 #
2092 results = email.NotifyEmail.parse_url(
2093 "mailtos://user:[email protected][email protected]"
2094 )
2095 assert isinstance(results, dict)
2096 assert results["user"] == "user"
2097 assert results["host"] == "gmail.com"
2098 assert results["password"] == "pass123"
2099 assert results["port"] is None
2100 assert "[email protected]" in results["targets"]
2101
2102 obj = Apprise.instantiate(results, suppress_exceptions=False)
2103 assert isinstance(obj, email.NotifyEmail)
2104
2105 assert len(obj.targets) == 1
2106 assert (False, "[email protected]") in obj.targets
2107
2108 assert mock_smtp.call_count == 0
2109 assert mock_smtp_ssl.call_count == 0
2110 assert obj.notify("test") is True
2111 assert mock_smtp.call_count == 1
2112 assert mock_smtp_ssl.call_count == 0
2113 assert response.starttls.call_count == 1
2114 assert response.login.call_count == 1
2115 assert response.sendmail.call_count == 1
2116 # Store our Sent Arguments
2117 # Syntax is:
2118 # sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
2119 # [0] [1] [2]
2120 from_ = response.sendmail.call_args[0][0]
2121 to = response.sendmail.call_args[0][1]
2122 msg = response.sendmail.call_args[0][2]
2123 assert from_ == "[email protected]"
2124 assert isinstance(to, list)
2125 assert len(to) == 1
2126 assert to[0] == "[email protected]"
2127 assert msg.split("\n")[-3] == "test"
2128
2129 mock_smtp.reset_mock()
2130 mock_smtp_ssl.reset_mock()
2131 response.reset_mock()
2132
2133 #
2134 # Perform the same test where the To field is in the URL itself
2135 #
2136 results = email.NotifyEmail.parse_url(
2137 "mailtos://user:[email protected]/[email protected]"
2138 )
2139 assert isinstance(results, dict)
2140 assert results["user"] == "user"
2141 assert results["host"] == "gmail.com"
2142 assert results["password"] == "pass123"
2143 assert results["port"] is None
2144 assert "[email protected]" in results["targets"]
2145
2146 obj = Apprise.instantiate(results, suppress_exceptions=False)
2147 assert isinstance(obj, email.NotifyEmail)
2148
2149 assert len(obj.targets) == 1
2150 assert (False, "[email protected]") in obj.targets
2151
2152 assert mock_smtp.call_count == 0
2153 assert mock_smtp_ssl.call_count == 0
2154 assert obj.notify("test") is True
2155 assert mock_smtp.call_count == 1
2156 assert mock_smtp_ssl.call_count == 0
2157 assert response.starttls.call_count == 1
2158 assert response.login.call_count == 1
2159 assert response.sendmail.call_count == 1
2160 # Store our Sent Arguments
2161 # Syntax is:
2162 # sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
2163 # [0] [1] [2]
2164 from_ = response.sendmail.call_args[0][0]
2165 to = response.sendmail.call_args[0][1]
2166 msg = response.sendmail.call_args[0][2]
2167 assert from_ == "[email protected]"
2168 assert isinstance(to, list)
2169 assert len(to) == 1
2170 assert to[0] == "[email protected]"
2171 assert msg.split("\n")[-3] == "test"
2172
2173
2174 @mock.patch("smtplib.SMTP_SSL")
2175 @mock.patch("smtplib.SMTP")
2176 def test_plugin_email_formatting_990(mock_smtp, mock_smtp_ssl):
2177 """
2178 NotifyEmail() GitHub Issue 990
2179 https://github.com/caronc/apprise/issues/990
2180 Email formatting not working correctly
2181
2182 """
2183
2184 response = mock.Mock()
2185 mock_smtp_ssl.return_value = response
2186 mock_smtp.return_value = response
2187
2188 results = email.NotifyEmail.parse_url(
2189 "mailtos://mydomain.com?smtp=mail.local.mydomain.com"
2190 "&[email protected]&pass=mypassword"
2191 "&[email protected]&[email protected]&mode=ssl&port=465"
2192 )
2193
2194 assert isinstance(results, dict)
2195 assert results["user"] == "[email protected]"
2196 assert results["host"] == "mydomain.com"
2197 assert results["smtp_host"] == "mail.local.mydomain.com"
2198 assert results["password"] == "mypassword"
2199 assert results["secure_mode"] == "ssl"
2200 assert results["port"] == "465"
2201 assert "[email protected]" in results["targets"]
2202
2203 obj = Apprise.instantiate(results, suppress_exceptions=False)
2204 assert isinstance(obj, email.NotifyEmail)
2205
2206 assert len(obj.targets) == 1
2207 assert (False, "[email protected]") in obj.targets
2208
2209
2210 def test_plugin_email_variables_1087():
2211 """
2212 NotifyEmail() GitHub Issue 1087
2213 https://github.com/caronc/apprise/issues/1087
2214 Email variables reported not working correctly
2215
2216 """
2217
2218 # Valid Configuration
2219 result, _ = ConfigBase.config_parse(
2220 cleandoc("""
2221 #
2222 # Test Email Parsing
2223 #
2224 urls:
2225 - mailtos://alt.lan/:
2226 - user: [email protected]
2227 pass: xxxxXXXxxx
2228 smtp: smtp.alt.lan
2229 to: [email protected]
2230 """),
2231 asset=AppriseAsset(),
2232 )
2233
2234 assert isinstance(result, list)
2235 assert len(result) == 1
2236
2237 email_ = result[0]
2238 assert email_.from_addr == ["Apprise", "[email protected]"]
2239 assert email_.user == "[email protected]"
2240 assert email_.smtp_host == "smtp.alt.lan"
2241 assert email_.targets == [(False, "[email protected]")]
2242 assert email_.password == "xxxxXXXxxx"
2243
2244 # Valid Configuration
2245 result, _ = ConfigBase.config_parse(
2246 cleandoc("""
2247 #
2248 # Test Email Parsing where YAML tokens over-ride qsd
2249 #
2250 urls:
2251 - mailtos://alt.lan/?pass=abcd&[email protected]:
2252 - user: [email protected]
2253 pass: xxxxXXXxxx
2254 smtp: smtp.alt.lan
2255 to: [email protected]
2256 """),
2257 asset=AppriseAsset(),
2258 )
2259
2260 assert isinstance(result, list)
2261 assert len(result) == 1
2262
2263 # YAML child tokens are higher priority than URL query-string
2264 # parameters -- testuser and xxxxXXXxxx win over joe and abcd.
2265 email_ = result[0]
2266 assert email_.from_addr == ["Apprise", "[email protected]"]
2267 assert email_.user == "[email protected]"
2268 assert email_.smtp_host == "smtp.alt.lan"
2269 assert email_.targets == [(False, "[email protected]")]
2270 assert email_.password == "xxxxXXXxxx"
2271
2272
2273 @mock.patch("smtplib.SMTP_SSL")
2274 @mock.patch("smtplib.SMTP")
2275 def test_plugin_email_to_handling_1356(mock_smtp, mock_smtp_ssl):
2276 """
2277 NotifyEmail() GitHub Issue 1356
2278 https://github.com/caronc/apprise/issues/1356
2279 Email not correctly preparing the `to:`
2280
2281 """
2282
2283 response = mock.Mock()
2284 mock_smtp_ssl.return_value = response
2285 mock_smtp.return_value = response
2286
2287 results = email.NotifyEmail.parse_url(
2288 "mailtos://smtp-relay.gmail.com?"
2289 "[email protected]&[email protected]"
2290 )
2291
2292 assert isinstance(results, dict)
2293 assert results["user"] is None
2294 assert results["password"] is None
2295 assert results["host"] == "smtp-relay.gmail.com"
2296 assert results["port"] is None
2297 assert results["from_addr"] == "[email protected]"
2298 assert results["smtp_host"] == ""
2299 assert "[email protected]" in results["targets"]
2300
2301 obj = Apprise.instantiate(results, suppress_exceptions=False)
2302 assert isinstance(obj, email.NotifyEmail)
2303
2304 assert len(obj.targets) == 1
2305 assert (False, "[email protected]") in obj.targets
2306
2307 assert obj.smtp_host == "smtp-relay.gmail.com"
2308 assert obj.from_addr == (False, "[email protected]")
2309
2310 assert mock_smtp.call_count == 0
2311 assert mock_smtp_ssl.call_count == 0
2312 assert obj.notify("body", "title") is True
2313
2314 assert mock_smtp.call_count == 1
2315 assert mock_smtp_ssl.call_count == 0
2316 assert response.starttls.call_count == 1
2317 # No login occurs as no user/pass was provided
2318 assert response.login.call_count == 0
2319 assert response.sendmail.call_count == 1
2320
2321 # Store our Sent Arguments
2322 # Syntax is:
2323 # sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
2324 # [0] [1] [2]
2325 from_ = response.sendmail.call_args[0][0]
2326 to = response.sendmail.call_args[0][1]
2327 msg = response.sendmail.call_args[0][2]
2328 assert from_ == "[email protected]"
2329 assert isinstance(to, list)
2330 assert len(to) == 1
2331 assert to[0] == "[email protected]"
2332 assert msg.split("\n")[-3] == "body"
2333
2334
2335 @mock.patch("smtplib.SMTP_SSL")
2336 @mock.patch("smtplib.SMTP")
2337 def test_plugin_email_variables_1334(mock_smtp, mock_smtp_ssl):
2338 """
2339 NotifyEmail() GitHub Issue 1334
2340 https://github.com/caronc/apprise/issues/1334
2341 Localhost & Local Domain default user
2342
2343 """
2344
2345 response = mock.Mock()
2346 mock_smtp_ssl.return_value = response
2347 mock_smtp.return_value = response
2348
2349 results = email.NotifyEmail.parse_url("mailto://localhost")
2350
2351 assert isinstance(results, dict)
2352 assert results["user"] is None
2353 assert results["password"] is None
2354 assert results["host"] == "localhost"
2355 assert results["port"] is None
2356 assert results["from_addr"] == ""
2357 assert results["smtp_host"] == ""
2358 assert results["targets"] == []
2359
2360 obj = Apprise.instantiate(results, suppress_exceptions=False)
2361 assert isinstance(obj, email.NotifyEmail)
2362
2363 assert len(obj.targets) == 1
2364 assert (False, "root@localhost") in obj.targets
2365
2366 assert obj.smtp_host == "localhost"
2367 assert obj.secure is False
2368 assert obj.from_addr == [False, "root@localhost"]
2369
2370 assert mock_smtp.call_count == 0
2371 assert mock_smtp_ssl.call_count == 0
2372 assert obj.notify("body", "title") is True
2373
2374 assert mock_smtp.call_count == 1
2375 assert mock_smtp_ssl.call_count == 0
2376 assert response.starttls.call_count == 0
2377 # No login occurs as no user/pass was provided
2378 assert response.login.call_count == 0
2379 assert response.sendmail.call_count == 1
2380
2381 #
2382 # Again, but a different variation of the localhost domain
2383 #
2384 mock_smtp.reset_mock()
2385 mock_smtp_ssl.reset_mock()
2386 response.reset_mock()
2387
2388 results = email.NotifyEmail.parse_url(
2389 "mailtos://[email protected]"
2390 )
2391
2392 assert isinstance(results, dict)
2393 assert results["user"] == "user"
2394 assert results["password"] is None
2395 assert results["host"] == "localhost.localdomain"
2396 assert results["port"] is None
2397 assert results["from_addr"] == ""
2398 assert results["smtp_host"] == ""
2399 assert results["targets"] == []
2400
2401 obj = Apprise.instantiate(results, suppress_exceptions=False)
2402 assert isinstance(obj, email.NotifyEmail)
2403
2404 assert len(obj.targets) == 1
2405 assert (False, "[email protected]") in obj.targets
2406
2407 assert obj.smtp_host == "localhost.localdomain"
2408 assert obj.secure is True
2409 assert obj.from_addr == ["Apprise", "[email protected]"]
2410
2411 assert mock_smtp.call_count == 0
2412 assert mock_smtp_ssl.call_count == 0
2413 assert obj.notify("body", "title") is True
2414
2415 assert mock_smtp.call_count == 1
2416 assert mock_smtp_ssl.call_count == 0
2417 assert response.starttls.call_count == 1
2418 # No login occurs as no user/pass was provided
2419 assert response.login.call_count == 0
2420 assert response.sendmail.call_count == 1
2421
2422
2423 @mock.patch("smtplib.SMTP_SSL")
2424 @mock.patch("smtplib.SMTP")
2425 def test_plugin_host_detection_from_source_email(mock_smtp, mock_smtp_ssl):
2426 """NotifyEmail() Discord Issue reporting that the following did not work:
2427
2428 mailtos://?smtp=mobile.charter.net&pass=password&[email protected]
2429 """
2430
2431 response = mock.Mock()
2432 mock_smtp_ssl.return_value = response
2433 mock_smtp.return_value = response
2434
2435 results = email.NotifyEmail.parse_url(
2436 "mailtos://spectrum.net?smtp=mobile.charter.net"
2437 "&pass=password&[email protected]"
2438 )
2439
2440 assert isinstance(results, dict)
2441 assert results["user"] == "[email protected]"
2442 assert results["host"] == "spectrum.net"
2443 assert results["smtp_host"] == "mobile.charter.net"
2444 assert results["password"] == "password"
2445
2446 obj = Apprise.instantiate(results, suppress_exceptions=False)
2447 assert isinstance(obj, email.NotifyEmail) is True
2448
2449 assert len(obj.targets) == 1
2450 assert (False, "[email protected]") in obj.targets
2451 assert obj.from_addr[0] == obj.app_id
2452 assert obj.from_addr[1] == "[email protected]"
2453 assert obj.password == "password"
2454 assert obj.user == "[email protected]"
2455 assert obj.secure is True
2456 assert obj.port == 587
2457 assert obj.smtp_host == "mobile.charter.net"
2458
2459 assert mock_smtp.call_count == 0
2460 assert mock_smtp_ssl.call_count == 0
2461 assert obj.notify("body", "title") is True
2462
2463 assert mock_smtp.call_count == 1
2464 assert mock_smtp_ssl.call_count == 0
2465 assert response.starttls.call_count == 1
2466 assert response.login.call_count == 1
2467 assert response.sendmail.call_count == 1
2468 # Store our Sent Arguments
2469 # Syntax is:
2470 # sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
2471 # [0] [1] [2]
2472 from_ = response.sendmail.call_args[0][0]
2473 to = response.sendmail.call_args[0][1]
2474 msg = response.sendmail.call_args[0][2]
2475 assert from_ == "[email protected]"
2476 assert isinstance(to, list)
2477 assert len(to) == 1
2478 assert to[0] == "[email protected]"
2479 assert msg.split("\n")[-3] == "body"
2480
2481 #
2482 # Now let's do a shortened version of the same URL where the host isn't
2483 # specified but is parseable from he user login
2484 #
2485 mock_smtp.reset_mock()
2486 mock_smtp_ssl.reset_mock()
2487 response.reset_mock()
2488
2489 results = email.NotifyEmail.parse_url(
2490 "mailtos://?smtp=mobile.charter.net"
2491 "&pass=password&[email protected]"
2492 )
2493
2494 assert isinstance(results, dict)
2495 assert results["user"] == "[email protected]"
2496 assert results["host"] == "" # No hostname defined; it's detected later
2497 assert results["smtp_host"] == "mobile.charter.net"
2498 assert results["password"] == "password"
2499
2500 obj = Apprise.instantiate(results, suppress_exceptions=False)
2501 assert isinstance(obj, email.NotifyEmail) is True
2502
2503 assert len(obj.targets) == 1
2504 assert (False, "[email protected]") in obj.targets
2505 assert obj.from_addr[0] == obj.app_id
2506 assert obj.from_addr[1] == "[email protected]"
2507 assert obj.password == "password"
2508 assert obj.user == "[email protected]"
2509 assert obj.secure is True
2510 assert obj.port == 587
2511 assert obj.smtp_host == "mobile.charter.net"
2512
2513 assert mock_smtp.call_count == 0
2514 assert mock_smtp_ssl.call_count == 0
2515 assert obj.notify("body", "title") is True
2516
2517 assert mock_smtp.call_count == 1
2518 assert mock_smtp_ssl.call_count == 0
2519 assert response.starttls.call_count == 1
2520 assert response.login.call_count == 1
2521 assert response.sendmail.call_count == 1
2522 # Store our Sent Arguments
2523 # Syntax is:
2524 # sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
2525 # [0] [1] [2]
2526 from_ = response.sendmail.call_args[0][0]
2527 to = response.sendmail.call_args[0][1]
2528 msg = response.sendmail.call_args[0][2]
2529 assert from_ == "[email protected]"
2530 assert isinstance(to, list)
2531 assert len(to) == 1
2532 assert to[0] == "[email protected]"
2533 assert msg.split("\n")[-3] == "body"
2534
2535 #
2536 # Now let's do a shortened version of the same URL where the host isn't
2537 # specified but is parseable from he user login
2538 #
2539 mock_smtp.reset_mock()
2540 mock_smtp_ssl.reset_mock()
2541 response.reset_mock()
2542
2543 results = email.NotifyEmail.parse_url(
2544 "mailtos://?smtp=mobile.charter.net"
2545 "&pass=password&user=userid-without-domain"
2546 )
2547
2548 assert isinstance(results, dict)
2549 assert results["user"] == "userid-without-domain"
2550 assert results["host"] == "" # No hostname defined
2551 assert results["smtp_host"] == "mobile.charter.net"
2552 assert results["password"] == "password"
2553
2554 with pytest.raises(TypeError):
2555 # We will fail
2556 Apprise.instantiate(results, suppress_exceptions=False)
2557
2558 #
2559 # Now support target emails in place of the hostname
2560 #
2561
2562 mock_smtp.reset_mock()
2563 mock_smtp_ssl.reset_mock()
2564 response.reset_mock()
2565
2566 results = email.NotifyEmail.parse_url(
2567 "mailtos://John Doe<john%40yahoo.ca>?smtp=mobile.charter.net"
2568 "&pass=password&[email protected]"
2569 )
2570
2571 assert isinstance(results, dict)
2572 assert results["user"] == "[email protected]"
2573 assert results["host"] == "" # No hostname defined; it's detected later
2574 assert results["smtp_host"] == "mobile.charter.net"
2575 assert results["password"] == "password"
2576
2577 obj = Apprise.instantiate(results, suppress_exceptions=False)
2578 assert isinstance(obj, email.NotifyEmail) is True
2579
2580 assert len(obj.targets) == 1
2581 assert ("John Doe", "[email protected]") in obj.targets
2582 assert obj.from_addr[0] == obj.app_id
2583 assert obj.from_addr[1] == "[email protected]"
2584 assert obj.password == "password"
2585 assert obj.user == "[email protected]"
2586 assert obj.secure is True
2587 assert obj.port == 587
2588 assert obj.smtp_host == "mobile.charter.net"
2589
2590 assert mock_smtp.call_count == 0
2591 assert mock_smtp_ssl.call_count == 0
2592 assert obj.notify("body", "title") is True
2593
2594 assert mock_smtp.call_count == 1
2595 assert mock_smtp_ssl.call_count == 0
2596 assert response.starttls.call_count == 1
2597 assert response.login.call_count == 1
2598 assert response.sendmail.call_count == 1
2599 # Store our Sent Arguments
2600 # Syntax is:
2601 # sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
2602 # [0] [1] [2]
2603 from_ = response.sendmail.call_args[0][0]
2604 to = response.sendmail.call_args[0][1]
2605 msg = response.sendmail.call_args[0][2]
2606 assert from_ == "[email protected]"
2607 assert isinstance(to, list)
2608 assert len(to) == 1
2609 assert to[0] == "[email protected]"
2610 assert msg.split("\n")[-3] == "body"
2611
2612
2613 @mock.patch("smtplib.SMTP_SSL")
2614 @mock.patch("smtplib.SMTP")
2615 def test_plugin_email_by_ipaddr_1113(mock_smtp, mock_smtp_ssl):
2616 """
2617 NotifyEmail() GitHub Issue 1113
2618 https://github.com/caronc/apprise/issues/1113
2619 Email with ip addresses not working
2620
2621 """
2622
2623 response = mock.Mock()
2624 mock_smtp_ssl.return_value = response
2625 mock_smtp.return_value = response
2626
2627 results = email.NotifyEmail.parse_url(
2628 "mailto://10.0.0.195:25/[email protected]&[email protected]"
2629 )
2630
2631 assert isinstance(results, dict)
2632 assert results["user"] is None
2633 assert results["password"] is None
2634 assert results["host"] == "10.0.0.195"
2635 assert results["from_addr"] == "[email protected]"
2636 assert isinstance(results["targets"], list)
2637 assert len(results["targets"]) == 1
2638 assert results["targets"][0] == "[email protected]"
2639 assert results["port"] == 25
2640
2641 email_ = Apprise.instantiate(results, suppress_exceptions=False)
2642 assert isinstance(email_, email.NotifyEmail) is True
2643
2644 assert len(email_.targets) == 1
2645 assert (False, "[email protected]") in email_.targets
2646
2647 assert email_.from_addr == (False, "[email protected]")
2648 assert email_.user is None
2649 assert email_.password is None
2650 assert email_.smtp_host == "10.0.0.195"
2651 assert email_.port == 25
2652 assert email_.targets == [(False, "[email protected]")]
2653
2654
2655 @pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy")
2656 @mock.patch("smtplib.SMTP_SSL")
2657 @mock.patch("smtplib.SMTP")
2658 def test_plugin_email_pgp(mock_smtp, mock_smtpssl, tmpdir):
2659 """NotifyEmail() PGP Tests."""
2660 # Our mock of our socket action
2661 mock_socket = mock.Mock()
2662 mock_socket.starttls.return_value = True
2663 mock_socket.login.return_value = True
2664
2665 # Create a mock SMTP Object
2666 mock_smtp.return_value = mock_socket
2667 mock_smtpssl.return_value = mock_socket
2668
2669 assert utils.pgp.PGP_SUPPORT is True
2670 utils.pgp.PGP_SUPPORT = False
2671 # Forces to run through section of code that produces a warning there is
2672 # no PGP
2673 obj = Apprise.instantiate("mailto://user:[email protected]?pgp=encrypt")
2674 # No PGP Support and set enabled
2675 assert obj.notify("test body") is False
2676
2677 # Return the PGP status for remaining checks
2678 utils.pgp.PGP_SUPPORT = True
2679
2680 # Initialize our email (no from name)
2681 obj = Apprise.instantiate("mailto://user2:[email protected]?pgp=encrypt")
2682
2683 # Nothing to lookup
2684 assert obj.pgp.public_keyfile() is None
2685 assert obj.pgp.public_key() is None
2686 assert obj.pgp.encrypt("message") is False
2687 # Keys can not be generated in memory mode
2688 assert obj.pgp.keygen() is False
2689
2690 # The reason... no location to store data
2691 assert obj.store.mode == PersistentStoreMode.MEMORY
2692
2693 tmpdir0 = tmpdir.mkdir("tmp00")
2694 asset = AppriseAsset(
2695 storage_mode=PersistentStoreMode.FLUSH,
2696 storage_path=str(tmpdir0),
2697 )
2698
2699 # Prepare PGP
2700 obj = Apprise.instantiate(
2701 "mailto://pgp:[email protected]?pgp=yes", asset=asset
2702 )
2703 assert obj.store.mode == PersistentStoreMode.FLUSH
2704
2705 # Still no public key
2706 assert obj.pgp.public_key(autogen=False) is None
2707 assert obj.pgp.keygen() is True
2708 # Now we'll have a public key
2709 assert isinstance(obj.pgp.public_keyfile(), str)
2710
2711 # Generate warning by second call
2712 assert obj.pgp.keygen() is True
2713
2714 # Remove newly generated files
2715 os.unlink(os.path.join(obj.store.path, "pgp-pub.asc"))
2716 os.unlink(os.path.join(obj.store.path, "pgp-prv.asc"))
2717 obj = Apprise.instantiate(
2718 "mailto://pgp:[email protected]?pgp=yes", asset=asset
2719 )
2720 assert obj.store.mode == PersistentStoreMode.FLUSH
2721 assert obj.pgp.keygen() is True
2722
2723 # Prepare PGP while providing it a key
2724 obj = Apprise.instantiate(
2725 "mailto://pgp:[email protected]?pgp=yes&"
2726 f"pgppub={obj.pgp.public_keyfile()}",
2727 asset=asset,
2728 )
2729
2730 # keyfile Defined
2731 assert obj.pgp.pub_keyfile is not None
2732
2733 # Get our key
2734 key = obj.pgp.public_key()
2735
2736 # In this circumstance we can not generate a new key as the one provided
2737 # is immutable
2738 assert obj.pgp.keygen() is False
2739
2740 # Our key is the same
2741 assert key is obj.pgp.public_key()
2742
2743 tmpdir0 = tmpdir.mkdir("tmp00a")
2744 asset0 = AppriseAsset(
2745 storage_mode=PersistentStoreMode.FLUSH,
2746 storage_path=str(tmpdir0),
2747 )
2748
2749 # Prepare Invalid PGP Key
2750 obj = Apprise.instantiate(
2751 "mailto://pgpX:[email protected]?pgp=yes", asset=asset0
2752 )
2753
2754 # No keyfiles
2755 assert obj.pgp.pub_keyfile is None
2756
2757 # Generate our keys
2758 assert obj.pgp.keygen() is True
2759
2760 # Second call uses cache
2761 assert obj.pgp.keygen() is True
2762
2763 # We will find our key
2764 key = obj.pgp.public_key()
2765 assert key is not None
2766
2767 # Utilize force parameter
2768 assert obj.pgp.keygen(force=True) is True
2769
2770 # Our key is new
2771 assert key != obj.pgp.public_key()
2772 assert obj.pgp.public_key() is not None
2773
2774 # Prepare Invalid PGP Key
2775 obj = Apprise.instantiate(
2776 "mailto://pgp:[email protected]?pgp=yes&pgppub=invalid", asset=asset
2777 )
2778
2779 # Returns false
2780 assert obj.pgp.pub_keyfile is False
2781 assert obj.pgp.public_keyfile() is False
2782
2783 tmpdir2 = tmpdir.mkdir("tmp02")
2784 asset = AppriseAsset(
2785 storage_mode=PersistentStoreMode.FLUSH,
2786 storage_path=str(tmpdir2),
2787 )
2788 obj = Apprise.instantiate(
2789 "mailto://chris:[email protected]?pgp=yes", asset=asset
2790 )
2791
2792 assert obj.store.mode == PersistentStoreMode.FLUSH
2793 assert obj.pgp.keygen() is True
2794
2795 # Second call uses cache
2796 assert obj.pgp.keygen() is True
2797
2798 # We will find our key
2799 assert obj.pgp.public_key() is not None
2800
2801 # We do this again but even when we do a requisition for a public key
2802 # it will generate a new pair or keys for us once it detects we don't
2803 # have any
2804 tmpdir3 = tmpdir.mkdir("tmp03")
2805 asset = AppriseAsset(
2806 storage_mode=PersistentStoreMode.FLUSH,
2807 storage_path=str(tmpdir3),
2808 )
2809 obj = Apprise.instantiate(
2810 "mailto://chris:[email protected]/[email protected]?pgp=yes", asset=asset
2811 )
2812
2813 assert obj.store.mode == PersistentStoreMode.FLUSH
2814
2815 # We'll have a public key object to encrypt with
2816 assert obj.pgp.public_key() is not None
2817
2818 encrypted = obj.pgp.encrypt("hello world")
2819 assert encrypted.startswith("-----BEGIN PGP MESSAGE-----")
2820 assert encrypted.rstrip().endswith("-----END PGP MESSAGE-----")
2821
2822 dir_content = os.listdir(obj.store.path)
2823 assert "chris-pub.asc" in dir_content
2824 assert "chris-prv.asc" in dir_content
2825
2826 assert obj.pgp.public_keyfile().endswith("chris-pub.asc")
2827
2828 assert obj.notify("test body") is True
2829
2830 # The private key is not needed for sending the encrypted messages
2831 os.unlink(os.path.join(obj.store.path, "chris-prv.asc"))
2832 os.rename(
2833 os.path.join(obj.store.path, "chris-pub.asc"),
2834 os.path.join(obj.store.path, "[email protected]"),
2835 )
2836
2837 assert obj.pgp.public_keyfile() is None
2838 assert obj.pgp.public_keyfile("[email protected]") is None
2839 assert obj.pgp.public_keyfile("[email protected]").endswith(
2840 "[email protected]"
2841 )
2842
2843 assert obj.pgp.public_keyfile("[email protected]").endswith(
2844 "[email protected]"
2845 )
2846 assert obj.pgp.public_keyfile("[email protected]").endswith(
2847 "[email protected]"
2848 )
2849 assert obj.pgp.public_keyfile("unknown") is None
2850
2851 shutil.copyfile(
2852 os.path.join(obj.store.path, "[email protected]"),
2853 os.path.join(obj.store.path, "user-pub.asc"),
2854 )
2855
2856 assert obj.pgp.public_keyfile("[email protected]").endswith(
2857 "[email protected]"
2858 )
2859 assert obj.pgp.public_keyfile("[email protected]").endswith(
2860 "[email protected]"
2861 )
2862
2863 # Remove file
2864 os.unlink(os.path.join(obj.store.path, "[email protected]"))
2865 assert obj.pgp.public_keyfile("[email protected]").endswith("user-pub.asc")
2866 shutil.copyfile(
2867 os.path.join(obj.store.path, "user-pub.asc"),
2868 os.path.join(obj.store.path, "chris-pub.asc"),
2869 )
2870 # user-pub.asc still trumps still trumps
2871 assert obj.pgp.public_keyfile("[email protected]").endswith("user-pub.asc")
2872 shutil.copyfile(
2873 os.path.join(obj.store.path, "chris-pub.asc"),
2874 os.path.join(obj.store.path, "[email protected]"),
2875 )
2876 # user-pub still trumps
2877 assert obj.pgp.public_keyfile("[email protected]").endswith("user-pub.asc")
2878 assert obj.pgp.public_keyfile("[email protected]").endswith(
2879 "[email protected]"
2880 )
2881
2882 # remove this file
2883 os.unlink(os.path.join(obj.store.path, "user-pub.asc"))
2884
2885 # now we fall back to basic/default configuration
2886 assert obj.pgp.public_keyfile("[email protected]").endswith(
2887 "[email protected]"
2888 )
2889 os.unlink(os.path.join(obj.store.path, "[email protected]"))
2890 assert obj.pgp.public_keyfile("[email protected]").endswith("chris-pub.asc")
2891
2892 # Testing again
2893 tmpdir4 = tmpdir.mkdir("tmp04")
2894 asset = AppriseAsset(
2895 storage_mode=PersistentStoreMode.FLUSH,
2896 storage_path=str(tmpdir4),
2897 )
2898 obj = Apprise.instantiate(
2899 "mailto://chris:[email protected]/[email protected]?pgp=yes", asset=asset
2900 )
2901
2902 with mock.patch("builtins.open", side_effect=FileNotFoundError):
2903 # can't open key
2904 assert obj.pgp.public_key() is None
2905
2906 with mock.patch("builtins.open", side_effect=OSError):
2907 # can't open key
2908 assert obj.pgp.public_key() is None
2909 # Test unlink
2910 with mock.patch("os.unlink", side_effect=OSError):
2911 assert obj.pgp.public_key() is None
2912
2913 # Key Generation will fail
2914 assert obj.pgp.keygen() is False
2915
2916 with mock.patch("pgpy.PGPKey.new", side_effect=NameError):
2917 # Can't Generate keys
2918 assert obj.pgp.keygen() is False
2919 # can't open key
2920 assert obj.pgp.public_key() is None
2921
2922 with mock.patch("pgpy.PGPKey.from_blob", side_effect=FileNotFoundError):
2923 # can't open key
2924 assert obj.pgp.public_key() is None
2925
2926 with mock.patch("pgpy.PGPKey.from_blob", side_effect=OSError):
2927 # can't open key
2928 assert obj.pgp.public_key() is None
2929
2930 # Can't encrypt key
2931 with mock.patch("pgpy.PGPKey.from_blob", side_effect=NameError):
2932 assert obj.pgp.public_key() is None
2933
2934 with mock.patch("pgpy.PGPMessage.new", side_effect=NameError):
2935 assert obj.pgp.encrypt("message") is None
2936 # Attempts to encrypt a message
2937 assert obj.notify("test-encrypt") is False
2938
2939 # Create new keys
2940 assert obj.pgp.keygen() is True
2941 with (
2942 mock.patch("os.path.isfile", return_value=False),
2943 mock.patch("builtins.open", side_effect=OSError),
2944 mock.patch("os.unlink", return_value=None),
2945 ):
2946 assert obj.pgp.keygen() is False
2947
2948 # Testing again
2949 tmpdir5 = tmpdir.mkdir("tmp05")
2950 asset = AppriseAsset(
2951 storage_mode=PersistentStoreMode.FLUSH,
2952 storage_path=str(tmpdir5),
2953 )
2954 obj = Apprise.instantiate(
2955 "mailto://chris:[email protected]/[email protected]?pgp=yes", asset=asset
2956 )
2957
2958 # Catch edge case where we just can't generate the the key
2959 with (
2960 mock.patch(
2961 "os.path.isfile",
2962 side_effect=(
2963 # 5x False to skip through pgp.public_keyfile()
2964 False,
2965 False,
2966 False,
2967 False,
2968 False,
2969 False,
2970 # 1x True to pass pgp.keygen()
2971 True,
2972 # 5x False to skip through pgp.public_keyfile() second call
2973 False,
2974 False,
2975 False,
2976 False,
2977 False,
2978 False,
2979 ),
2980 ),
2981 mock.patch("pgpy.PGPKey.from_blob", side_effect=FileNotFoundError),
2982 ):
2983 assert obj.pgp.public_key() is None
2984
2985 # Corrupt Data
2986 tmpdir6 = tmpdir.mkdir("tmp06")
2987 asset = AppriseAsset(
2988 storage_mode=PersistentStoreMode.FLUSH,
2989 storage_path=str(tmpdir6),
2990 )
2991 obj = Apprise.instantiate(
2992 "mailto://chris:[email protected]/[email protected]?pgp=yes", asset=asset
2993 )
2994
2995 shutil.copyfile(
2996 os.path.join(TEST_VAR_DIR, "pgp", "corrupt-pub.asc"),
2997 os.path.join(obj.store.path, "chris-pub.asc"),
2998 )
2999
3000 # Key is corrupted
3001 assert obj.notify("test") is False
3002
3003 shutil.copyfile(
3004 os.path.join(TEST_VAR_DIR, "apprise-test.jpeg"),
3005 os.path.join(obj.store.path, "chris-pub.asc"),
3006 )
3007
3008 # Key is a binary image; definitely not a valid key
3009 assert obj.notify("test") is False
3010
3011
3012 @mock.patch("smtplib.SMTP_SSL")
3013 @mock.patch("smtplib.SMTP")
3014 def test_plugin_email_pgp_mode_param(mock_smtp, mock_smtpssl):
3015 """NotifyEmail() pgp_mode parameter and backward-compat use_pgp."""
3016
3017 mock_socket = mock.Mock()
3018 mock_socket.starttls.return_value = True
3019 mock_socket.login.return_value = True
3020 mock_smtp.return_value = mock_socket
3021 mock_smtpssl.return_value = mock_socket
3022
3023 # pgp= absent -> pgp_mode defaults to 'no'
3024 obj = Apprise.instantiate("mailto://user:[email protected]")
3025 assert obj is not None
3026 assert obj.pgp_mode == "no"
3027 assert obj.use_wkd is False
3028
3029 # pgp=encrypt -> pgp_mode = 'encrypt'
3030 obj = Apprise.instantiate("mailto://user:[email protected]?pgp=encrypt")
3031 assert obj.pgp_mode == "encrypt"
3032
3033 # pgp=e (prefix shorthand) -> pgp_mode = 'encrypt'
3034 obj = Apprise.instantiate("mailto://user:[email protected]?pgp=e")
3035 assert obj.pgp_mode == "encrypt"
3036
3037 # pgp=none -> no mode match; falls to default 'no' (backward compat)
3038 obj = Apprise.instantiate("mailto://user:[email protected]?pgp=none")
3039 assert obj.pgp_mode == "no"
3040
3041 # pgp=n -> prefix matches 'no'
3042 obj = Apprise.instantiate("mailto://user:[email protected]?pgp=n")
3043 assert obj.pgp_mode == "no"
3044
3045 # pgp=no -> direct mode match; canonical URL form
3046 obj = Apprise.instantiate("mailto://user:[email protected]?pgp=no")
3047 assert obj.pgp_mode == "no"
3048
3049 # pgp=false -> legacy bool path; no deprecation warning -> default 'no'
3050 obj = Apprise.instantiate("mailto://user:[email protected]?pgp=false")
3051 assert obj.pgp_mode == "no"
3052
3053 # pgp=yes -> parse_bool -> True -> 'encrypt' (deprecated path)
3054 obj = Apprise.instantiate("mailto://user:[email protected]?pgp=yes")
3055 assert obj.pgp_mode == "encrypt"
3056
3057 # pgp=true -> same deprecated path
3058 obj = Apprise.instantiate("mailto://user:[email protected]?pgp=true")
3059 assert obj.pgp_mode == "encrypt"
3060
3061 # url() emits 'pgp=encrypt' when mode is encrypt, and nothing when no
3062 obj = Apprise.instantiate("mailto://user:[email protected]?pgp=encrypt")
3063 assert "pgp=encrypt" in obj.url()
3064 assert "pgp=no" not in obj.url()
3065
3066 obj = Apprise.instantiate("mailto://user:[email protected]")
3067 assert "pgp=" not in obj.url()
3068
3069 # use_pgp=True deprecated kwarg maps to pgp_mode='encrypt'
3070 obj = email.NotifyEmail(
3071 user="user",
3072 password="pass",
3073 host="nuxref.com",
3074 use_pgp=True,
3075 )
3076 assert obj.pgp_mode == "encrypt"
3077
3078 # use_pgp=False deprecated kwarg maps to pgp_mode='no'
3079 obj = email.NotifyEmail(
3080 user="user",
3081 password="pass",
3082 host="nuxref.com",
3083 use_pgp=False,
3084 )
3085 assert obj.pgp_mode == "no"
3086
3087 # pgp_mode wins over use_pgp when both are supplied
3088 obj = email.NotifyEmail(
3089 user="user",
3090 password="pass",
3091 host="nuxref.com",
3092 pgp_mode="encrypt",
3093 use_pgp=False,
3094 )
3095 assert obj.pgp_mode == "encrypt"
3096
3097 # pgppub= path is masked when privacy=True
3098 obj = Apprise.instantiate(
3099 "mailto://user:[email protected]?pgp=encrypt&pgppub=/path/to/my-pub.asc"
3100 )
3101 assert obj is not None
3102 assert obj.pgp_key == "/path/to/my-pub.asc"
3103 # Full URL includes pgppub= (path may be percent-encoded in the query
3104 # string); privacy URL must replace the value with literal ****
3105 assert "pgppub=" in obj.url(privacy=False)
3106 assert "pgppub=****" in obj.url(privacy=True)
3107 assert "my-pub.asc" not in obj.url(privacy=True)
3108
3109
3110 @mock.patch("smtplib.SMTP_SSL")
3111 @mock.patch("smtplib.SMTP")
3112 def test_plugin_email_wkd_param(mock_smtp, mock_smtpssl):
3113 """NotifyEmail() wkd= URL parameter and url() round-trip."""
3114
3115 mock_socket = mock.Mock()
3116 mock_socket.starttls.return_value = True
3117 mock_socket.login.return_value = True
3118 mock_smtp.return_value = mock_socket
3119 mock_smtpssl.return_value = mock_socket
3120
3121 # wkd=yes -> use_wkd=True; a WKD controller is wired into pgp
3122 obj = Apprise.instantiate("mailto://user:[email protected]?wkd=yes")
3123 assert obj.use_wkd is True
3124 assert obj.pgp.wkd is not None
3125
3126 # wkd=yes without pgp= implies pgp=encrypt
3127 assert obj.pgp_mode == "encrypt"
3128
3129 # wkd=no -> use_wkd=False
3130 obj = Apprise.instantiate("mailto://user:[email protected]?wkd=no")
3131 assert obj.use_wkd is False
3132 assert obj.pgp.wkd is None
3133
3134 # url() includes wkd=yes when enabled; pgp=encrypt is implied
3135 obj = Apprise.instantiate("mailto://user:[email protected]?wkd=yes")
3136 generated = obj.url()
3137 assert "wkd=yes" in generated
3138 assert "pgp=encrypt" in generated
3139
3140 # wkd=yes alongside explicit pgp=no keeps no (explicit wins)
3141 obj = Apprise.instantiate("mailto://user:[email protected]?pgp=no&wkd=yes")
3142 assert obj.pgp_mode == "no"
3143
3144 # url() must emit pgp=no when wkd=yes and pgp=no is explicit so that
3145 # the round-trip URL does not re-apply the wkd=yes->encrypt implication
3146 generated = obj.url()
3147 assert "pgp=no" in generated
3148 assert "wkd=yes" in generated
3149
3150 # Parsing the round-trip URL must preserve pgp=no (not re-imply encrypt)
3151 obj2 = Apprise.instantiate(generated)
3152 assert obj2 is not None
3153 assert obj2.pgp_mode == "no"
3154 assert obj2.use_wkd is True
3155
3156 # use_wkd as a string 'no' must disable WKD (bool('no') would be True)
3157 obj = email.NotifyEmail(
3158 user="user", password="pass", host="nuxref.com", use_wkd="no"
3159 )
3160 assert obj.use_wkd is False
3161
3162 # Direct __init__ call with use_wkd=True and no pgp_mode
3163 obj = email.NotifyEmail(
3164 user="user", password="pass", host="nuxref.com", use_wkd=True
3165 )
3166 assert obj.use_wkd is True
3167 assert obj.pgp_mode == "encrypt"
3168
3169 # url() omits wkd= when disabled (it is the default)
3170 obj = Apprise.instantiate("mailto://user:[email protected]")
3171 assert "wkd=" not in obj.url()
3172
3173
3174 @pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy")
3175 @mock.patch("smtplib.SMTP_SSL")
3176 @mock.patch("smtplib.SMTP")
3177 def test_plugin_email_wkd_key_discovery(mock_smtp, mock_smtpssl, tmpdir):
3178 """Email send uses the WKD-fetched key when no local key exists."""
3179 import pgpy
3180
3181 mock_socket = mock.Mock()
3182 mock_socket.starttls.return_value = True
3183 mock_socket.login.return_value = True
3184 mock_smtp.return_value = mock_socket
3185 mock_smtpssl.return_value = mock_socket
3186
3187 # Generate a real key pair to serve as the WKD response
3188 key = pgpy.PGPKey.new(
3189 pgpy.constants.PubKeyAlgorithm.RSAEncryptOrSign, 2048
3190 )
3191 uid = pgpy.PGPUID.new("Chris", email="[email protected]")
3192 key.add_uid(
3193 uid,
3194 usage={
3195 pgpy.constants.KeyFlags.Sign,
3196 pgpy.constants.KeyFlags.EncryptCommunications,
3197 },
3198 hashes=[pgpy.constants.HashAlgorithm.SHA256],
3199 ciphers=[pgpy.constants.SymmetricKeyAlgorithm.AES256],
3200 compression=[pgpy.constants.CompressionAlgorithm.ZLIB],
3201 )
3202 pub_bytes = str(key.pubkey).encode()
3203
3204 asset = AppriseAsset(
3205 storage_mode=PersistentStoreMode.FLUSH,
3206 storage_path=str(tmpdir),
3207 )
3208
3209 obj = Apprise.instantiate(
3210 "mailto://chris:[email protected]?pgp=encrypt&wkd=yes",
3211 asset=asset,
3212 )
3213 assert obj.use_wkd is True
3214
3215 # Patch WKD fetch to return our generated public key
3216 with mock.patch.object(obj.pgp.wkd, "fetch", return_value=pub_bytes):
3217 assert obj.notify("test body") is True
3218
3219 # Clear the parsed-key cache so the second block cannot reuse the
3220 # key loaded above -- we need the fetch mock to be the sole source
3221 obj.pgp._ApprisePGPController__key_lookup.clear()
3222
3223 # WKD returning None with autogen disabled falls through gracefully
3224 asset.pgp_autogen = False
3225 with mock.patch.object(obj.pgp.wkd, "fetch", return_value=None):
3226 assert obj.notify("test body") is False
3227
3228
3229 @mock.patch("smtplib.SMTP_SSL")
3230 @mock.patch("smtplib.SMTP")
3231 def test_plugin_email_pgp_sign_mode_param(mock_smtp, mock_smtpssl):
3232 """NotifyEmail() pgp=sign mode round-trip and attribute checks."""
3233
3234 mock_socket = mock.Mock()
3235 mock_socket.starttls.return_value = True
3236 mock_socket.login.return_value = True
3237 mock_smtp.return_value = mock_socket
3238 mock_smtpssl.return_value = mock_socket
3239
3240 # pgp=sign sets pgp_mode to 'sign'
3241 obj = Apprise.instantiate("mailto://user:[email protected]?pgp=sign")
3242 assert obj is not None
3243 assert obj.pgp_mode == "sign"
3244
3245 # pgp=s (prefix shorthand) also resolves to 'sign'
3246 obj = Apprise.instantiate("mailto://user:[email protected]?pgp=s")
3247 assert obj is not None
3248 assert obj.pgp_mode == "sign"
3249
3250 # url() round-trip preserves pgp=sign
3251 obj = Apprise.instantiate("mailto://user:[email protected]?pgp=sign")
3252 generated = obj.url()
3253 assert "pgp=sign" in generated
3254 obj2 = Apprise.instantiate(generated)
3255 assert obj2 is not None
3256 assert obj2.pgp_mode == "sign"
3257
3258 # pgp=sign + wkd=yes: sign mode is respected; wkd implication does NOT
3259 # override an explicit pgp=sign to pgp=encrypt
3260 obj = Apprise.instantiate("mailto://user:[email protected]?pgp=sign&wkd=yes")
3261 assert obj.pgp_mode == "sign"
3262 assert obj.use_wkd is True
3263
3264
3265 @mock.patch("smtplib.SMTP_SSL")
3266 @mock.patch("smtplib.SMTP")
3267 def test_plugin_email_pgp_privkey_param(mock_smtp, mock_smtpssl, tmpdir):
3268 """NotifyEmail() pgpprv= URL parameter round-trip."""
3269
3270 mock_socket = mock.Mock()
3271 mock_socket.starttls.return_value = True
3272 mock_socket.login.return_value = True
3273 mock_smtp.return_value = mock_socket
3274 mock_smtpssl.return_value = mock_socket
3275
3276 prv_path = os.path.join(
3277 os.path.dirname(__file__), "var", "pgp", "valid-prv.asc"
3278 )
3279
3280 # pgpprv= is stored on the instance
3281 obj = Apprise.instantiate(
3282 f"mailto://user:[email protected]?pgp=sign&pgpprv={prv_path}"
3283 )
3284 assert obj is not None
3285 assert obj.pgp_privkey == prv_path
3286
3287 # url() includes pgpprv= in plain mode, masks it in privacy mode
3288 plain = obj.url(privacy=False)
3289 priv = obj.url(privacy=True)
3290 assert "pgpprv=" in plain
3291 assert prv_path in plain or "valid-prv.asc" in plain
3292 assert "pgpprv=****" in priv
3293
3294 # Round-trip: parse the generated URL and verify pgp_privkey is preserved
3295 parsed = email.NotifyEmail.parse_url(plain)
3296 assert parsed is not None
3297 assert "pgp_privkey" in parsed
3298 assert "valid-prv.asc" in parsed["pgp_privkey"]
3299
3300
3301 @pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy")
3302 @mock.patch("smtplib.SMTP_SSL")
3303 @mock.patch("smtplib.SMTP")
3304 def test_plugin_email_pgp_sign_send(mock_smtp, mock_smtpssl, tmpdir):
3305 """pgp=sign mode produces a multipart/signed email on send."""
3306
3307 mock_socket = mock.Mock()
3308 mock_socket.starttls.return_value = True
3309 mock_socket.login.return_value = True
3310 mock_smtp.return_value = mock_socket
3311 mock_smtpssl.return_value = mock_socket
3312
3313 prv_path = os.path.join(
3314 os.path.dirname(__file__), "var", "pgp", "valid-prv.asc"
3315 )
3316 asset = AppriseAsset(
3317 storage_mode=PersistentStoreMode.FLUSH,
3318 storage_path=str(tmpdir),
3319 )
3320 obj = Apprise.instantiate(
3321 f"mailto://user:[email protected]?pgp=sign&pgpprv={prv_path}",
3322 asset=asset,
3323 )
3324 assert obj is not None
3325
3326 # Notification should succeed and sendmail should be called once
3327 assert obj.notify("test body") is True
3328 assert mock_socket.sendmail.call_count == 1
3329
3330 # The emitted email must contain the multipart/signed structure
3331 raw = mock_socket.sendmail.call_args[0][2]
3332 assert "multipart/signed" in raw
3333 assert "application/pgp-signature" in raw
3334
3335
3336 @pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy")
3337 def test_plugin_email_pgp_sign_crlf_roundtrip(tmpdir):
3338 """PGP signature must verify against CRLF content, not bare LF.
3339
3340 This test verifies we are following RFC 3156's requirement
3341 """
3342 import pgpy as _pgpy
3343
3344 prv_path = os.path.join(TEST_VAR_DIR, "pgp", "valid-prv.asc")
3345
3346 # Build a controller that uses the test fixture private key
3347 ctrl = utils.pgp.ApprisePGPController(
3348 path=str(tmpdir), prv_keyfile=prv_path
3349 )
3350
3351 # Obtain the corresponding public key so we can verify independently;
3352 # the private key object exposes its own public sub-key via .pubkey
3353 prv_key = ctrl.private_key()
3354 assert prv_key is not None
3355 pub_key = prv_key.pubkey
3356
3357 # Simulate a MIME body with bare LF endings (as Python produces on Linux)
3358 raw_body = "Content-Type: text/plain\r\n\r\nHello RFC 3156\n"
3359
3360 # Build the CRLF form — exactly what the fixed code passes to sign()
3361 crlf_body = re.sub(r"(?:\r\n|\n|\r(?!\n))", "\r\n", raw_body)
3362
3363 # Build the bare-LF form — what the unfixed code would have passed
3364 lf_body = re.sub(r"\r\n", "\n", crlf_body)
3365
3366 # Sign the CRLF form (as the production code does)
3367 result = ctrl.sign(crlf_body)
3368 assert result is not None, "sign() must succeed with a valid private key"
3369 sig_str, micalg = result
3370 assert micalg.startswith("pgp-")
3371
3372 # Parse the returned armored signature back to a PGPSignature object
3373 sig = _pgpy.PGPSignature.from_blob(sig_str)
3374
3375 # The CRLF body must verify -- this is what the recipient receives.
3376 # pgpy.verify() returns a SignatureVerification object (truthy on
3377 # success, falsy on failure) rather than raising PGPError for a bad
3378 # signature; check the return value directly.
3379 crlf_ok = bool(pub_key.verify(crlf_body, sig))
3380 assert crlf_ok, (
3381 "Signature did not verify against CRLF content -- "
3382 "the signed body must use CRLF line endings (RFC 3156)"
3383 )
3384
3385 # The bare-LF form must NOT verify (regression guard: CRLF
3386 # normalisation before pgp.sign() must not be removed).
3387 lf_ok = bool(pub_key.verify(lf_body, sig))
3388 assert not lf_ok, (
3389 "Signature verified against bare-LF content -- CRLF normalisation "
3390 "before pgp.sign() may have been removed (regression)"
3391 )
3392
3393
3394 @pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy")
3395 @mock.patch("smtplib.SMTP_SSL")
3396 @mock.patch("smtplib.SMTP")
3397 def test_plugin_email_pgp_sign_wire_content_crlf(
3398 mock_smtp, mock_smtpssl, tmpdir
3399 ):
3400 """Content passed to pgp.sign() must have no bare LF line endings.
3401
3402 Further verification ensureing RFC 3156 requirements are met
3403 """
3404 mock_socket = mock.Mock()
3405 mock_socket.starttls.return_value = True
3406 mock_socket.login.return_value = True
3407 mock_smtp.return_value = mock_socket
3408 mock_smtpssl.return_value = mock_socket
3409
3410 prv_path = os.path.join(TEST_VAR_DIR, "pgp", "valid-prv.asc")
3411
3412 # Capture the exact content forwarded to pgp.sign() during send
3413 signed_content = {}
3414 original_sign = utils.pgp.ApprisePGPController.sign
3415
3416 def capturing_sign(self, message):
3417 # Record the message that base.py passes to the signer
3418 signed_content["message"] = message
3419 return original_sign(self, message)
3420
3421 asset = AppriseAsset(
3422 storage_mode=PersistentStoreMode.FLUSH,
3423 storage_path=str(tmpdir),
3424 )
3425 obj = Apprise.instantiate(
3426 f"mailto://user:[email protected]?pgp=sign&pgpprv={prv_path}",
3427 asset=asset,
3428 )
3429 assert obj is not None
3430
3431 # Send while intercepting sign() to record the input content
3432 with mock.patch.object(
3433 utils.pgp.ApprisePGPController, "sign", capturing_sign
3434 ):
3435 assert obj.notify("test body") is True
3436
3437 # Confirm send actually happened and our interceptor was triggered
3438 assert mock_socket.sendmail.call_count == 1
3439 assert "message" in signed_content, (
3440 "pgp.sign() was not called during the send — "
3441 "the interception wrapper was not reached"
3442 )
3443
3444 # Verify every line ending in the signed content must be CRLF
3445 assert not re.search(r"(?<!\r)\n", signed_content["message"]), (
3446 "pgp.sign() received content with bare LF line endings — "
3447 "CRLF normalisation (RFC 3156 compliance) may have been removed "
3448 "from base.py"
3449 )
3450
3451
3452 @pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy")
3453 @mock.patch("smtplib.SMTP_SSL")
3454 @mock.patch("smtplib.SMTP")
3455 def test_plugin_email_pgp_sign_no_privkey_fails(
3456 mock_smtp, mock_smtpssl, tmpdir
3457 ):
3458 """pgp=sign with no accessible private key causes send to fail."""
3459
3460 mock_socket = mock.Mock()
3461 mock_socket.starttls.return_value = True
3462 mock_socket.login.return_value = True
3463 mock_smtp.return_value = mock_socket
3464 mock_smtpssl.return_value = mock_socket
3465
3466 asset = AppriseAsset(
3467 storage_mode=PersistentStoreMode.FLUSH,
3468 storage_path=str(tmpdir),
3469 )
3470 # Sign mode requested but no private key in tmpdir and none specified
3471 obj = Apprise.instantiate(
3472 "mailto://user:[email protected]?pgp=sign",
3473 asset=asset,
3474 )
3475 assert obj is not None
3476 assert obj.notify("test body") is False
3477
3478
3479 @pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy")
3480 @mock.patch("smtplib.SMTP_SSL")
3481 @mock.patch("smtplib.SMTP")
3482 def test_plugin_email_pgp_sign_opportunistic_encrypt(
3483 mock_smtp, mock_smtpssl, tmpdir
3484 ):
3485 """pgp=sign with WKD: signs always, encrypts when WKD key found."""
3486
3487 mock_socket = mock.Mock()
3488 mock_socket.starttls.return_value = True
3489 mock_socket.login.return_value = True
3490 mock_smtp.return_value = mock_socket
3491 mock_smtpssl.return_value = mock_socket
3492
3493 prv_path = os.path.join(
3494 os.path.dirname(__file__), "var", "pgp", "valid-prv.asc"
3495 )
3496
3497 # Generate a public key to serve as the WKD payload
3498 key = pgpy.PGPKey.new(
3499 pgpy.constants.PubKeyAlgorithm.RSAEncryptOrSign, 2048
3500 )
3501 uid = pgpy.PGPUID.new("User", email="[email protected]")
3502 key.add_uid(
3503 uid,
3504 usage={
3505 pgpy.constants.KeyFlags.Sign,
3506 pgpy.constants.KeyFlags.EncryptCommunications,
3507 },
3508 hashes=[pgpy.constants.HashAlgorithm.SHA256],
3509 ciphers=[pgpy.constants.SymmetricKeyAlgorithm.AES256],
3510 compression=[pgpy.constants.CompressionAlgorithm.ZLIB],
3511 )
3512 pub_bytes = str(key.pubkey).encode()
3513
3514 asset = AppriseAsset(
3515 storage_mode=PersistentStoreMode.FLUSH,
3516 storage_path=str(tmpdir),
3517 )
3518 obj = Apprise.instantiate(
3519 f"mailto://user:[email protected]?pgp=sign&wkd=yes&pgpprv={prv_path}",
3520 asset=asset,
3521 )
3522 assert obj is not None
3523 assert obj.pgp_mode == "sign"
3524
3525 # With WKD returning a public key: sign + encrypt
3526 with mock.patch.object(obj.pgp.wkd, "fetch", return_value=pub_bytes):
3527 assert obj.notify("test body") is True
3528
3529 raw = mock_socket.sendmail.call_args[0][2]
3530 # The outer structure is multipart/encrypted (the signed body is inside)
3531 assert "multipart/encrypted" in raw
3532 mock_socket.sendmail.reset_mock()
3533
3534 # Clear the cache so the next call re-queries WKD
3535 obj.pgp._ApprisePGPController__key_lookup.clear()
3536
3537 # With WKD returning nothing: sign only, no failure
3538 with mock.patch.object(obj.pgp.wkd, "fetch", return_value=None):
3539 assert obj.notify("test body") is True
3540
3541 raw = mock_socket.sendmail.call_args[0][2]
3542 # No encryption this time; just a signed message
3543 assert "multipart/signed" in raw
3544 assert "multipart/encrypted" not in raw
3545
3546
3547 @mock.patch("smtplib.SMTP_SSL")
3548 @mock.patch("smtplib.SMTP")
3549 def test_plugin_email_pgp_sign_no_pgp_support(mock_smtp, mock_smtpssl):
3550 """pgp=sign fails gracefully when PGPy is not installed."""
3551
3552 mock_socket = mock.Mock()
3553 mock_socket.starttls.return_value = True
3554 mock_socket.login.return_value = True
3555 mock_smtp.return_value = mock_socket
3556 mock_smtpssl.return_value = mock_socket
3557
3558 prv_path = os.path.join(
3559 os.path.dirname(__file__), "var", "pgp", "valid-prv.asc"
3560 )
3561 obj = Apprise.instantiate(
3562 f"mailto://user:[email protected]?pgp=sign&pgpprv={prv_path}"
3563 )
3564 assert obj is not None
3565
3566 # Simulate PGPy not installed
3567 import apprise.utils.pgp as pgp_utils
3568
3569 real_support = pgp_utils.PGP_SUPPORT
3570 pgp_utils.PGP_SUPPORT = False
3571 try:
3572 assert obj.notify("test body") is False
3573 finally:
3574 pgp_utils.PGP_SUPPORT = real_support
3575
3576
3577 @pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy")
3578 @mock.patch("smtplib.SMTP_SSL")
3579 @mock.patch("smtplib.SMTP")
3580 def test_plugin_email_pgp_sign_encrypt_none_mode(
3581 mock_smtp, mock_smtpssl, tmpdir
3582 ):
3583 """prepare_emails() skips PGP entirely when pgp_mode is PGPMode.NONE."""
3584
3585 mock_socket = mock.Mock()
3586 mock_socket.starttls.return_value = True
3587 mock_socket.login.return_value = True
3588 mock_smtp.return_value = mock_socket
3589 mock_smtpssl.return_value = mock_socket
3590
3591 prv_path = os.path.join(
3592 os.path.dirname(__file__), "var", "pgp", "valid-prv.asc"
3593 )
3594 asset = AppriseAsset(
3595 storage_mode=PersistentStoreMode.FLUSH,
3596 storage_path=str(tmpdir),
3597 )
3598
3599 # pgp=no disables all PGP even when a private key is provided
3600 obj = Apprise.instantiate(
3601 f"mailto://user:[email protected]?pgp=no&pgpprv={prv_path}",
3602 asset=asset,
3603 )
3604 assert obj is not None
3605 assert obj.notify("test body") is True
3606
3607 # The email must not contain any PGP markers
3608 raw = mock_socket.sendmail.call_args[0][2]
3609 assert "pgp-signature" not in raw.lower()
3610 assert "pgp-encrypted" not in raw.lower()
3611
3612
3613 @pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy")
3614 @mock.patch("smtplib.SMTP_SSL")
3615 @mock.patch("smtplib.SMTP")
3616 def test_plugin_email_pgp_sign_keygen_auto(mock_smtp, mock_smtpssl, tmpdir):
3617 """pgp=sign auto-discovers a private key generated by keygen()."""
3618
3619 mock_socket = mock.Mock()
3620 mock_socket.starttls.return_value = True
3621 mock_socket.login.return_value = True
3622 mock_smtp.return_value = mock_socket
3623 mock_smtpssl.return_value = mock_socket
3624
3625 asset = AppriseAsset(
3626 storage_mode=PersistentStoreMode.FLUSH,
3627 storage_path=str(tmpdir),
3628 )
3629 obj = Apprise.instantiate(
3630 "mailto://user:[email protected]?pgp=sign",
3631 asset=asset,
3632 )
3633 assert obj is not None
3634
3635 # Generate the key pair into the storage directory
3636 assert obj.pgp.keygen() is True
3637
3638 # Now send -- the auto-generated private key must be discovered.
3639 # With both keys present the message is sign+encrypted; the signing
3640 # step is the behavior under test, so we only assert success here.
3641 assert obj.notify("test body") is True
3642
3643
3644 def test_plugin_email_prepare():
3645 """NotifyEmail() prepare_emails static function."""
3646 with pytest.raises(AppriseException):
3647 # No To: provided
3648 for _e in email.NotifyEmail.prepare_emails(
3649 subject="Email Subject",
3650 body="Email Body",
3651 from_addr=(None, "[email protected]"),
3652 to=[],
3653 ):
3654 pass
3655
3656 # Most basic call (a lot of defaults are used)
3657 iterator = email.NotifyEmail.prepare_emails(
3658 subject="Email Subject",
3659 body="Email Body",
3660 from_addr=(None, "[email protected]"),
3661 to=[
3662 ("Apprise User", "[email protected]"),
3663 ],
3664 )
3665 entries = list(iterator)
3666 assert len(entries) == 1
3667
3668
3669 @pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy")
3670 def test_plugin_pgp(tmpdir):
3671 """Pretty Good Privacy Testing."""
3672
3673 p_obj = utils.pgp.ApprisePGPController(path=None)
3674 # No Path
3675 assert p_obj.keygen() is False
3676 assert p_obj.public_keyfile() is None
3677
3678 p_obj = utils.pgp.ApprisePGPController(path=None, email="[email protected]")
3679 # No Path
3680 assert p_obj.keygen() is False
3681
3682 tmpdir0 = tmpdir.mkdir("tmp00")
3683 p_obj = utils.pgp.ApprisePGPController(
3684 path=str(tmpdir0), email="[email protected]"
3685 )
3686
3687 # A key can be generated with a path defined
3688 assert p_obj.keygen() is True
3689 assert p_obj.public_keyfile() is not None
3690 # A key can be generated with a path defined
3691 assert p_obj.keygen(name="Apprise", force=True) is True
3692 assert (
3693 p_obj.keygen(email="[email protected]", name="Apprise", force=True) is True
3694 )
3695
3696 assert utils.pgp.PGP_SUPPORT is True
3697 utils.pgp.PGP_SUPPORT = False
3698
3699 with pytest.raises(AppriseException):
3700 assert p_obj.public_keyfile()
3701
3702 # Return the PGP status for remaining checks
3703 utils.pgp.PGP_SUPPORT = True
3704
3705 tmpdir1 = tmpdir.mkdir("tmp01")
3706 p_obj = utils.pgp.ApprisePGPController(
3707 path=str(tmpdir1), pub_keyfile="bad-file"
3708 )
3709 assert p_obj.public_keyfile() is False
3710
3711
3712 @pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy")
3713 def test_pgp_public_keyfile_skips_self_email(tmpdir):
3714 """Test pgp.public_keyfile() when self.email is None and skipped."""
3715
3716 key_dir = tmpdir.mkdir("pgpkeytest2")
3717 key_path = os.path.join(str(key_dir), "externaluser-pub.asc")
3718
3719 # Create a fake matching keyfile to trigger discovery
3720 with open(key_path, "w") as f:
3721 f.write("-----BEGIN PGP PUBLIC KEY BLOCK-----\n")
3722
3723 # Controller without setting self.email
3724 pgp = utils.pgp.ApprisePGPController(path=str(key_dir), email=None)
3725
3726 # Should skip over `if self.email:` logic entirely
3727 result = pgp.public_keyfile("[email protected]")
3728
3729 assert result.endswith("externaluser-pub.asc")
3730
3731
3732 @mock.patch("smtplib.SMTP")
3733 def test_plugin_email_gmx_template_lookup(mock_smtp):
3734 """NotifyEmail() GMX template lookup tests."""
3735
3736 response = mock.Mock()
3737 mock_smtp.return_value = response
3738
3739 for domain in (
3740 "gmx.net",
3741 "gmx.com",
3742 "gmx.de",
3743 "gmx.at",
3744 "gmx.ch",
3745 "gmx.fr",
3746 ):
3747 results = email.NotifyEmail.parse_url(
3748 f"mailtos://user:pass123@{domain}"
3749 )
3750 obj = Apprise.instantiate(results, suppress_exceptions=False)
3751 assert isinstance(obj, email.NotifyEmail)
3752
3753 # Template-driven defaults
3754 assert obj.smtp_host == "mail.gmx.com"
3755 assert obj.secure_mode == "starttls"
3756 assert obj.port == 587
3757 assert obj.secure is True
3758
3759 # Send once to trigger SMTP/login behaviour
3760 assert obj.notify("body", "title") is True
3761
3762 # STARTTLS used
3763 assert response.starttls.call_count == 1
3764 assert response.login.call_count == 1
3765
3766 login_user, login_pass = response.login.call_args[0]
3767 mock_smtp.reset_mock()
3768
3769 assert login_pass == "pass123"
3770
3771 # GMX should authenticate with full email, not just the local part
3772 assert login_user == f"user@{domain}"
3773
3774
3775 @mock.patch("smtplib.SMTP")
3776 @mock.patch("smtplib.SMTP_SSL")
3777 def test_plugin_email_tls_certificate_verification(mock_smtpssl, mock_smtp):
3778 """Verify that SMTPS and STARTTLS honour the verify_certificate setting by
3779 passing a validating SSL context to smtplib."""
3780
3781 response = mock.Mock()
3782 response.starttls.return_value = True
3783 response.login.return_value = True
3784 response.sendmail.return_value = True
3785 response.quit.return_value = True
3786 mock_smtp.return_value = response
3787 mock_smtpssl.return_value = response
3788
3789 # 1. SMTPS (mode=ssl) with the default verify_certificate=True should
3790 # pass a context that validates the certificate and hostname.
3791 obj = Apprise.instantiate(
3792 "mailtos://user:[email protected]?mode=ssl",
3793 suppress_exceptions=False,
3794 )
3795 assert isinstance(obj, email.NotifyEmail)
3796 assert obj.verify_certificate is True
3797 assert obj.notify(body="body", title="title") is True
3798
3799 assert mock_smtpssl.call_count == 1
3800 context = mock_smtpssl.call_args.kwargs.get("context")
3801 assert isinstance(context, ssl.SSLContext)
3802 assert context.verify_mode == ssl.CERT_REQUIRED
3803 assert context.check_hostname is True
3804
3805 mock_smtp.reset_mock()
3806 mock_smtpssl.reset_mock()
3807
3808 # 2. SMTPS (mode=ssl) with verify=no should pass a context that does not
3809 # validate the certificate.
3810 obj = Apprise.instantiate(
3811 "mailtos://user:[email protected]?mode=ssl&verify=no",
3812 suppress_exceptions=False,
3813 )
3814 assert obj.verify_certificate is False
3815 assert obj.notify(body="body", title="title") is True
3816
3817 assert mock_smtpssl.call_count == 1
3818 context = mock_smtpssl.call_args.kwargs.get("context")
3819 assert isinstance(context, ssl.SSLContext)
3820 assert context.verify_mode == ssl.CERT_NONE
3821 assert context.check_hostname is False
3822
3823 mock_smtp.reset_mock()
3824 mock_smtpssl.reset_mock()
3825
3826 # 3. STARTTLS with the default verify_certificate=True should pass a
3827 # validating context to starttls().
3828 obj = Apprise.instantiate(
3829 "mailtos://user:[email protected]?mode=starttls",
3830 suppress_exceptions=False,
3831 )
3832 assert obj.verify_certificate is True
3833 assert obj.notify(body="body", title="title") is True
3834
3835 assert response.starttls.call_count == 1
3836 context = response.starttls.call_args.kwargs.get("context")
3837 assert isinstance(context, ssl.SSLContext)
3838 assert context.verify_mode == ssl.CERT_REQUIRED
3839 assert context.check_hostname is True
3840
3841 response.starttls.reset_mock()
3842
3843 # 4. STARTTLS with verify=no should pass a non-validating context.
3844 obj = Apprise.instantiate(
3845 "mailtos://user:[email protected]?mode=starttls&verify=no",
3846 suppress_exceptions=False,
3847 )
3848 assert obj.verify_certificate is False
3849 assert obj.notify(body="body", title="title") is True
3850
3851 assert response.starttls.call_count == 1
3852 context = response.starttls.call_args.kwargs.get("context")
3853 assert isinstance(context, ssl.SSLContext)
3854 assert context.verify_mode == ssl.CERT_NONE
3855 assert context.check_hostname is False
3856
3857
3858 @mock.patch("smtplib.SMTP")
3859 def test_plugin_email_starttls_certificate_failure_handling(mock_smtp):
3860 """A rejected STARTTLS certificate must be a normal send failure."""
3861 response = mock.Mock()
3862 response.starttls.side_effect = ssl.SSLCertVerificationError(
3863 "certificate verify failed"
3864 )
3865 # A real socket is no longer connected after the failed TLS handshake.
3866 response.quit.side_effect = smtplib.SMTPServerDisconnected(
3867 "Server not connected"
3868 )
3869 mock_smtp.return_value = response
3870
3871 obj = Apprise.instantiate(
3872 "mailtos://user:[email protected]?mode=starttls",
3873 suppress_exceptions=False,
3874 )
3875 assert isinstance(obj, email.NotifyEmail)
3876
3877 assert obj.notify(body="body", title="title") is False
3878 response.login.assert_not_called()
3879 response.sendmail.assert_not_called()
3880
3881
3882 @mock.patch("smtplib.SMTP")
3883 def test_plugin_email_inline_attachments(mock_smtplib):
3884 """Test ?inline=yes RFC 2387 inline attachment handling."""
3885
3886 # Capture raw email bodies sent via SMTP
3887 sent_messages = []
3888
3889 class SMTPMock:
3890 def __init__(self, *a, **kw):
3891 pass
3892
3893 def sendmail(self, from_addr, to_addrs, message):
3894 sent_messages.append(message)
3895
3896 def quit(self, *a, **kw):
3897 pass
3898
3899 def starttls(self, *a, **kw):
3900 pass
3901
3902 def login(self, *a, **kw):
3903 pass
3904
3905 mock_smtplib.return_value = SMTPMock()
3906
3907 img = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
3908 img_name = "apprise-test.gif"
3909 img2 = os.path.join(TEST_VAR_DIR, "apprise-test.png")
3910 img2_name = "apprise-test.png"
3911
3912 # inline=False (default): multipart/mixed, attachment
3913 obj = Apprise.instantiate(
3914 "mailto://user:[email protected]", suppress_exceptions=False
3915 )
3916 assert isinstance(obj, email.NotifyEmail)
3917 assert obj.inline is False
3918
3919 sent_messages.clear()
3920 assert (
3921 obj.notify(
3922 body="<p>hello</p>",
3923 title="test",
3924 notify_type=NotifyType.INFO,
3925 attach=img,
3926 )
3927 is True
3928 )
3929 assert len(sent_messages) == 1
3930 msg = sent_messages[0]
3931
3932 # Standard mode: mixed wrapper, attachment disposition, no Content-ID
3933 assert "multipart/mixed" in msg
3934 assert "Content-Disposition: attachment" in msg
3935 assert "Content-ID" not in msg
3936
3937 obj = Apprise.instantiate(
3938 "mailto://user:[email protected]?inline=yes", suppress_exceptions=False
3939 )
3940 assert isinstance(obj, email.NotifyEmail)
3941 assert obj.inline is True
3942
3943 # inline=True, HTML, image with no pre-existing cid: ref:
3944 # a <br/><img src="cid:name"> anchor is appended to the body and
3945 # the attachment is embedded inline
3946 sent_messages.clear()
3947 assert (
3948 obj.notify(
3949 body="<p>no cid ref here</p>",
3950 title="test",
3951 notify_type=NotifyType.INFO,
3952 attach=img,
3953 )
3954 is True
3955 )
3956 assert len(sent_messages) == 1
3957 msg = sent_messages[0]
3958
3959 # Image inlined regardless -- anchor appended automatically
3960 assert "multipart/related" in msg
3961 assert "Content-Disposition: inline" in msg
3962 assert "Content-ID:" in msg
3963 assert img_name in msg
3964
3965 # inline=True, HTML, image WITH pre-existing cid: ref:
3966 # no duplicate anchor is added; attachment still inlined
3967 html_with_ref = f'<img src="cid:{img_name}">'
3968
3969 sent_messages.clear()
3970 assert (
3971 obj.notify(
3972 body=html_with_ref,
3973 title="test",
3974 notify_type=NotifyType.INFO,
3975 attach=img,
3976 )
3977 is True
3978 )
3979 assert len(sent_messages) == 1
3980 msg = sent_messages[0]
3981
3982 # Still related + inline; body should not have a second <br/><img>
3983 assert "multipart/related" in msg
3984 assert "Content-Disposition: inline" in msg
3985 assert "Content-ID:" in msg
3986 # Only one cid: anchor expected in the body part
3987 assert msg.count(f"cid:{img_name}") == 1
3988
3989 # inline=True, HTML, two images: both inlined, body gets an
3990 # anchor appended for the one not already referenced
3991 html_one_ref = f'<img src="cid:{img_name}">'
3992
3993 sent_messages.clear()
3994 assert (
3995 obj.notify(
3996 body=html_one_ref,
3997 title="test",
3998 notify_type=NotifyType.INFO,
3999 attach=AppriseAttachment([img, img2]),
4000 )
4001 is True
4002 )
4003 assert len(sent_messages) == 1
4004 msg = sent_messages[0]
4005
4006 # Both images are inline; second one had its anchor appended
4007 assert "multipart/related" in msg
4008 assert msg.count("Content-Disposition: inline") == 2
4009 assert msg.count("Content-ID:") == 2
4010 assert img_name in msg
4011 assert img2_name in msg
4012
4013 # inline=True, HTML, non-image attachment: stays as regular
4014 # download regardless of inline flag
4015 img_jpeg = os.path.join(TEST_VAR_DIR, "apprise-test.jpeg")
4016
4017 from apprise.attachment.file import AttachFile
4018
4019 pdf_attach = AttachFile(img_jpeg, mimetype="application/pdf")
4020 aa = AppriseAttachment()
4021 aa.add(pdf_attach)
4022
4023 sent_messages.clear()
4024 assert (
4025 obj.notify(
4026 body="<p>body</p>",
4027 title="test",
4028 notify_type=NotifyType.INFO,
4029 attach=aa,
4030 )
4031 is True
4032 )
4033 assert len(sent_messages) == 1
4034 msg = sent_messages[0]
4035
4036 # No image -> no related wrapper, no inline, no Content-ID
4037 assert "multipart/mixed" in msg
4038 assert "Content-Disposition: attachment" in msg
4039 assert "Content-ID" not in msg
4040
4041 # inline=True, TEXT format: [Image: name] is appended to the
4042 # text body; attachment stays as a regular download
4043 obj_txt = Apprise.instantiate(
4044 "mailto://user:[email protected]?inline=yes&format=text",
4045 suppress_exceptions=False,
4046 )
4047 assert isinstance(obj_txt, email.NotifyEmail)
4048 assert obj_txt.inline is True
4049
4050 sent_messages.clear()
4051 assert (
4052 obj_txt.notify(
4053 body="plain text body",
4054 title="test",
4055 notify_type=NotifyType.INFO,
4056 attach=img,
4057 )
4058 is True
4059 )
4060 assert len(sent_messages) == 1
4061 msg = sent_messages[0]
4062
4063 # Text mode: mixed wrapper, attachment disposition, placeholder in body
4064 assert "multipart/mixed" in msg
4065 assert "Content-Disposition: attachment" in msg
4066 assert "Content-ID" not in msg
4067 assert f"[Image: {img_name}]" in msg
4068
4069 # inline=True, TEXT format, non-image attachment
4070 sent_messages.clear()
4071 assert (
4072 obj_txt.notify(
4073 body="plain text body",
4074 title="test",
4075 notify_type=NotifyType.INFO,
4076 attach=aa, # application/pdf override -- not an image
4077 )
4078 is True
4079 )
4080 assert len(sent_messages) == 1
4081 msg = sent_messages[0]
4082
4083 # Non-image in text inline mode: body unchanged, no [Image:] annotation
4084 assert "Content-Disposition: attachment" in msg
4085 assert "[Image:" not in msg
4086
4087 # inline=True, HTML, image attachment with uppercase mimetype
4088 upper_attach = AttachFile(img)
4089 upper_attach.detected_mimetype = "Image/GIF"
4090 aa_upper = AppriseAttachment()
4091 aa_upper.add(upper_attach)
4092
4093 sent_messages.clear()
4094 assert (
4095 obj.notify(
4096 body="<p>no cid</p>",
4097 title="test",
4098 notify_type=NotifyType.INFO,
4099 attach=aa_upper,
4100 )
4101 is True
4102 )
4103 assert len(sent_messages) == 1
4104 msg = sent_messages[0]
4105
4106 # Uppercase mimetype must still be treated as an image
4107 assert "multipart/related" in msg
4108 assert "Content-Disposition: inline" in msg
4109
4110 # inline=True, TEXT format, uppercase mimetype: [Image: name] marker must
4111 # also appear, proving the case-insensitive check works in the text path
4112 sent_messages.clear()
4113 assert (
4114 obj_txt.notify(
4115 body="plain body",
4116 title="test",
4117 notify_type=NotifyType.INFO,
4118 attach=aa_upper,
4119 )
4120 is True
4121 )
4122 assert len(sent_messages) == 1
4123 msg = sent_messages[0]
4124 assert f"[Image: {img_name}]" in msg
4125
4126 # inline=True, HTML, cid: ref in body with no matching attachment:
4127 # warning is logged so the user can debug the mismatch
4128 with mock.patch("apprise.plugins.email.base.logger") as mock_logger:
4129 assert (
4130 obj.notify(
4131 body='<img src="cid:missing-file.jpg">',
4132 title="test",
4133 notify_type=NotifyType.INFO,
4134 attach=img,
4135 )
4136 is True
4137 )
4138
4139 # Warning fired for the unmatched ref
4140 warning_texts = " ".join(
4141 str(c) for c in mock_logger.warning.call_args_list
4142 )
4143 assert "missing-file.jpg" in warning_texts
4144
4145 # inline=True, HTML, only unmatched cid: ref with a non-image attachment:
4146 # the unmatched ref is dropped after the warning so cid_refs is empty
4147 # when the wrapper type is chosen -- wrapper must be multipart/mixed
4148 sent_messages.clear()
4149 with mock.patch("apprise.plugins.email.base.logger"):
4150 assert (
4151 obj.notify(
4152 body='<p>body <img src="cid:ghost.jpg"></p>',
4153 title="test",
4154 notify_type=NotifyType.INFO,
4155 # application/pdf -- not an image, not named ghost.jpg
4156 attach=aa,
4157 )
4158 is True
4159 )
4160 assert len(sent_messages) == 1
4161 msg = sent_messages[0]
4162
4163 # No inline parts exist: wrapper must be mixed, not related
4164 assert "multipart/mixed" in msg
4165 assert "multipart/related" not in msg
4166 assert "Content-ID" not in msg
4167
4168 # inline=True, HTML, explicit cid: ref whose filename MATCHES a
4169 # non-image attachment (PDF): a cid: URI can only resolve within
4170 # the same MIME package, so if the caller wrote it they attached
4171 # the file deliberately. The ref is honored regardless of type --
4172 # wrapper becomes multipart/related and the PDF is inlined.
4173 sent_messages.clear()
4174 with mock.patch("apprise.plugins.email.base.logger") as mock_logger:
4175 assert (
4176 obj.notify(
4177 body=f'<p>body <embed src="cid:{pdf_attach.name}"></p>',
4178 title="test",
4179 notify_type=NotifyType.INFO,
4180 # same PDF attachment as earlier tests
4181 attach=aa,
4182 )
4183 is True
4184 )
4185 # The body ref matched by name, so no "no attachment matches" warning
4186 for call in mock_logger.warning.call_args_list:
4187 assert "apprise-test" not in str(call)
4188 assert len(sent_messages) == 1
4189 msg = sent_messages[0]
4190
4191 # Explicit cid: ref to PDF must be honored: related wrapper, inline
4192 assert "multipart/related" in msg
4193 assert "Content-Disposition: inline" in msg
4194 assert "Content-ID" in msg
4195
4196 # inline=True, HTML, cid: ref encoded with %20 for a file whose actual
4197 # name contains a space: the decoded ref matches the attachment so no
4198 # spurious warning is fired and the image is inlined exactly once
4199 spaced_attach = AttachFile(img, name="my photo.gif")
4200 aa_spaced = AppriseAttachment()
4201 aa_spaced.add(spaced_attach)
4202
4203 sent_messages.clear()
4204 with mock.patch("apprise.plugins.email.base.logger") as mock_logger:
4205 assert (
4206 obj.notify(
4207 body='<img src="cid:my%20photo.gif">',
4208 title="test",
4209 notify_type=NotifyType.INFO,
4210 attach=aa_spaced,
4211 )
4212 is True
4213 )
4214
4215 # No warning about an unmatched ref -- %20 decoded to space matched it
4216 for call in mock_logger.warning.call_args_list:
4217 assert "my" not in str(call), (
4218 "Spurious warning fired for a cid: ref that should have "
4219 "matched after %20 normalisation"
4220 )
4221 assert len(sent_messages) == 1
4222 msg = sent_messages[0]
4223
4224 # Image is inlined exactly once (no duplicate anchor)
4225 assert msg.count("cid:my%20photo.gif") == 1
4226 assert "Content-Disposition: inline" in msg
4227 assert "Content-ID" in msg
4228
4229 # inline=True, HTML, inaccessible attachment
4230 bad_attach = AttachFile("/nonexistent/path/photo.jpg")
4231 aa_bad = AppriseAttachment()
4232 aa_bad.add(bad_attach)
4233
4234 sent_messages.clear()
4235 assert (
4236 obj.notify(
4237 body="<p>body</p>",
4238 title="test",
4239 notify_type=NotifyType.INFO,
4240 attach=aa_bad,
4241 )
4242 is False # bad attachment detected by the main loop
4243 )
4244 # No sendmail call -- the bad attachment caused an early failure
4245 assert len(sent_messages) == 0
4246
4247 # inline=True, TEXT format, inaccessible attachment
4248 sent_messages.clear()
4249 assert (
4250 obj_txt.notify(
4251 body="plain body",
4252 title="test",
4253 notify_type=NotifyType.INFO,
4254 attach=aa_bad,
4255 )
4256 is False
4257 )
4258 assert len(sent_messages) == 0
4259
4260 # URL round-trip: inline=yes survives url() -> parse_url()
4261 assert "inline=yes" in obj.url()
4262 parsed = email.NotifyEmail.parse_url(obj.url())
4263 assert parsed is not None
4264 assert parsed.get("inline") is True
4265
4266 # inline=no parses as False
4267 obj2 = Apprise.instantiate(
4268 "mailto://user:[email protected]?inline=no", suppress_exceptions=False
4269 )
4270 assert isinstance(obj2, email.NotifyEmail)
4271 assert obj2.inline is False
4272 assert "inline" not in obj2.url()