File: test_plugin_email.py

package info (click to toggle)
apprise 1.9.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,792 kB
  • sloc: python: 74,226; sh: 132; makefile: 6
file content (2460 lines) | stat: -rw-r--r-- 86,663 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
# -*- coding: utf-8 -*-
# BSD 2-Clause License
#
# Apprise - Push Notification Library.
# Copyright (c) 2025, Chris Caron <lead2gold@gmail.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import logging
import pytest
import os
import shutil
import sys
import re
from unittest import mock
from inspect import cleandoc

import smtplib
from email.header import decode_header

from apprise import NotifyType, NotifyBase
from apprise import Apprise
from apprise import AttachBase
from apprise import AppriseAsset
from apprise import PersistentStoreMode
from apprise.exception import AppriseException
from apprise.config import ConfigBase
from apprise import AppriseAttachment
from apprise.plugins import email
from apprise import utils

# Disable logging for a cleaner testing output
logging.disable(logging.CRITICAL)

# Attachment Directory
TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), 'var')

TEST_URLS = (
    ##################################
    # NotifyEmail
    ##################################
    ('mailto://', {
        'instance': TypeError,
    }),
    ('mailtos://', {
        'instance': TypeError,
    }),
    ('mailto://:@/', {
        'instance': TypeError,
    }),
    # No Username
    ('mailtos://:pass@nuxref.com:567', {
        # Can't prepare a To address using this expression
        'instance': TypeError,
    }),

    # Pre-Configured Email Services
    ('mailto://user:pass@gmail.com', {
        'instance': email.NotifyEmail,
    }),
    ('mailto://user:pass@hotmail.com', {
        'instance': email.NotifyEmail,
    }),
    ('mailto://user:pass@live.com', {
        'instance': email.NotifyEmail,
    }),
    ('mailto://user:pass@prontomail.com', {
        'instance': email.NotifyEmail,
    }),
    ('mailto://user:pass@yahoo.com', {
        'instance': email.NotifyEmail,
    }),
    ('mailto://user:pass@yahoo.ca', {
        'instance': email.NotifyEmail,
    }),
    ('mailto://user:pass@fastmail.com', {
        'instance': email.NotifyEmail,
    }),
    ('mailto://user:pass@sendgrid.com', {
        'instance': email.NotifyEmail,
    }),

    # Yandex
    ('mailto://user:pass@yandex.com', {
        'instance': email.NotifyEmail,
    }),
    ('mailto://user:pass@yandex.ru', {
        'instance': email.NotifyEmail,
    }),
    ('mailto://user:pass@yandex.fr', {
        'instance': email.NotifyEmail,
    }),

    # Custom Emails
    ('mailtos://user:pass@nuxref.com:567', {
        'instance': email.NotifyEmail,
    }),
    ('mailto://user:pass@nuxref.com?mode=ssl', {
        # mailto:// with mode=ssl causes us to convert to ssl
        'instance': email.NotifyEmail,
        # Our expected url(privacy=True) startswith() response:
        'privacy_url': 'mailtos://user:****@nuxref.com',
    }),
    ('mailto://user:pass@nuxref.com:567?format=html', {
        'instance': email.NotifyEmail,
    }),
    ('mailtos://user:pass@nuxref.com:567?to=l2g@nuxref.com', {
        'instance': email.NotifyEmail,
    }),
    ('mailtos://user:pass@domain.com?user=admin@mail-domain.com', {
        'instance': email.NotifyEmail,
    }),
    ('mailtos://%20@domain.com?user=admin@mail-domain.com', {
        'instance': email.NotifyEmail,
    }),
    ('mailtos://%20@domain.com?user=admin@mail-domain.com?pgp=yes', {
        # Test pgp flag
        'instance': email.NotifyEmail,
    }),
    ('mailtos://user:pass@nuxref.com:567/l2g@nuxref.com', {
        'instance': email.NotifyEmail,
    }),
    (
        'mailto://user:pass@example.com:2525?user=l2g@example.com'
        '&pass=l2g@apprise!is!Awesome', {
            'instance': email.NotifyEmail,
        },
    ),
    (
        'mailto://user:pass@example.com:2525?user=l2g@example.com'
        '&pass=l2g@apprise!is!Awesome&format=text', {
            'instance': email.NotifyEmail,
        },
    ),
    (
        # Test Carbon Copy
        'mailtos://user:pass@example.com?smtp=smtp.example.com'
        '&name=l2g&cc=noreply@example.com,test@example.com', {
            'instance': email.NotifyEmail,
        },
    ),
    (
        # Test Blind Carbon Copy
        'mailtos://user:pass@example.com?smtp=smtp.example.com'
        '&name=l2g&bcc=noreply@example.com,test@example.com', {
            'instance': email.NotifyEmail,
        },
    ),
    (
        # Test Carbon Copy with bad email
        'mailtos://user:pass@example.com?smtp=smtp.example.com'
        '&name=l2g&cc=noreply@example.com,@', {
            'instance': email.NotifyEmail,
        },
    ),
    (
        # Test Blind Carbon Copy with bad email
        'mailtos://user:pass@example.com?smtp=smtp.example.com'
        '&name=l2g&bcc=noreply@example.com,@', {
            'instance': email.NotifyEmail,
        },
    ),
    (
        # Test Reply To
        'mailtos://user:pass@example.com?smtp=smtp.example.com'
        '&name=l2g&reply=test@example.com,test2@example.com', {
            'instance': email.NotifyEmail,
        },
    ),
    (
        # Test Reply To with bad email
        'mailtos://user:pass@example.com?smtp=smtp.example.com'
        '&name=l2g&reply=test@example.com,@', {
            'instance': email.NotifyEmail,
        },
    ),
    # headers
    ('mailto://user:pass@localhost.localdomain'
        '?+X-Customer-Campaign-ID=Apprise', {
            'instance': email.NotifyEmail,
        }),
    # No Password
    ('mailtos://user:@nuxref.com', {
        'instance': email.NotifyEmail,
    }),
    # Invalid From Address; but just gets put as the from name instead
    # Hence the below generats From: "@ <user@nuxref.com>"
    ('mailtos://user:pass@nuxref.com?from=@', {
        'instance': email.NotifyEmail,
    }),
    # Invalid From Address
    ('mailtos://nuxref.com?user=&pass=.', {
        'instance': TypeError,
    }),
    # Invalid To Address is accepted, but we won't be able to properly email
    # using the notify() call
    ('mailtos://user:pass@nuxref.com?to=@', {
        'instance': email.NotifyEmail,
        'response': False,
    }),
    # Valid URL, but can't structure a proper email
    ('mailtos://nuxref.com?user=%20"&pass=.', {
        'instance': TypeError,
    }),
    # Invalid From (and To) Address
    ('mailtos://nuxref.com?to=test', {
        'instance': TypeError,
    }),
    # Invalid Secure Mode
    ('mailtos://user:pass@example.com?mode=notamode', {
        'instance': TypeError,
    }),
    # STARTTLS flag checking
    ('mailtos://user:pass@gmail.com?mode=starttls', {
        'instance': email.NotifyEmail,
        # Our expected url(privacy=True) startswith() response:
        'privacy_url': 'mailtos://user:****@gmail.com',
    }),
    # SSL flag checking
    ('mailtos://user:pass@gmail.com?mode=ssl', {
        'instance': email.NotifyEmail,
    }),
    # Can make a To address using what we have (l2g@nuxref.com)
    ('mailtos://nuxref.com?user=l2g&pass=.', {
        'instance': email.NotifyEmail,
        # Our expected url(privacy=True) startswith() response:
        'privacy_url': 'mailtos://l2g:****@nuxref.com',
    }),
    ('mailto://user:pass@localhost:2525', {
        'instance': email.NotifyEmail,
        # Throws a series of connection and transfer exceptions when this flag
        # is set and tests that we gracfully handle them
        'test_smtplib_exceptions': True,
    }),
    # Use of both 'name' and 'from' together; these are synonymous
    ('mailtos://user:pass@nuxref.com?'
     'from=jack@gmail.com&name=Jason<jason@gmail.com>', {
         'instance': email.NotifyEmail}),
    # Test no auth at all
    ('mailto://localhost?from=test@example.com&to=test@example.com', {
        'instance': email.NotifyEmail,
        'privacy_url': 'mailto://localhost',
    }),
    # Test multi-emails where some are bad
    ('mailto://user:pass@localhost/test@example.com/test2@/$@!/', {
        'instance': email.NotifyEmail,
        'privacy_url': 'mailto://user:****@localhost/'
    }),
    ('mailto://user:pass@localhost/?bcc=test2@,$@!/', {
        'instance': email.NotifyEmail,
    }),
    ('mailto://user:pass@localhost/?cc=test2@,$@!/', {
        'instance': email.NotifyEmail,
    }),
    ('mailto://user:pass@localhost/?reply=test2@,$@!/', {
        'instance': email.NotifyEmail,
    }),
)


@mock.patch('smtplib.SMTP')
@mock.patch('smtplib.SMTP_SSL')
def test_plugin_email(mock_smtp, mock_smtpssl):
    """
    NotifyEmail() General Checks

    """

    # iterate over our dictionary and test it out
    for (url, meta) in TEST_URLS:

        # Our expected instance
        instance = meta.get('instance', None)

        # Our expected server objects
        self = meta.get('self', None)

        # Our expected Query response (True, False, or exception type)
        response = meta.get('response', True)

        # Our expected privacy url
        # Don't set this if don't need to check it's value
        privacy_url = meta.get('privacy_url')

        test_smtplib_exceptions = meta.get(
            'test_smtplib_exceptions', False)

        # Our mock of our socket action
        mock_socket = mock.Mock()
        mock_socket.starttls.return_value = True
        mock_socket.login.return_value = True

        # Create a mock SMTP Object
        mock_smtp.return_value = mock_socket
        mock_smtpssl.return_value = mock_socket

        if test_smtplib_exceptions:
            # Handle exception testing; first we turn the boolean flag ito
            # a list of exceptions
            test_smtplib_exceptions = (
                smtplib.SMTPHeloError(
                    0, 'smtplib.SMTPHeloError() not handled'),
                smtplib.SMTPException(
                    0, 'smtplib.SMTPException() not handled'),
                RuntimeError(
                    0, 'smtplib.HTTPError() not handled'),
                smtplib.SMTPRecipientsRefused(
                    'smtplib.SMTPRecipientsRefused() not handled'),
                smtplib.SMTPSenderRefused(
                    0, 'smtplib.SMTPSenderRefused() not handled',
                    'addr@example.com'),
                smtplib.SMTPDataError(
                    0, 'smtplib.SMTPDataError() not handled'),
                smtplib.SMTPServerDisconnected(
                    'smtplib.SMTPServerDisconnected() not handled'),
            )

        try:
            obj = Apprise.instantiate(url, suppress_exceptions=False)

            if obj is None:
                # We're done (assuming this is what we were expecting)
                assert instance is None
                continue

            if instance is None:
                # Expected None but didn't get it
                print('%s instantiated %s (but expected None)' % (
                    url, str(obj)))
                assert False

            assert isinstance(obj, instance)

            if isinstance(obj, NotifyBase):
                # We loaded okay; now lets make sure we can reverse this url
                assert isinstance(obj.url(), str)

                # Get our URL Identifier
                assert isinstance(obj.url_id(), str)

                # Verify we can acquire a target count as an integer
                assert isinstance(len(obj), int)

                # Test url() with privacy=True
                assert isinstance(
                    obj.url(privacy=True), str)

                # Some Simple Invalid Instance Testing
                assert instance.parse_url(None) is None
                assert instance.parse_url(object) is None
                assert instance.parse_url(42) is None

                if privacy_url:
                    # Assess that our privacy url is as expected
                    assert obj.url(privacy=True).startswith(privacy_url)

                # Instantiate the exact same object again using the URL from
                # the one that was already created properly
                obj_cmp = Apprise.instantiate(obj.url())

                # Our object should be the same instance as what we had
                # originally expected above.
                if not isinstance(obj_cmp, NotifyBase):
                    # Assert messages are hard to trace back with the way
                    # these tests work. Just printing before throwing our
                    # assertion failure makes things easier to debug later on
                    print('TEST FAIL: {} regenerated as {}'.format(
                        url, obj.url()))
                    assert False

                # Verify there is no change from the old and the new
                assert len(obj) == len(obj_cmp), (
                    '%d targets found in %s, But %d targets found in %s'
                    % (len(obj), obj.url(privacy=True), len(obj_cmp),
                       obj_cmp.url(privacy=True)))

            if self:
                # Iterate over our expected entries inside of our object
                for key, val in self.items():
                    # Test that our object has the desired key
                    assert hasattr(key, obj)
                    assert getattr(key, obj) == val

            try:
                if test_smtplib_exceptions is False:
                    # Verify we can acquire a target count as an integer
                    targets = len(obj)

                    # check that we're as expected
                    assert obj.notify(
                        title='test', body='body',
                        notify_type=NotifyType.INFO) == response

                    if response:
                        # If we successfully got a response, there must have
                        # been at least 1 target present
                        assert targets > 0

                else:
                    for exception in test_smtplib_exceptions:
                        mock_socket.sendmail.side_effect = exception
                        try:
                            assert obj.notify(
                                title='test', body='body',
                                notify_type=NotifyType.INFO) is False

                        except AssertionError:
                            # Don't mess with these entries
                            raise

                        except Exception:
                            # We can't handle this exception type
                            raise

            except AssertionError:
                # Don't mess with these entries
                print('%s AssertionError' % url)
                raise

            except Exception as e:
                # Check that we were expecting this exception to happen
                if not isinstance(e, response):
                    raise

        except AssertionError:
            # Don't mess with these entries
            print('%s AssertionError' % url)
            raise

        except Exception as e:
            # Handle our exception
            if instance is None:
                print('%s generated %s' % (url, str(e)))
                raise

            if not isinstance(e, instance):
                print('%s Exception (expected %s); got %s' % (
                    url, str(instance), str(e)))
                raise


@mock.patch('smtplib.SMTP')
@mock.patch('smtplib.SMTP_SSL')
def test_plugin_email_webbase_lookup(mock_smtp, mock_smtpssl):
    """
    NotifyEmail() Web Based Lookup Tests

    """

    # Insert a test email at the head of our table
    email.templates.EMAIL_TEMPLATES = (
        (
            # Testing URL
            'Testing Lookup',
            re.compile(r'^(?P<id>[^@]+)@(?P<domain>l2g\.com)$', re.I),
            {
                'port': 123,
                'smtp_host': 'smtp.l2g.com',
                'secure': True,
                'login_type': (email.WebBaseLogin.USERID, )
            },
        ),
    ) + email.templates.EMAIL_TEMPLATES

    obj = Apprise.instantiate(
        'mailto://user:pass@l2g.com', suppress_exceptions=True)

    assert isinstance(obj, email.NotifyEmail)
    assert len(obj.targets) == 1
    assert (False, 'user@l2g.com') in obj.targets
    assert obj.from_addr[0] == obj.app_id
    assert obj.from_addr[1] == 'user@l2g.com'
    assert obj.password == 'pass'
    assert obj.user == 'user'
    assert obj.secure is True
    assert obj.port == 123
    assert obj.smtp_host == 'smtp.l2g.com'

    # We get the same results if an email is identified as the username
    # because the USERID variable forces that we can't use an email
    obj = Apprise.instantiate(
        'mailto://_:pass@l2g.com?user=user@test.com', suppress_exceptions=True)
    assert obj.user == 'user'


@mock.patch('smtplib.SMTP')
def test_plugin_email_smtplib_init_fail(mock_smtplib):
    """
    NotifyEmail() Test exception handling when calling smtplib.SMTP()

    """

    obj = Apprise.instantiate(
        'mailto://user:pass@gmail.com', suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    # Support Exception handling of smtplib.SMTP
    mock_smtplib.side_effect = RuntimeError('Test')

    assert obj.notify(
        body='body', title='test', notify_type=NotifyType.INFO) is False

    # A handled and expected exception
    mock_smtplib.side_effect = smtplib.SMTPException('Test')
    assert obj.notify(
        body='body', title='test', notify_type=NotifyType.INFO) is False


@mock.patch('smtplib.SMTP')
def test_plugin_email_smtplib_send_okay(mock_smtplib):
    """
    NotifyEmail() Test a successfully sent email

    """

    # Defaults to HTML
    obj = Apprise.instantiate(
        'mailto://user:pass@gmail.com', suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    # Support an email simulation where we can correctly quit
    mock_smtplib.starttls.return_value = True
    mock_smtplib.login.return_value = True
    mock_smtplib.sendmail.return_value = True
    mock_smtplib.quit.return_value = True

    assert obj.notify(
        body='body', title='test', notify_type=NotifyType.INFO) is True

    # Set Text
    obj = Apprise.instantiate(
        'mailto://user:pass@gmail.com?format=text', suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    assert obj.notify(
        body='body', title='test', notify_type=NotifyType.INFO) is True

    # Create an apprise object to work with as well
    a = Apprise()
    assert a.add('mailto://user:pass@gmail.com?format=text')

    # Send Attachment with success
    attach = os.path.join(TEST_VAR_DIR, 'apprise-test.gif')
    assert obj.notify(
        body='body', title='test', notify_type=NotifyType.INFO,
        attach=attach) is True

    # same results happen from our Apprise object
    assert a.notify(body='body', title='test', attach=attach) is True

    # test using an Apprise Attachment object
    assert obj.notify(
        body='body', title='test', notify_type=NotifyType.INFO,
        attach=AppriseAttachment(attach)) is True

    # same results happen from our Apprise object
    assert a.notify(
        body='body', title='test', attach=AppriseAttachment(attach)) is True

    max_file_size = AttachBase.max_file_size
    # Now do a case where the file can't be sent

    AttachBase.max_file_size = 1
    assert obj.notify(
        body='body', title='test', notify_type=NotifyType.INFO,
        attach=attach) is False

    # same results happen from our Apprise object
    assert a.notify(body='body', title='test', attach=attach) is False

    # Restore value
    AttachBase.max_file_size = max_file_size


@mock.patch('smtplib.SMTP')
def test_plugin_email_smtplib_send_multiple_recipients(mock_smtplib):
    """
    Verify that NotifyEmail() will use a single SMTP session for submitting
    multiple emails.
    """

    # Defaults to HTML
    obj = Apprise.instantiate(
        'mailto://user:pass@mail.example.org?'
        'to=foo@example.net,bar@example.com&'
        'cc=baz@example.org&bcc=qux@example.org', suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    assert obj.notify(
        body='body', title='test', notify_type=NotifyType.INFO) is True

    assert mock_smtplib.mock_calls == [
        mock.call('mail.example.org', 25, None, timeout=15),
        mock.call().login('user', 'pass'),
        mock.call().sendmail(
            'user@mail.example.org',
            ['foo@example.net', 'baz@example.org', 'qux@example.org'],
            mock.ANY),
        mock.call().sendmail(
            'user@mail.example.org',
            ['bar@example.com', 'baz@example.org', 'qux@example.org'],
            mock.ANY),
        mock.call().quit(),
    ]

    # No from= used in the above
    assert re.match(r'.*from=.*', obj.url()) is None
    # No mode= as this isn't a secure connection
    assert re.match(r'.*mode=.*', obj.url()) is None
    # No smtp= as the SMTP server is the same as the hostname in this case
    assert re.match(r'.*smtp=.*', obj.url()) is None
    # URL is assembled based on provided user
    assert re.match(
        r'^mailto://user:pass\@mail.example.org/.*', obj.url()) is not None

    # Verify our added emails are still part of the URL
    assert re.match(r'.*/foo%40example.net[/?].*', obj.url()) is not None
    assert re.match(r'.*/bar%40example.com[/?].*', obj.url()) is not None

    assert re.match(r'.*bcc=qux%40example.org.*', obj.url()) is not None
    assert re.match(r'.*cc=baz%40example.org.*', obj.url()) is not None


@mock.patch('smtplib.SMTP')
def test_plugin_email_smtplib_internationalization(mock_smtp):
    """
    NotifyEmail() Internationalization Handling

    """

    # Defaults to HTML
    obj = Apprise.instantiate(
        'mailto://user:pass@gmail.com?name=Например%20так',
        suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    class SMTPMock:
        def sendmail(self, *args, **kwargs):
            """
            over-ride sendmail calls so we can check our our
            internationalization formatting went
            """

            match_subject = re.search(
                r'\n?(?P<line>Subject: (?P<subject>(.+?)))\n(?:[a-z0-9-]+:)',
                args[2], re.I | re.M | re.S)
            assert match_subject is not None

            match_from = re.search(
                r'^(?P<line>From: (?P<name>.+) <(?P<email>[^>]+)>)$',
                args[2], re.I | re.M)
            assert match_from is not None

            # Verify our output was correctly stored
            assert match_from.group('email') == 'user@gmail.com'

            assert decode_header(match_from.group('name'))[0][0]\
                .decode('utf-8') == 'Например так'

            assert decode_header(match_subject.group('subject'))[0][0]\
                .decode('utf-8') == 'دعونا نجعل العالم مكانا أفضل.'

        # Dummy Function
        def quit(self, *args, **kwargs):
            return True

        # Dummy Function
        def starttls(self, *args, **kwargs):
            return True

        # Dummy Function
        def login(self, *args, **kwargs):
            return True

    # Prepare our object we will test our generated email against
    mock_smtp.return_value = SMTPMock()

    # Further test encoding through the message content as well
    assert obj.notify(
        # Google Translated to Arabic: "Let's make the world a better place."
        title='دعونا نجعل العالم مكانا أفضل.',
        # Google Translated to Hungarian: "One line of code at a time.'
        body='Egy sor kódot egyszerre.',
        notify_type=NotifyType.INFO) is True


def test_plugin_email_url_escaping():
    """
    NotifyEmail() Test that user/passwords are properly escaped from URL

    """
    # quote(' %20')
    passwd = '%20%2520'

    # Basically we want to check that ' ' equates to %20 and % equates to %25
    # So the above translates to ' %20' (a space in front of %20).  We want
    # to verify the handling of the password escaping and when it happens.
    # a very bad response would be '  ' (double space)
    obj = email.NotifyEmail.parse_url(
        'mailto://user:{}@gmail.com?format=text'.format(passwd))

    assert isinstance(obj, dict)
    assert 'password' in obj

    # Escaping doesn't happen at this stage because we want to leave this to
    # the plugins discretion
    assert obj.get('password') == '%20%2520'

    obj = Apprise.instantiate(
        'mailto://user:{}@gmail.com?format=text'.format(passwd),
        suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    # The password is escaped only 'once'
    assert obj.password == ' %20'


def test_plugin_email_url_variations():
    """
    NotifyEmail() Test URL variations to ensure parsing is correct

    """
    # Test variations of username required to be an email address
    # user@example.com
    obj = Apprise.instantiate(
        'mailto://{user}:{passwd}@example.com?smtp=example.com'.format(
            user='apprise%40example21.ca',
            passwd='abcd123'),
        suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    assert obj.password == 'abcd123'
    assert obj.user == 'apprise@example21.ca'

    # No from= used in the above
    assert re.match(r'.*from=.*', obj.url()) is None
    # No mode= as this isn't a secure connection
    assert re.match(r'.*mode=.*', obj.url()) is None
    # No smtp= as the SMTP server is the same as the hostname in this case
    # even though it was explicitly specified
    assert re.match(r'.*smtp=.*', obj.url()) is None
    # URL is assembled based on provided user
    assert re.match(
        r'^mailto://apprise:abcd123\@example.com/.*', obj.url()) is not None

    # test username specified in the url body (as an argument)
    # this always over-rides the entry at the front of the url
    obj = Apprise.instantiate(
        'mailto://_:{passwd}@example.com?user={user}'.format(
            user='apprise%40example21.ca',
            passwd='abcd123'),
        suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    assert obj.password == 'abcd123'
    assert obj.user == 'apprise@example21.ca'

    # No from= used in the above
    assert re.match(r'.*from=.*', obj.url()) is None
    # No mode= as this isn't a secure connection
    assert re.match(r'.*mode=.*', obj.url()) is None
    # No smtp= as the SMTP server is the same as the hostname in this case
    assert re.match(r'.*smtp=.*', obj.url()) is None
    # URL is assembled based on provided user
    assert re.match(
        r'^mailto://apprise:abcd123\@example.com/.*', obj.url()) is not None

    # test user and password specified in the url body (as an argument)
    # this always over-rides the entries at the front of the url
    obj = Apprise.instantiate(
        'mailtos://_:_@example.com?user={user}&pass={passwd}'.format(
            user='apprise%40example21.ca',
            passwd='abcd123'),
        suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    assert obj.password == 'abcd123'
    assert obj.user == 'apprise@example21.ca'
    assert len(obj.targets) == 1
    assert (False, 'apprise@example.com') in obj.targets
    assert obj.from_addr[0] == obj.app_id
    assert obj.from_addr[1] == 'apprise@example.com'
    assert obj.targets[0][0] is False
    assert obj.targets[0][1] == obj.from_addr[1]

    # No from= used in the above
    assert re.match(r'.*from=.*', obj.url()) is None
    # Default mode is starttls
    assert re.match(r'.*mode=starttls.*', obj.url()) is not None
    # No smtp= as the SMTP server is the same as the hostname in this case
    assert re.match(r'.*smtp=.*', obj.url()) is None
    # URL is assembled based on provided user
    assert re.match(
        r'^mailtos://apprise:abcd123\@example.com/.*', obj.url()) is not None

    # test user and password specified in the url body (as an argument)
    # this always over-rides the entries at the front of the url
    # this is similar to the previous test except we're only specifying
    # this information in the kwargs
    obj = Apprise.instantiate(
        'mailto://example.com?user={user}&pass={passwd}'.format(
            user='apprise%40example21.ca',
            passwd='abcd123'),
        suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    assert obj.password == 'abcd123'
    assert obj.user == 'apprise@example21.ca'
    assert len(obj.targets) == 1
    assert (False, 'apprise@example.com') in obj.targets
    assert obj.from_addr[0] == obj.app_id
    assert obj.from_addr[1] == 'apprise@example.com'
    assert obj.targets[0][0] is False
    assert obj.targets[0][1] == obj.from_addr[1]
    assert obj.smtp_host == 'example.com'

    # No from= used in the above
    assert re.match(r'.*from=.*', obj.url()) is None
    # No mode= as this isn't a secure connection
    assert re.match(r'.*mode=.*', obj.url()) is None
    # No smtp= as the SMTP server is the same as the hostname in this case
    assert re.match(r'.*smtp=.*', obj.url()) is None
    # URL is assembled based on provided user
    assert re.match(
        r'^mailto://apprise:abcd123\@example.com/.*', obj.url()) is not None

    # test a complicated example
    obj = Apprise.instantiate(
        'mailtos://{user}:{passwd}@{host}:{port}'
        '?smtp={smtp_host}&format=text&from=Charles<{this}>&to={that}'.format(
            user='apprise%40example21.ca',
            passwd='abcd123',
            host='example.com',
            port=1234,
            this='from@example.jp',
            that='to@example.jp',
            smtp_host='smtp.example.edu'),
        suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    assert obj.password == 'abcd123'
    assert obj.user == 'apprise@example21.ca'
    assert obj.host == 'example.com'
    assert obj.port == 1234
    assert obj.smtp_host == 'smtp.example.edu'
    assert len(obj.targets) == 1
    assert (False, 'to@example.jp') in obj.targets
    assert obj.from_addr[0] == 'Charles'
    assert obj.from_addr[1] == 'from@example.jp'
    assert re.match(
        r'.*from=Charles\+%3Cfrom%40example.jp%3E.*', obj.url()) is not None

    # Test Tagging under various urll encodings
    for toaddr in ('/john.smith+mytag@domain.com',
                   '?to=john.smith+mytag@domain.com',
                   '/john.smith%2Bmytag@domain.com',
                   '?to=john.smith%2Bmytag@domain.com'):

        obj = Apprise.instantiate(
            'mailto://user:pass@domain.com{}'.format(toaddr))
        assert isinstance(obj, email.NotifyEmail)
        assert obj.password == 'pass'
        assert obj.user == 'user'
        assert obj.host == 'domain.com'
        assert obj.from_addr[0] == obj.app_id
        assert obj.from_addr[1] == 'user@domain.com'
        assert len(obj.targets) == 1
        assert obj.targets[0][0] is False
        assert obj.targets[0][1] == 'john.smith+mytag@domain.com'


def test_plugin_email_dict_variations():
    """
    NotifyEmail() Test email dictionary variations to ensure parsing is correct

    """
    # Test variations of username required to be an email address
    # user@example.com
    obj = Apprise.instantiate({
        'schema': 'mailto',
        'user': 'apprise@example.com',
        'password': 'abd123',
        'host': 'example.com'}, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)


@mock.patch('smtplib.SMTP_SSL')
@mock.patch('smtplib.SMTP')
def test_plugin_email_url_parsing(mock_smtp, mock_smtp_ssl):
    """
    NotifyEmail() Test email url parsing

    """

    response = mock.Mock()
    mock_smtp_ssl.return_value = response
    mock_smtp.return_value = response

    # Test variations of username required to be an email address
    # user@example.com; we also test an over-ride port on a template driven
    # mailto:// entry
    results = email.NotifyEmail.parse_url(
        'mailtos://user:pass123@hotmail.com:444'
        '?to=user2@yahoo.com&name=test%20name')
    assert isinstance(results, dict)
    assert 'test name' == results['from_addr']
    assert 'user' == results['user']
    assert 444 == results['port']
    assert 'hotmail.com' == results['host']
    assert 'pass123' == results['password']
    assert 'user2@yahoo.com' in results['targets']

    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 1
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 1
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1
    # Store our Sent Arguments
    # Syntax is:
    #  sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
    #             [0]        [1]     [2]
    _from = response.sendmail.call_args[0][0]
    _to = response.sendmail.call_args[0][1]
    _msg = response.sendmail.call_args[0][2]
    assert _from == 'user@hotmail.com'
    assert isinstance(_to, list)
    assert len(_to) == 1
    assert _to[0] == 'user2@yahoo.com'
    assert _msg.split('\n')[-3] == 'test'

    # Our URL port was over-ridden (on template) to use 444
    # We can verify that this was correctly saved
    assert obj.url().startswith(
        'mailtos://user:pass123@hotmail.com:444/user2%40yahoo.com')
    assert 'mode=starttls' in obj.url()
    assert 'smtp=smtp-mail.outlook.com' in obj.url()

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    # The below switches the `name` with the `to` to verify the results
    # are the same; it also verfies that the mode gets changed to SSL
    # instead of STARTTLS
    results = email.NotifyEmail.parse_url(
        'mailtos://user:pass123@hotmail.com?smtp=override.com'
        '&name=test%20name&to=user2@yahoo.com&mode=ssl')
    assert isinstance(results, dict)
    assert 'test name' == results['from_addr']
    assert 'user' == results['user']
    assert 'hotmail.com' == results['host']
    assert 'pass123' == results['password']
    assert 'user2@yahoo.com' in results['targets']
    assert 'ssl' == results['secure_mode']
    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 1
    assert response.starttls.call_count == 0
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1
    # Store our Sent Arguments
    # Syntax is:
    #  sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
    #             [0]        [1]     [2]
    _from = response.sendmail.call_args[0][0]
    _to = response.sendmail.call_args[0][1]
    _msg = response.sendmail.call_args[0][2]
    assert _from == 'user@hotmail.com'
    assert isinstance(_to, list)
    assert len(_to) == 1
    assert _to[0] == 'user2@yahoo.com'
    assert _msg.split('\n')[-3] == 'test'

    user, pw = response.login.call_args[0]
    # the SMTP Server was ovr
    assert pw == 'pass123'
    assert user == 'user'

    assert obj.url().startswith(
        'mailtos://user:pass123@hotmail.com/user2%40yahoo.com')
    # Test that our template over-ride worked
    assert 'mode=ssl' in obj.url()
    assert 'smtp=override.com' in obj.url()
    # No reply address specified
    assert 'reply=' not in obj.url()

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    #
    # Test outlook/hotmail lookups
    #
    results = email.NotifyEmail.parse_url(
        'mailtos://user:pass123@hotmail.com')
    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)
    assert obj.smtp_host == 'smtp-mail.outlook.com'
    # No entries in the reply_to
    assert not obj.reply_to

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 1
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 1
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1

    user, pw = response.login.call_args[0]
    assert pw == 'pass123'
    assert user == 'user@hotmail.com'

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    results = email.NotifyEmail.parse_url(
        'mailtos://user:pass123@outlook.com')
    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)
    assert obj.smtp_host == 'smtp.outlook.com'
    # No entries in the reply_to
    assert not obj.reply_to

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 1
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 1
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1

    user, pw = response.login.call_args[0]
    assert pw == 'pass123'
    assert user == 'user@outlook.com'

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    results = email.NotifyEmail.parse_url(
        'mailtos://user:pass123@outlook.com.au')
    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)
    assert obj.smtp_host == 'smtp.outlook.com'
    # No entries in the reply_to
    assert not obj.reply_to

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 1
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 1
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1

    user, pw = response.login.call_args[0]
    assert pw == 'pass123'
    assert user == 'user@outlook.com.au'

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    # Consisitency Checks
    results = email.NotifyEmail.parse_url(
        'mailtos://outlook.com?smtp=smtp.outlook.com'
        '&user=user@outlook.com&pass=app.pw')
    obj1 = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj1, email.NotifyEmail)
    assert obj1.smtp_host == 'smtp.outlook.com'
    assert obj1.user == 'user@outlook.com'
    assert obj1.password == 'app.pw'
    assert obj1.secure_mode == 'starttls'
    assert obj1.port == 587

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 0
    assert obj1.notify("test") is True
    assert mock_smtp.call_count == 1
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 1
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1

    user, pw = response.login.call_args[0]
    assert pw == 'app.pw'
    assert user == 'user@outlook.com'

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    results = email.NotifyEmail.parse_url(
        'mailtos://user:app.pw@outlook.com')
    obj2 = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj2, email.NotifyEmail)
    assert obj2.smtp_host == obj1.smtp_host
    assert obj2.user == obj1.user
    assert obj2.password == obj1.password
    assert obj2.secure_mode == obj1.secure_mode
    assert obj2.port == obj1.port

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 0
    assert obj2.notify("test") is True
    assert mock_smtp.call_count == 1
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 1
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1

    user, pw = response.login.call_args[0]
    assert pw == 'app.pw'
    assert user == 'user@outlook.com'

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    results = email.NotifyEmail.parse_url(
        'mailto://user:pass@comcast.net')
    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)
    assert obj.smtp_host == 'smtp.comcast.net'
    assert obj.user == 'user@comcast.net'
    assert obj.password == 'pass'
    assert obj.secure_mode == 'ssl'
    assert obj.port == 465

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 1
    assert response.starttls.call_count == 0
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1

    user, pw = response.login.call_args[0]
    assert pw == 'pass'
    assert user == 'user@comcast.net'

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    results = email.NotifyEmail.parse_url(
        'mailtos://user:pass123@live.com')
    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)
    # No entries in the reply_to
    assert not obj.reply_to

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 1
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 1
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1

    user, pw = response.login.call_args[0]
    assert pw == 'pass123'
    assert user == 'user@live.com'

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    results = email.NotifyEmail.parse_url(
        'mailtos://user:pass123@hotmail.com')
    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)
    # No entries in the reply_to
    assert not obj.reply_to

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 1
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 1
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1

    user, pw = response.login.call_args[0]
    assert pw == 'pass123'
    assert user == 'user@hotmail.com'

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    #
    # Test Port Over-Riding
    #
    results = email.NotifyEmail.parse_url(
        "mailtos://abc:password@xyz.cn:465?"
        "smtp=smtp.exmail.qq.com&mode=ssl")
    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    # Verify our over-rides are in place
    assert obj.smtp_host == 'smtp.exmail.qq.com'
    assert obj.port == 465
    assert obj.from_addr[0] == obj.app_id
    assert obj.from_addr[1] == 'abc@xyz.cn'
    assert obj.secure_mode == 'ssl'
    # No entries in the reply_to
    assert not obj.reply_to

    # No from= used in the above
    assert re.match(r'.*from=.*', obj.url()) is None
    # No Our secure connection is SSL
    assert re.match(r'.*mode=ssl.*', obj.url()) is not None
    # No smtp= as the SMTP server is the same as the hostname in this case
    assert re.match(r'.*smtp=smtp.exmail.qq.com.*', obj.url()) is not None
    # URL is assembled based on provided user (:465 is dropped because it
    # is a default port when using xyz.cn)
    assert re.match(
        r'^mailtos://abc:password@xyz.cn/.*', obj.url()) is not None

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 1
    assert response.starttls.call_count == 0
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1

    user, pw = response.login.call_args[0]
    assert pw == 'password'
    assert user == 'abc'

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    results = email.NotifyEmail.parse_url(
        "mailtos://abc:password@xyz.cn?"
        "smtp=smtp.exmail.qq.com&mode=ssl&port=465")
    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    # Verify our over-rides are in place
    assert obj.smtp_host == 'smtp.exmail.qq.com'
    assert obj.port == 465
    assert obj.from_addr[0] == obj.app_id
    assert obj.from_addr[1] == 'abc@xyz.cn'
    assert obj.secure_mode == 'ssl'
    # No entries in the reply_to
    assert not obj.reply_to

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 1
    assert response.starttls.call_count == 0
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1

    user, pw = response.login.call_args[0]
    assert pw == 'password'
    assert user == 'abc'

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    #
    # Test Reply-To Email
    #
    results = email.NotifyEmail.parse_url(
        "mailtos://user:pass@example.com?reply=noreply@example.com")
    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)
    # Verify our over-rides are in place
    assert obj.smtp_host == 'example.com'
    assert obj.from_addr[0] == obj.app_id
    assert obj.from_addr[1] == 'user@example.com'
    assert obj.secure_mode == 'starttls'
    assert obj.url().startswith(
        'mailtos://user:pass@example.com')
    # Test that our template over-ride worked
    assert 'reply=noreply%40example.com' in obj.url()

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 1
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 1
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1

    user, pw = response.login.call_args[0]
    assert pw == 'pass'
    assert user == 'user'

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    #
    # Test Reply-To Email with Name Inline
    #
    results = email.NotifyEmail.parse_url(
        "mailtos://user:pass@example.com?reply=Chris<noreply@example.ca>")
    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)
    # Verify our over-rides are in place
    assert obj.smtp_host == 'example.com'
    assert obj.from_addr[0] == obj.app_id
    assert obj.from_addr[1] == 'user@example.com'
    assert obj.secure_mode == 'starttls'
    assert obj.url().startswith(
        'mailtos://user:pass@example.com')
    # Test that our template over-ride worked
    assert 'reply=Chris+%3Cnoreply%40example.ca%3E' in obj.url()

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 1
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 1
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1

    user, pw = response.login.call_args[0]
    assert pw == 'pass'
    assert user == 'user'

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    # Fast Mail Handling

    # Test variations of username required to be an email address
    # user@example.com; we also test an over-ride port on a template driven
    # mailto:// entry
    results = email.NotifyEmail.parse_url(
        'mailto://fastmail.com/?to=hello@concordium-explorer.nl'
        '&user=joe@mydomain.nl&pass=abc123'
        '&from=Concordium Explorer Bot<bot@concordium-explorer.nl>')
    assert isinstance(results, dict)
    assert 'Concordium Explorer Bot<bot@concordium-explorer.nl>' == \
        results['from_addr']
    assert 'joe@mydomain.nl' == results['user']
    assert results['port'] is None
    assert 'fastmail.com' == results['host']
    assert 'abc123' == results['password']
    assert 'hello@concordium-explorer.nl' in results['targets']

    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 1
    assert response.starttls.call_count == 0
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1
    # Store our Sent Arguments
    # Syntax is:
    #  sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
    #             [0]        [1]     [2]
    _from = response.sendmail.call_args[0][0]
    _to = response.sendmail.call_args[0][1]
    _msg = response.sendmail.call_args[0][2]
    assert _from == 'bot@concordium-explorer.nl'
    assert isinstance(_to, list)
    assert len(_to) == 1
    assert _to[0] == 'hello@concordium-explorer.nl'
    assert _msg.split('\n')[-3] == 'test'

    user, pw = response.login.call_args[0]
    assert pw == 'abc123'
    assert user == 'joe@mydomain.nl'

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    # Issue github.com/caronc/apprise/issue/1040
    #  mailto://fastmail.com?user=username@customdomain.com \
    #          &to=username@customdomain.com&pass=password123
    #
    # should just have to be written like (to= omitted)
    #  mailto://fastmail.com?user=username@customdomain.com&pass=password123
    #
    results = email.NotifyEmail.parse_url(
        'mailto://fastmail.com?user=username@customdomain.com'
        '&pass=password123')
    assert isinstance(results, dict)
    assert 'username@customdomain.com' == results['user']
    assert results['from_addr'] == ''
    assert results['port'] is None
    assert 'fastmail.com' == results['host']
    assert 'password123' == results['password']
    assert results['smtp_host'] == ''

    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)
    # During instantiation, our variables get detected
    assert obj.smtp_host == 'smtp.fastmail.com'
    assert obj.from_addr == ['Apprise', 'username@customdomain.com']
    assert obj.host == 'customdomain.com'
    # detected from
    assert (False, 'username@customdomain.com') in obj.targets

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 1
    assert response.starttls.call_count == 0
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1
    # Store our Sent Arguments
    # Syntax is:
    #  sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
    #             [0]        [1]     [2]
    _from = response.sendmail.call_args[0][0]
    _to = response.sendmail.call_args[0][1]
    _msg = response.sendmail.call_args[0][2]
    assert _from == 'username@customdomain.com'
    assert isinstance(_to, list)
    assert len(_to) == 1
    assert _to[0] == 'username@customdomain.com'
    assert _msg.split('\n')[-3] == 'test'

    user, pw = response.login.call_args[0]
    assert pw == 'password123'
    assert user == 'username@customdomain.com'

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    # Similar test as above, just showing that we can over-ride the From=
    # with these custom URLs as well and not require a full email
    results = email.NotifyEmail.parse_url(
        'mailto://fastmail.com?user=username@customdomain.com'
        '&pass=password123&from=Custom')
    assert isinstance(results, dict)
    assert 'username@customdomain.com' == results['user']
    assert results['from_addr'] == 'Custom'
    assert results['port'] is None
    assert 'fastmail.com' == results['host']
    assert 'password123' == results['password']
    assert results['smtp_host'] == ''

    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)
    # During instantiation, our variables get detected
    assert obj.smtp_host == 'smtp.fastmail.com'
    assert obj.from_addr == ['Custom', 'username@customdomain.com']
    assert obj.host == 'customdomain.com'
    # detected from
    assert (False, 'username@customdomain.com') in obj.targets

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 1
    assert response.starttls.call_count == 0
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1
    # Store our Sent Arguments
    # Syntax is:
    #  sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
    #             [0]        [1]     [2]
    _from = response.sendmail.call_args[0][0]
    _to = response.sendmail.call_args[0][1]
    _msg = response.sendmail.call_args[0][2]
    assert _from == 'username@customdomain.com'
    assert isinstance(_to, list)
    assert len(_to) == 1
    assert _to[0] == 'username@customdomain.com'
    assert _msg.split('\n')[-3] == 'test'

    user, pw = response.login.call_args[0]
    assert pw == 'password123'
    assert user == 'username@customdomain.com'

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    # Issue github.com/caronc/apprise/issue/941

    # mail domain = mail-domain.com
    # host domain = domain.subdomain.com
    # PASSWORD needs to be fetched since a user= was provided
    #  - this is an edge case that is tested here
    results = email.NotifyEmail.parse_url(
        'mailtos://PASSWORD@domain.subdomain.com:587?'
        'user=admin@mail-domain.com&to=mail@mail-domain.com')
    assert isinstance(results, dict)
    # From_Addr could not be detected at this stage, but will be
    # handled during instantiation
    assert '' == results['from_addr']
    assert 'admin@mail-domain.com' == results['user']
    assert results['port'] == 587
    assert 'domain.subdomain.com' == results['host']
    assert 'PASSWORD' == results['password']
    assert 'mail@mail-domain.com' in results['targets']

    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    # Not that our from_address takes on 'admin@domain.subdomain.com'
    assert obj.from_addr == ['Apprise', 'admin@domain.subdomain.com']

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 1
    assert response.starttls.call_count == 1
    assert mock_smtp_ssl.call_count == 0
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1
    # Store our Sent Arguments
    # Syntax is:
    #  sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
    #             [0]        [1]     [2]
    _from = response.sendmail.call_args[0][0]
    _to = response.sendmail.call_args[0][1]
    _msg = response.sendmail.call_args[0][2]
    assert _from == 'admin@domain.subdomain.com'
    assert isinstance(_to, list)
    assert len(_to) == 1
    assert _to[0] == 'mail@mail-domain.com'
    assert _msg.split('\n')[-3] == 'test'

    user, pw = response.login.call_args[0]
    assert user == 'admin@mail-domain.com'
    assert pw == 'PASSWORD'


@mock.patch('smtplib.SMTP_SSL')
@mock.patch('smtplib.SMTP')
def test_plugin_email_plus_in_toemail(mock_smtp, mock_smtp_ssl):
    """
    NotifyEmail() support + in To Email address

    """

    response = mock.Mock()
    mock_smtp_ssl.return_value = response
    mock_smtp.return_value = response

    # We want to test the case where a + is found in the To address; we want to
    # ensure that it is supported
    results = email.NotifyEmail.parse_url(
        'mailtos://user:pass123@gmail.com'
        '?to=Plus Support<test+notification@gmail.com>')
    assert isinstance(results, dict)
    assert 'user' == results['user']
    assert 'gmail.com' == results['host']
    assert 'pass123' == results['password']
    assert results['port'] is None
    assert 'Plus Support<test+notification@gmail.com>' in results['targets']

    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    assert len(obj.targets) == 1
    assert ('Plus Support', 'test+notification@gmail.com') in obj.targets
    assert obj.smtp_host == 'smtp.gmail.com'
    assert obj.from_addr == ['Apprise', 'user@gmail.com']
    assert obj.host == 'gmail.com'

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 1
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 1
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1
    # Store our Sent Arguments
    # Syntax is:
    #  sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
    #             [0]        [1]     [2]
    _from = response.sendmail.call_args[0][0]
    _to = response.sendmail.call_args[0][1]
    _msg = response.sendmail.call_args[0][2]
    assert _from == 'user@gmail.com'
    assert isinstance(_to, list)
    assert len(_to) == 1
    assert _to[0] == 'test+notification@gmail.com'
    assert _msg.split('\n')[-3] == 'test'

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    #
    # Perform the same test where the To field jsut contains the + in the
    # address
    #
    results = email.NotifyEmail.parse_url(
        'mailtos://user:pass123@gmail.com'
        '?to=test+notification@gmail.com')
    assert isinstance(results, dict)
    assert 'user' == results['user']
    assert 'gmail.com' == results['host']
    assert 'pass123' == results['password']
    assert results['port'] is None
    assert 'test+notification@gmail.com' in results['targets']

    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    assert len(obj.targets) == 1
    assert (False, 'test+notification@gmail.com') in obj.targets

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 1
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 1
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1
    # Store our Sent Arguments
    # Syntax is:
    #  sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
    #             [0]        [1]     [2]
    _from = response.sendmail.call_args[0][0]
    _to = response.sendmail.call_args[0][1]
    _msg = response.sendmail.call_args[0][2]
    assert _from == 'user@gmail.com'
    assert isinstance(_to, list)
    assert len(_to) == 1
    assert _to[0] == 'test+notification@gmail.com'
    assert _msg.split('\n')[-3] == 'test'

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    #
    # Perform the same test where the To field is in the URL itself
    #
    results = email.NotifyEmail.parse_url(
        'mailtos://user:pass123@gmail.com'
        '/test+notification@gmail.com')
    assert isinstance(results, dict)
    assert 'user' == results['user']
    assert 'gmail.com' == results['host']
    assert 'pass123' == results['password']
    assert results['port'] is None
    assert 'test+notification@gmail.com' in results['targets']

    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    assert len(obj.targets) == 1
    assert (False, 'test+notification@gmail.com') in obj.targets

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert obj.notify("test") is True
    assert mock_smtp.call_count == 1
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 1
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1
    # Store our Sent Arguments
    # Syntax is:
    #  sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
    #             [0]        [1]     [2]
    _from = response.sendmail.call_args[0][0]
    _to = response.sendmail.call_args[0][1]
    _msg = response.sendmail.call_args[0][2]
    assert _from == 'user@gmail.com'
    assert isinstance(_to, list)
    assert len(_to) == 1
    assert _to[0] == 'test+notification@gmail.com'
    assert _msg.split('\n')[-3] == 'test'


@mock.patch('smtplib.SMTP_SSL')
@mock.patch('smtplib.SMTP')
def test_plugin_email_formatting_990(mock_smtp, mock_smtp_ssl):
    """
    NotifyEmail() GitHub Issue 990
    https://github.com/caronc/apprise/issues/990
    Email formatting not working correctly

    """

    response = mock.Mock()
    mock_smtp_ssl.return_value = response
    mock_smtp.return_value = response

    results = email.NotifyEmail.parse_url(
        'mailtos://mydomain.com?smtp=mail.local.mydomain.com'
        '&user=noreply@mydomain.com&pass=mypassword'
        '&from=noreply@mydomain.com&to=me@mydomain.com&mode=ssl&port=465')

    assert isinstance(results, dict)
    assert 'noreply@mydomain.com' == results['user']
    assert 'mydomain.com' == results['host']
    assert 'mail.local.mydomain.com' == results['smtp_host']
    assert 'mypassword' == results['password']
    assert 'ssl' == results['secure_mode']
    assert '465' == results['port']
    assert 'me@mydomain.com' in results['targets']

    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail)

    assert len(obj.targets) == 1
    assert (False, 'me@mydomain.com') in obj.targets


def test_plugin_email_variables_1087():
    """
    NotifyEmail() GitHub Issue 1087
    https://github.com/caronc/apprise/issues/1087
    Email variables reported not working correctly

    """

    # Valid Configuration
    result, _ = ConfigBase.config_parse(cleandoc("""
    #
    # Test Email Parsing
    #
    urls:
      - mailtos://alt.lan/:
        - user: testuser@alt.lan
          pass: xxxxXXXxxx
          smtp: smtp.alt.lan
          to: alteriks@alt.lan
    """), asset=AppriseAsset())

    assert isinstance(result, list)
    assert len(result) == 1

    email = result[0]
    assert email.from_addr == ['Apprise', 'testuser@alt.lan']
    assert email.user == 'testuser@alt.lan'
    assert email.smtp_host == 'smtp.alt.lan'
    assert email.targets == [(False, 'alteriks@alt.lan')]
    assert email.password == 'xxxxXXXxxx'

    # Valid Configuration
    result, _ = ConfigBase.config_parse(cleandoc("""
    #
    # Test Email Parsing where qsd over-rides all
    #
    urls:
      - mailtos://alt.lan/?pass=abcd&user=joe@alt.lan:
        - user: testuser@alt.lan
          pass: xxxxXXXxxx
          smtp: smtp.alt.lan
          to: alteriks@alt.lan
    """), asset=AppriseAsset())

    assert isinstance(result, list)
    assert len(result) == 1

    email = result[0]
    assert email.from_addr == ['Apprise', 'joe@alt.lan']
    assert email.user == 'joe@alt.lan'
    assert email.smtp_host == 'smtp.alt.lan'
    assert email.targets == [(False, 'alteriks@alt.lan')]
    assert email.password == 'abcd'


@mock.patch('smtplib.SMTP_SSL')
@mock.patch('smtplib.SMTP')
def test_plugin_host_detection_from_source_email(mock_smtp, mock_smtp_ssl):
    """
    NotifyEmail() Discord Issue reporting that the following did not work:
     mailtos://?smtp=mobile.charter.net&pass=password&user=name@spectrum.net

    """

    response = mock.Mock()
    mock_smtp_ssl.return_value = response
    mock_smtp.return_value = response

    results = email.NotifyEmail.parse_url(
        'mailtos://spectrum.net?smtp=mobile.charter.net'
        '&pass=password&user=name@spectrum.net')

    assert isinstance(results, dict)
    assert 'name@spectrum.net' == results['user']
    assert 'spectrum.net' == results['host']
    assert 'mobile.charter.net' == results['smtp_host']
    assert 'password' == results['password']

    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail) is True

    assert len(obj.targets) == 1
    assert (False, 'name@spectrum.net') in obj.targets
    assert obj.from_addr[0] == obj.app_id
    assert obj.from_addr[1] == 'name@spectrum.net'
    assert obj.password == 'password'
    assert obj.user == 'name@spectrum.net'
    assert obj.secure is True
    assert obj.port == 587
    assert obj.smtp_host == 'mobile.charter.net'

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert obj.notify('body', 'title') is True

    assert mock_smtp.call_count == 1
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 1
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1
    # Store our Sent Arguments
    # Syntax is:
    #  sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
    #             [0]        [1]     [2]
    _from = response.sendmail.call_args[0][0]
    _to = response.sendmail.call_args[0][1]
    _msg = response.sendmail.call_args[0][2]
    assert _from == 'name@spectrum.net'
    assert isinstance(_to, list)
    assert len(_to) == 1
    assert _to[0] == 'name@spectrum.net'
    assert _msg.split('\n')[-3] == 'body'

    #
    # Now let's do a shortened version of the same URL where the host isn't
    # specified but is parseable from he user login
    #
    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    results = email.NotifyEmail.parse_url(
        'mailtos://?smtp=mobile.charter.net'
        '&pass=password&user=name@spectrum.net')

    assert isinstance(results, dict)
    assert 'name@spectrum.net' == results['user']
    assert '' == results['host']  # No hostname defined; it's detected later
    assert 'mobile.charter.net' == results['smtp_host']
    assert 'password' == results['password']

    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail) is True

    assert len(obj.targets) == 1
    assert (False, 'name@spectrum.net') in obj.targets
    assert obj.from_addr[0] == obj.app_id
    assert obj.from_addr[1] == 'name@spectrum.net'
    assert obj.password == 'password'
    assert obj.user == 'name@spectrum.net'
    assert obj.secure is True
    assert obj.port == 587
    assert obj.smtp_host == 'mobile.charter.net'

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert obj.notify('body', 'title') is True

    assert mock_smtp.call_count == 1
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 1
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1
    # Store our Sent Arguments
    # Syntax is:
    #  sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
    #             [0]        [1]     [2]
    _from = response.sendmail.call_args[0][0]
    _to = response.sendmail.call_args[0][1]
    _msg = response.sendmail.call_args[0][2]
    assert _from == 'name@spectrum.net'
    assert isinstance(_to, list)
    assert len(_to) == 1
    assert _to[0] == 'name@spectrum.net'
    assert _msg.split('\n')[-3] == 'body'

    #
    # Now let's do a shortened version of the same URL where the host isn't
    # specified but is parseable from he user login
    #
    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    results = email.NotifyEmail.parse_url(
        'mailtos://?smtp=mobile.charter.net'
        '&pass=password&user=userid-without-domain')

    assert isinstance(results, dict)
    assert 'userid-without-domain' == results['user']
    assert '' == results['host']  # No hostname defined
    assert 'mobile.charter.net' == results['smtp_host']
    assert 'password' == results['password']

    with pytest.raises(TypeError):
        # We will fail
        Apprise.instantiate(results, suppress_exceptions=False)

    #
    # Now support target emails in place of the hostname
    #

    mock_smtp.reset_mock()
    mock_smtp_ssl.reset_mock()
    response.reset_mock()

    results = email.NotifyEmail.parse_url(
        'mailtos://John Doe<john%40yahoo.ca>?smtp=mobile.charter.net'
        '&pass=password&user=name@spectrum.net')

    assert isinstance(results, dict)
    assert 'name@spectrum.net' == results['user']
    assert '' == results['host']  # No hostname defined; it's detected later
    assert 'mobile.charter.net' == results['smtp_host']
    assert 'password' == results['password']

    obj = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(obj, email.NotifyEmail) is True

    assert len(obj.targets) == 1
    assert ('John Doe', 'john@yahoo.ca') in obj.targets
    assert obj.from_addr[0] == obj.app_id
    assert obj.from_addr[1] == 'name@spectrum.net'
    assert obj.password == 'password'
    assert obj.user == 'name@spectrum.net'
    assert obj.secure is True
    assert obj.port == 587
    assert obj.smtp_host == 'mobile.charter.net'

    assert mock_smtp.call_count == 0
    assert mock_smtp_ssl.call_count == 0
    assert obj.notify('body', 'title') is True

    assert mock_smtp.call_count == 1
    assert mock_smtp_ssl.call_count == 0
    assert response.starttls.call_count == 1
    assert response.login.call_count == 1
    assert response.sendmail.call_count == 1
    # Store our Sent Arguments
    # Syntax is:
    #  sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
    #             [0]        [1]     [2]
    _from = response.sendmail.call_args[0][0]
    _to = response.sendmail.call_args[0][1]
    _msg = response.sendmail.call_args[0][2]
    assert _from == 'name@spectrum.net'
    assert isinstance(_to, list)
    assert len(_to) == 1
    assert _to[0] == 'john@yahoo.ca'
    assert _msg.split('\n')[-3] == 'body'


@mock.patch('smtplib.SMTP_SSL')
@mock.patch('smtplib.SMTP')
def test_plugin_email_by_ipaddr_1113(mock_smtp, mock_smtp_ssl):
    """
    NotifyEmail() GitHub Issue 1113
    https://github.com/caronc/apprise/issues/1113
    Email with ip addresses not working

    """

    response = mock.Mock()
    mock_smtp_ssl.return_value = response
    mock_smtp.return_value = response

    results = email.NotifyEmail.parse_url(
        'mailto://10.0.0.195:25/?to=alerts@example.com&'
        'from=sender@example.com')

    assert isinstance(results, dict)
    assert results['user'] is None
    assert results['password'] is None
    assert results['host'] == '10.0.0.195'
    assert results['from_addr'] == 'sender@example.com'
    assert isinstance(results['targets'], list)
    assert len(results['targets']) == 1
    assert results['targets'][0] == 'alerts@example.com'
    assert results['port'] == 25

    _email = Apprise.instantiate(results, suppress_exceptions=False)
    assert isinstance(_email, email.NotifyEmail) is True

    assert len(_email.targets) == 1
    assert (False, 'alerts@example.com') in _email.targets

    assert _email.from_addr == (False, 'sender@example.com')
    assert _email.user is None
    assert _email.password is None
    assert _email.smtp_host == '10.0.0.195'
    assert _email.port == 25
    assert _email.targets == [(False, 'alerts@example.com')]


@pytest.mark.skipif('pgpy' not in sys.modules, reason="Requires PGPy")
@mock.patch('smtplib.SMTP_SSL')
@mock.patch('smtplib.SMTP')
def test_plugin_email_pgp(mock_smtp, mock_smtpssl, tmpdir):
    """
    NotifyEmail() PGP Tests

    """
    # Our mock of our socket action
    mock_socket = mock.Mock()
    mock_socket.starttls.return_value = True
    mock_socket.login.return_value = True

    # Create a mock SMTP Object
    mock_smtp.return_value = mock_socket
    mock_smtpssl.return_value = mock_socket

    assert utils.pgp.PGP_SUPPORT is True
    utils.pgp.PGP_SUPPORT = False
    # Forces to run through section of code that produces a warning there is
    # no PGP
    obj = Apprise.instantiate('mailto://user:pass@nuxref.com?pgp=yes')
    # No PGP Support and set enabled
    assert obj.notify('test body') is False

    # Return the PGP status for remaining checks
    utils.pgp.PGP_SUPPORT = True

    # Initialize our email (no from name)
    obj = Apprise.instantiate('mailto://user2:pass@nuxref.com?pgp=yes')

    # Nothing to lookup
    assert obj.pgp.public_keyfile() is None
    assert obj.pgp.public_key() is None
    assert obj.pgp.encrypt("message") is False
    # Keys can not be generated in memory mode
    assert obj.pgp.keygen() is False

    # The reason... no location to store data
    assert obj.store.mode == PersistentStoreMode.MEMORY

    tmpdir0 = tmpdir.mkdir('tmp00')
    asset = AppriseAsset(
        storage_mode=PersistentStoreMode.FLUSH,
        storage_path=str(tmpdir0),
    )

    # Prepare PGP
    obj = Apprise.instantiate(
        'mailto://pgp:pass@nuxref.com?pgp=yes', asset=asset)
    assert obj.store.mode == PersistentStoreMode.FLUSH

    # Still no public key
    assert obj.pgp.public_key(autogen=False) is None
    assert obj.pgp.keygen() is True
    # Now we'll have a public key
    assert isinstance(obj.pgp.public_keyfile(), str)

    # Generate warning by second call
    assert obj.pgp.keygen() is True

    # Remove newly generated files
    os.unlink(os.path.join(obj.store.path, 'pgp-pub.asc'))
    os.unlink(os.path.join(obj.store.path, 'pgp-prv.asc'))
    obj = Apprise.instantiate(
        'mailto://pgp:pass@nuxref.com?pgp=yes', asset=asset)
    assert obj.store.mode == PersistentStoreMode.FLUSH
    assert obj.pgp.keygen() is True

    # Prepare PGP while providing it a key
    obj = Apprise.instantiate(
        'mailto://pgp:pass@nuxref.com?pgp=yes&pgpkey=%s' %
        obj.pgp.public_keyfile(), asset=asset)

    # keyfile Defined
    assert obj.pgp.pub_keyfile is not None

    # Get our key
    key = obj.pgp.public_key()

    # In this circumstance we can not generate a new key as the one provided
    # is immutable
    assert obj.pgp.keygen() is False

    # Our key is the same
    assert key is obj.pgp.public_key()

    tmpdir0 = tmpdir.mkdir('tmp00a')
    asset0 = AppriseAsset(
        storage_mode=PersistentStoreMode.FLUSH,
        storage_path=str(tmpdir0),
    )

    # Prepare Invalid PGP Key
    obj = Apprise.instantiate(
        'mailto://pgpX:pass@nuxref.com?pgp=yes',
        asset=asset0)

    # No keyfiles
    assert obj.pgp.pub_keyfile is None

    # Generate our keys
    assert obj.pgp.keygen() is True

    # Second call uses cache
    assert obj.pgp.keygen() is True

    # We will find our key
    key = obj.pgp.public_key()
    assert key is not None

    # Utilize force parameter
    assert obj.pgp.keygen(force=True) is True

    # Our key is new
    assert key != obj.pgp.public_key()
    assert obj.pgp.public_key() is not None

    # Prepare Invalid PGP Key
    obj = Apprise.instantiate(
        'mailto://pgp:pass@nuxref.com?pgp=yes&pgpkey=invalid',
        asset=asset)

    # Returns false
    assert obj.pgp.pub_keyfile is False
    assert obj.pgp.public_keyfile() is False

    tmpdir2 = tmpdir.mkdir('tmp02')
    asset = AppriseAsset(
        storage_mode=PersistentStoreMode.FLUSH,
        storage_path=str(tmpdir2),
    )
    obj = Apprise.instantiate(
        'mailto://chris:pass@nuxref.com?pgp=yes', asset=asset)

    assert obj.store.mode == PersistentStoreMode.FLUSH
    assert obj.pgp.keygen() is True

    # Second call uses cache
    assert obj.pgp.keygen() is True

    # We will find our key
    assert obj.pgp.public_key() is not None

    # We do this again but even when we do a requisition for a public key
    # it will generate a new pair or keys for us once it detects we don't
    # have any
    tmpdir3 = tmpdir.mkdir('tmp03')
    asset = AppriseAsset(
        storage_mode=PersistentStoreMode.FLUSH,
        storage_path=str(tmpdir3),
    )
    obj = Apprise.instantiate(
        'mailto://chris:pass@nuxref.com/user@example.com?pgp=yes', asset=asset)

    assert obj.store.mode == PersistentStoreMode.FLUSH

    # We'll have a public key object to encrypt with
    assert obj.pgp.public_key() is not None

    encrypted = obj.pgp.encrypt("hello world")
    assert encrypted.startswith('-----BEGIN PGP MESSAGE-----')
    assert encrypted.rstrip().endswith('-----END PGP MESSAGE-----')

    dir_content = os.listdir(obj.store.path)
    assert 'chris-pub.asc' in dir_content
    assert 'chris-prv.asc' in dir_content

    assert obj.pgp.public_keyfile().endswith('chris-pub.asc')

    assert obj.notify('test body') is True

    # The private key is not needed for sending the encrypted messages
    os.unlink(os.path.join(obj.store.path, 'chris-prv.asc'))
    os.rename(
        os.path.join(obj.store.path, 'chris-pub.asc'),
        os.path.join(obj.store.path, 'user@example.com-pub.asc'))

    assert obj.pgp.public_keyfile() is None
    assert obj.pgp.public_keyfile("not-reference@example.com") is None
    assert obj.pgp.public_keyfile("user@example.com")\
        .endswith('user@example.com-pub.asc')

    assert obj.pgp.public_keyfile("user@example.com")\
        .endswith('user@example.com-pub.asc')
    assert obj.pgp.public_keyfile("User@Example.com")\
        .endswith('user@example.com-pub.asc')
    assert obj.pgp.public_keyfile("unknown") is None

    shutil.copyfile(
        os.path.join(obj.store.path, 'user@example.com-pub.asc'),
        os.path.join(obj.store.path, 'user-pub.asc'),
    )

    assert obj.pgp.public_keyfile("user@example.com")\
        .endswith('user@example.com-pub.asc')
    assert obj.pgp.public_keyfile("User@Example.com")\
        .endswith('user@example.com-pub.asc')

    # Remove file
    os.unlink(os.path.join(obj.store.path, 'user@example.com-pub.asc'))
    assert obj.pgp.public_keyfile("user@example.com").endswith('user-pub.asc')
    shutil.copyfile(
        os.path.join(obj.store.path, 'user-pub.asc'),
        os.path.join(obj.store.path, 'chris-pub.asc'),
    )
    # user-pub.asc still trumps still trumps
    assert obj.pgp.public_keyfile("user@example.com").endswith('user-pub.asc')
    shutil.copyfile(
        os.path.join(obj.store.path, 'chris-pub.asc'),
        os.path.join(obj.store.path, 'chris@nuxref.com-pub.asc'),
    )
    # user-pub still trumps
    assert obj.pgp.public_keyfile("user@example.com").endswith('user-pub.asc')
    assert obj.pgp.public_keyfile("invalid@example.com")\
        .endswith('chris@nuxref.com-pub.asc')

    # remove this file
    os.unlink(os.path.join(obj.store.path, 'user-pub.asc'))

    # now we fall back to basic/default configuration
    assert obj.pgp.public_keyfile("user@example.com")\
        .endswith('chris@nuxref.com-pub.asc')
    os.unlink(os.path.join(obj.store.path, 'chris@nuxref.com-pub.asc'))
    assert obj.pgp.public_keyfile("user@example.com").endswith('chris-pub.asc')

    # Testing again
    tmpdir4 = tmpdir.mkdir('tmp04')
    asset = AppriseAsset(
        storage_mode=PersistentStoreMode.FLUSH,
        storage_path=str(tmpdir4),
    )
    obj = Apprise.instantiate(
        'mailto://chris:pass@nuxref.com/user@example.com?pgp=yes', asset=asset)

    with mock.patch('builtins.open', side_effect=FileNotFoundError):
        # can't open key
        assert obj.pgp.public_key() is None

    with mock.patch('builtins.open', side_effect=OSError):
        # can't open key
        assert obj.pgp.public_key() is None
        # Test unlink
        with mock.patch('os.unlink', side_effect=OSError):
            assert obj.pgp.public_key() is None

        # Key Generation will fail
        assert obj.pgp.keygen() is False

    with mock.patch('pgpy.PGPKey.new', side_effect=NameError):
        # Can't Generate keys
        assert obj.pgp.keygen() is False
        # can't open key
        assert obj.pgp.public_key() is None

    with mock.patch('pgpy.PGPKey.from_blob', side_effect=FileNotFoundError):
        # can't open key
        assert obj.pgp.public_key() is None

    with mock.patch('pgpy.PGPKey.from_blob', side_effect=OSError):
        # can't open key
        assert obj.pgp.public_key() is None

    # Can't encrypt key
    with mock.patch('pgpy.PGPKey.from_blob', side_effect=NameError):
        assert obj.pgp.public_key() is None

    with mock.patch('pgpy.PGPMessage.new', side_effect=NameError):
        assert obj.pgp.encrypt("message") is None
        # Attempts to encrypt a message
        assert obj.notify('test-encrypt') is False

    # Create new keys
    assert obj.pgp.keygen() is True
    with mock.patch('os.path.isfile', return_value=False):
        with mock.patch('builtins.open', side_effect=OSError):
            with mock.patch('os.unlink', return_value=None):
                assert obj.pgp.keygen() is False

    # Testing again
    tmpdir5 = tmpdir.mkdir('tmp05')
    asset = AppriseAsset(
        storage_mode=PersistentStoreMode.FLUSH,
        storage_path=str(tmpdir5),
    )
    obj = Apprise.instantiate(
        'mailto://chris:pass@nuxref.com/user@example.com?pgp=yes', asset=asset)

    # Catch edge case where we just can't generate the the key
    with mock.patch('os.path.isfile', side_effect=(
            # 5x False to skip through pgp.public_keyfile()
            False, False, False, False, False, False,
            # 1x True to pass pgp.keygen()
            True,
            # 5x False to skip through pgp.public_keyfile() second call
            False, False, False, False, False, False)):
        with mock.patch('pgpy.PGPKey.from_blob',
                        side_effect=FileNotFoundError):
            assert obj.pgp.public_key() is None

    # Corrupt Data
    tmpdir6 = tmpdir.mkdir('tmp06')
    asset = AppriseAsset(
        storage_mode=PersistentStoreMode.FLUSH,
        storage_path=str(tmpdir6),
    )
    obj = Apprise.instantiate(
        'mailto://chris:pass@nuxref.com/user@example.com?pgp=yes', asset=asset)

    shutil.copyfile(
        os.path.join(TEST_VAR_DIR, 'pgp', 'corrupt-pub.asc'),
        os.path.join(obj.store.path, 'chris-pub.asc'),
    )

    # Key is corrupted
    obj.notify('test') is False

    shutil.copyfile(
        os.path.join(TEST_VAR_DIR, 'apprise-test.jpeg'),
        os.path.join(obj.store.path, 'chris-pub.asc'),
    )

    # Key is a binary image; definitely not a valid key
    obj.notify('test') is False

    # Using a public key
    shutil.copyfile(
        os.path.join(TEST_VAR_DIR, 'pgp', 'valid-pub.asc'),
        os.path.join(obj.store.path, 'chris-pub.asc'),
    )

    # Notification goes through
    obj.notify('test') is True


@pytest.mark.skipif('pgpy' not in sys.modules, reason="Requires PGPy")
def test_plugin_email_prepare():
    """
    NotifyEmail() prepare_emails static function

    """
    with pytest.raises(AppriseException):
        # No To: provided
        for e in email.NotifyEmail.prepare_emails(
                subject="Email Subject",
                body="Email Body",
                from_addr=(None, "test@test.com"), to=[]):
            pass

    # Most basic call (a lot of defaults are used)
    _iterator = email.NotifyEmail.prepare_emails(
        subject="Email Subject",
        body="Email Body",
        from_addr=(None, "test@test.com"),
        to=[('Apprise User', 'apprise@test.com'), ])
    entries = [i for i in _iterator]
    assert len(entries) == 1


@pytest.mark.skipif('pgpy' not in sys.modules, reason="Requires PGPy")
def test_plugin_pgp(tmpdir):
    """
    Pretty Good Privacy Testing
    """

    p_obj = utils.pgp.ApprisePGPController(path=None)
    # No Path
    assert p_obj.keygen() is False
    assert p_obj.public_keyfile() is None

    p_obj = utils.pgp.ApprisePGPController(
        path=None, email='l2g@email.com')
    # No Path
    assert p_obj.keygen() is False

    tmpdir0 = tmpdir.mkdir('tmp00')
    p_obj = utils.pgp.ApprisePGPController(
        path=str(tmpdir0), email='l2g@email.com')

    # A key can be generated with a path defined
    assert p_obj.keygen() is True
    assert p_obj.public_keyfile() is not None
    # A key can be generated with a path defined
    assert p_obj.keygen(name='Apprise', force=True) is True
    assert p_obj.keygen(
        email='l2g@email.com', name='Apprise', force=True) is True

    assert utils.pgp.PGP_SUPPORT is True
    utils.pgp.PGP_SUPPORT = False

    with pytest.raises(AppriseException):
        assert p_obj.public_keyfile()

    # Return the PGP status for remaining checks
    utils.pgp.PGP_SUPPORT = True

    tmpdir1 = tmpdir.mkdir('tmp01')
    p_obj = utils.pgp.ApprisePGPController(
        path=str(tmpdir1), pub_keyfile='bad-file')
    assert p_obj.public_keyfile() is False