simple_components_4.42.0_21c00530/gnat-sockets-smtp-client.adb

   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
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
--                                                                    --
--  package                         Copyright (c)  Dmitry A. Kazakov  --
--     GNAT.Sockets.SMTP.Client                    Luebeck            --
--  Implementation                                 Summer, 2016       --
--                                                                    --
--                                Last revision :  13:13 14 Sep 2019  --
--                                                                    --
--  This  library  is  free software; you can redistribute it and/or  --
--  modify it under the terms of the GNU General Public  License  as  --
--  published by the Free Software Foundation; either version  2  of  --
--  the License, or (at your option) any later version. This library  --
--  is distributed in the hope that it will be useful,  but  WITHOUT  --
--  ANY   WARRANTY;   without   even   the   implied   warranty   of  --
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU  --
--  General  Public  License  for  more  details.  You  should  have  --
--  received  a  copy  of  the GNU General Public License along with  --
--  this library; if not, write _  the  Free  Software  Foundation,  --
--  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.    --
--                                                                    --
--  As a special exception, if other files instantiate generics from  --
--  this unit, or you link this unit with other files to produce  an  --
--  executable, this unit does not by  itself  cause  the  resulting  --
--  executable to be covered by the GNU General Public License. This  --
--  exception  does not however invalidate any other reasons why the  --
--  executable file might be covered by the GNU Public License.       --
--____________________________________________________________________--

with Ada.Characters.Latin_1;      use Ada.Characters.Latin_1;
with Ada.Exceptions;              use Ada.Exceptions;
with Ada.IO_Exceptions;           use Ada.IO_Exceptions;
with Ada.Strings.Maps.Constants;  use Ada.Strings.Maps.Constants;
with Strings_Edit;                use Strings_Edit;
with Strings_Edit.Base64;         use Strings_Edit.Base64;
with Strings_Edit.Integers;       use Strings_Edit.Integers;
with Strings_Edit.Quoted;         use Strings_Edit.Quoted;
with Strings_Edit.UTF8.Mapping;   use Strings_Edit.UTF8.Mapping;

with Ada.Numerics.Discrete_Random;
with Ada.Unchecked_Deallocation;
with GNAT.MD5;

package body GNAT.Sockets.SMTP.Client is
   use Mail_Handles;
   use Object;

   Opad           : constant Stream_Element := 16#5C#;
   Ipad           : constant Stream_Element := 16#36#;
   Encoded_Length : constant := 72;
   Chunk_Length   : constant := (Encoded_Length * 3 + 3) / 4;
   CRLF           : constant String := CR & LF;
   Colon          : constant String := ":" ;
   Dot            : constant String := "." ;
   LF_Dot         : constant String := LF & ".";
   Data_End       : constant String := CRLF & "." & CRLF;
   Multipart_End  : constant String := "--" & CRLF & Data_End;
   Boundary       : constant String :=   -- 1234567890123456
                             CRLF & CRLF & "--[message part]" & CRLF;

   package Random_UID is
      new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_64);

   Dice : Random_UID.Generator;

   procedure Free is
      new Ada.Unchecked_Deallocation
          (  Attachment_Object'Class,
             Attachment_Object_Ptr
          );
   procedure Free is
      new Ada.Unchecked_Deallocation
          (  Root_Stream_Type'Class,
             Stream_Ptr
          );
   procedure Free is
      new Ada.Unchecked_Deallocation (String, String_Ptr);

--     function "abs" (Name : String) return String is
--        Length : Natural := 0;
--     begin
--        for Index in Name'Range loop
--           case Name (Index) is
--              when 'A'..'Z' | 'a'..'z' | '0'..'9' |
--                   '-' | '_' | '.' | '!' | '~' | '*' | ''' | '(' | ')' =>
--                 Length := Length + 1;
--              when others =>
--                 Length := Length + 3;
--           end case;
--        end loop;
--        declare
--           Pointer : Integer := 1;
--           Result  : String (1..Length);
--        begin
--           for Index in Name'Range loop
--              case Name (Index) is
--                 when 'A'..'Z' | 'a'..'z' | '0'..'9' |
--                      '-' | '_' | '.' | '!' | '~' | '*' |
--                      ''' | '(' | ')' =>
--                    Result (Pointer) := Name (Index);
--                    Pointer := Pointer + 1;
--                 when others =>
--                    Result (Pointer) := '%';
--                    Pointer := Pointer + 1;
--                    Strings_Edit.Integers.Put
--                    (  Destination => Result,
--                       Pointer     => Pointer,
--                       Value       => Character'Pos (Name (Index)),
--                       Base        => 16,
--                       Field       => 2,
--                       Justify     => Right,
--                       Fill        => '0'
--                    );
--              end case;
--           end loop;
--           return Result;
--        end;
--     end "abs";

   procedure Add_Address
             (  List    : in out Mail_Address_List;
                Address : String
             )  is
      use Persistent.Catalogue;
      Text : constant String := Trim (Address);
   begin
      if Text'Length > 0 then
         Add (List.Set, Address);
      end if;
   end Add_Address;

   procedure Append
             (  Object     : in out Mail_Object;
                Attachment : Attachment_Object_Ptr
             )  is
   begin
      if Object.First = null then
         Object.First := Attachment;
      else
         Object.Last.Next := Attachment;
      end if;
      Object.Last := Attachment;
   end Append;

   procedure Attach_File
             (  Message      : in out Mail;
                Contents     : String;
                Content_Type : String := "text/plain";
                Disposition  : String := "";
                Description  : String := ""
             )  is
      Attachment : Attachment_Object_Ptr;
   begin
      if not Is_Valid (Message.Reference) then
         Raise_Exception
         (  Use_Error'Identity,
            "Attaching to an uninitialized mail message"
         );
      end if;
      declare
         Object : Mail_Object'Class renames Ptr (Message.Reference).all;
         Header : constant String :=
                           Get_Content_Type (Content_Type) &
                           Get_Content_Disposition (Disposition) &
                           Get_Content_Description (Description) &
                           "Content-Transfer-Encoding: base64" &
                           CRLF & CRLF;
      begin
         Set_MIME (Object);
         Attachment :=
            new Attachment_File
                (  Name_Length   => Contents'Length,
                   Header_Length => Header'Length
                );
         Attachment.Header := Header;
         declare
            This : Attachment_File renames
                   Attachment_File (Attachment.all);
         begin
            This.Name := Contents;
            Stream_IO.Open (This.File, Stream_IO.In_File, Contents);
            This.Open := True;
         exception
            when others =>
               Free (Attachment);
               raise;
         end;
         Append (Object, Attachment);
      end;
   end Attach_File;

   procedure Attach_Stream
             (  Message      : in out Mail;
                Contents     : access Root_Stream_Type'Class;
                Content_Type : String := "text/plain";
                Disposition  : String := "";
                Description  : String := ""
             )  is
   begin
      if not Is_Valid (Message.Reference) then
         Raise_Exception
         (  Use_Error'Identity,
            "Attaching to an uninitialized mail message"
         );
      end if;
      declare
         Object : Mail_Object'Class renames Ptr (Message.Reference).all;
      begin
         Set_MIME (Object);
         Append
         (  Object,
            Create_Stream_Attachment
            (  Contents     => Contents.all'Unchecked_Access,
               Owned        => True,
               Content_Type => Content_Type,
               Disposition  => Disposition,
               Description  => Description
         )  );
      end;
   end Attach_Stream;

   procedure Attach_Stream
             (  Message      : in out Mail;
                Contents     : in out Root_Stream_Type'Class;
                Content_Type : String := "text/plain";
                Disposition  : String := "";
                Description  : String := ""
             )  is
   begin
      if not Is_Valid (Message.Reference) then
         Raise_Exception
         (  Use_Error'Identity,
            "Attaching to an uninitialized mail message"
         );
      end if;
      declare
         Object : Mail_Object'Class renames Ptr (Message.Reference).all;
      begin
         Set_MIME (Object);
         Append
         (  Object,
            Create_Stream_Attachment
            (  Contents     => Contents'Unchecked_Access,
               Owned        => False,
               Content_Type => Content_Type,
               Disposition  => Disposition,
               Description  => Description
         )  );
      end;
   end Attach_Stream;

   procedure Attach_String
             (  Message      : in out Mail;
                Contents     : String;
                Content_Type : String := "text/plain";
                Disposition  : String := "";
                Description  : String := ""
             )  is
   begin
      if not Is_Valid (Message.Reference) then
         Raise_Exception
         (  Use_Error'Identity,
            "Attaching to an uninitialized mail message"
         );
      end if;
      declare
         Object : Mail_Object'Class renames Ptr (Message.Reference).all;
      begin
         Set_MIME (Object);
         Append
         (  Object,
            Create_String_Attachment
            (  Contents     => Contents,
               Content_Type => Content_Type,
               Disposition  => Disposition,
               Description  => Description
         )  );
      end;
   end Attach_String;

   procedure Check (Message : Mail) is
   begin
      if not Is_Valid (Message.Reference) then
         Raise_Exception (Use_Error'Identity, "Empty mail message");
      end if;
      declare
         Object : Mail_Object'Class renames
                  Ptr (Message.Reference).all;
      begin
         if Object.Next /= null then
            Raise_Exception
            (  Use_Error'Identity,
               "The mail message is already queued"
            );
         elsif (  (  Object.Contents = null
                  or else
                     Object.Contents'Length = 0
                  )
               and then
                  Object.First = null
               )  then
            Raise_Exception
            (  Use_Error'Identity,
               "Missing message body"
            );
         elsif (  Object.Texts (Mail_From) = null
               or else
                  Object.Texts (Mail_From)'Length = 0
               )  then
            Raise_Exception
            (  Use_Error'Identity,
               "Missing sender's address"
            );
         elsif (  Object.Texts (Mail_Subject) = null
               or else
                  Object.Texts (Mail_Subject)'Length = 0
               )  then
            Raise_Exception (Use_Error'Identity, "Missing subject");
         elsif Is_Empty (Object.Addresses (Mail_To)) then
            Raise_Exception
            (  Use_Error'Identity,
               "Missing recipient's address"
            );
         end if;
      end;
   end Check;

   procedure Close (Attachment : in out Attachment_Object) is
   begin
      null;
   end Close;

   procedure Close (Attachment : in out Attachment_File) is
   begin
      if Attachment.Open then
         Attachment.Open := False;
         begin
            Stream_IO.Close (Attachment.File);
         exception
            when others =>
               null;
         end;
      end if;
   end Close;

   procedure Completed (Client : in out SMTP_Client) is
   begin
      null;
   end Completed;

   procedure Connected (Client : in out SMTP_Client) is
   begin
      Client.Command        := SMTP_Greeting;
      Client.Receive_State  := Receive_Code;
      Client.Send_State     := Send_Command;
      Client.Count          := 0;
      Client.Authentication := 0;
      Client.Mail_Size      := Natural'Last;
      Client.Offered_TLS    := False;
      Client.Extensions     := (others => False);
      Connected (Connection (Client));
      Connected (Connection (Client));
   end Connected;

   function CRAM_MD5 (User, Password, Challenge : String)
      return String is
      use GNAT.MD5;

      function "xor" (Text : String; Pad : Stream_Element)
         return String is
         Result : String (Text'Range);
      begin
         for Index in Result'Range loop
            Result (Index) :=
               Character'Val (Character'Pos (Text (Index)) xor Pad);
         end loop;
         return Result;
      end "xor";

      Secret : String := (1..64 => NUL);
   begin
      if Password'Length <= Secret'Length then
         Secret (1..Password'Length) := Password;
      else
         Secret (1..16) := To_String (Digest (Password));
      end if;
      return To_Base64
             (  User
             &  ' '
             &  Digest
                (  (Secret xor Opad)
                &  To_String (Digest ((Secret xor Ipad) & Challenge))
             )  );
   end CRAM_MD5;

   function Cnonce return String is
      use Interfaces;
      use Random_UID;
      use GNAT.MD5;
      Value  : constant Unsigned_64 := Random (Dice);
      Result : constant String :=
                  (  1 => Character'Val (          Value mod 2**8),
                     2 => Character'Val ((Value / 2**8 ) mod 2**8),
                     3 => Character'Val ((Value / 2**16) mod 2**8),
                     4 => Character'Val ((Value / 2**24) mod 2**8),
                     5 => Character'Val ((Value / 2**32) mod 2**8),
                     6 => Character'Val ((Value / 2**40) mod 2**8),
                     7 => Character'Val ((Value / 2**48) mod 2**8),
                     8 => Character'Val ( Value / 2**56)
                  );
      Encode : constant String := Digest (Result);
   begin
      return Encode (Encode'First..Encode'First + 13);
   end Cnonce;

   function DIGEST_MD5
            (  Host      : String;
               User      : String;
               Password  : String;
               Challenge : String;
               Request   : String;
               Cnonce    : String
            )  return String is
      use GNAT.MD5;
      Method  : constant String := "AUTHENTICATE";
      QOP     : constant String := "auth";
      Nc      : constant String := "00000001";

      Pointer : Integer := Challenge'First;
      Topic   : SMTP_Challenge;
      From    : array (SMTP_Challenge) of Integer :=
                   (others => Challenge'First);
      To      : array (SMTP_Challenge) of Integer :=
                   (others => Challenge'First - 1);

      function Nonce return String is
      begin
         return Challenge (From (SMTP_NONCE)..To (SMTP_NONCE));
      end Nonce;

      function Realm return String is
      begin
         if From (SMTP_REALM) <= To (SMTP_REALM) then
            return Challenge (From (SMTP_REALM)..To (SMTP_REALM));
         else
            return Host;
         end if;
      end Realm;

      function URI return String is
      begin
         return Request & '/' & Realm;
      end URI;

      function A1 return String is
      begin
         if (  To_Lowercase
               (  Challenge
                  (  From (SMTP_ALGORITHM)
                  .. To (SMTP_ALGORITHM)
               )  )
            =  "md5-sess"
            )
         then
            return
            (  To_String (Digest (User & ':' & Realm & ':' & Password))
            &  ':'
            &  Nonce
            &  ':'
            &  Cnonce
            );
         else
            return User & ':' & Realm & ':' & Password;
         end if;
      end A1;

      function A2 return String is
         QOP : constant String :=
                  To_Lowercase
                  (  Challenge (From (SMTP_QOP)..To (SMTP_QOP))
                  );
      begin
         if QOP = "auth-int" or else QOP = "auth-conf" then
            return
            (  Method
            &  ':'
            &  URI
            &  ":00000000000000000000000000000000"
           );
         else
            return Method & ':' & URI;
         end if;
      end A2;

   begin
      while Pointer <= Challenge'Last loop
         Get (Challenge, Pointer);
         exit when Pointer > Challenge'Last;
         declare
            Got_It : Boolean;
         begin
            Get (Challenge, Pointer, Challenges, Topic, Got_It);
            if not Got_It then
               Raise_Exception
               (  Data_Error'Identity,
                  "Invalid digest-md5 challenge, unsupported " &
                  "topic at " &
                  Challenge (Pointer..Challenge'Last)
               );
            end if;
         end;
         Get (Challenge, Pointer);
         if Pointer > Challenge'Last or else Challenge (Pointer) /= '='
         then
            Raise_Exception
            (  Data_Error'Identity,
               "Invalid digest-md5 challenge, '=' is expected after " &
               "a keyword at " &
               Challenge (Pointer..Challenge'Last)
            );
         end if;
         Pointer := Pointer + 1;
         Get (Challenge, Pointer);
         if Pointer > Challenge'Last then
            Raise_Exception
            (  Data_Error'Identity,
               "Invalid digest-md5 challenge, topic value is " &
               "expected after equality sign at " &
               Challenge (Pointer..Challenge'Last)
            );
         end if;
         if Challenge (Pointer) = '"' then
            Pointer := Pointer + 1;
            From (Topic) := Pointer;
            while Pointer <= Challenge'Last loop
               if Challenge (Pointer) = '"' then
                  To (Topic) := Pointer - 1;
                  exit;
               end if;
               Pointer := Pointer + 1;
            end loop;
            if Pointer > Challenge'Last then
               Raise_Exception
               (  Data_Error'Identity,
                  "Invalid digest-md5 challenge, missing closing " &
                  "quotation marks"
               );
            end if;
            Pointer := Pointer + 1;
         else
            From (Topic) := Pointer;
            loop
               if Pointer > Challenge'Last then
                  To (Topic) := Pointer - 1;
                  exit;
               end if;
               case Challenge (Pointer) is
                  when ' ' | ',' | Character'Val (9) =>
                     To (Topic) := Pointer - 1;
                     exit;
                  when others =>
                     Pointer := Pointer + 1;
               end case;
            end loop;
         end if;
         Get (Challenge, Pointer);
         exit when Pointer > Challenge'Last;
         if Challenge (Pointer) /= ',' then
            Raise_Exception
            (  Data_Error'Identity,
               "Invalid digest-md5 challenge, ',' is expected at " &
               Challenge (Pointer..Challenge'Last)
            );
         end if;
         Pointer := Pointer + 1;
      end loop;
      declare
         Response : constant String :=
                       Digest
                       (  Digest (A1)
                       &  ':'
                       &  Nonce
                       &  ':'
                       &  Nc
                       &  ':'
                       &  Cnonce
                       &  ':'
                       &  QOP
                       &  ':'
                       &  Digest (A2)
                       );
      begin
         declare
            Decoded : constant String :=
               (  "charset=utf-8,"
               &  "username="""
               &  User
               &  """,realm="""
               &  Realm
               &  """,nonce="""
               &  Nonce
               &  """,nc="
               &  Nc
               &  ",cnonce="""
               &  Cnonce
               &  """,digest-uri="""
               &  URI
               &  """,response="
               &  Response
               &  ",qop="
               &  QOP
               );
         begin
            return To_Base64 (Decoded);
         end;
      end;
   end DIGEST_MD5;

   function Create
            (  From     : String;
               Subject  : String;
               To       : Mail_Address_List'Class;
               Contents : String;
               Cc       : Mail_Address_List'Class := Empty;
               Bcc      : Mail_Address_List'Class := Empty;
               Date     : Time   := Clock;
               MIME     : String := "text/plain"
            )  return Mail is
      Result : Mail;
   begin
      Set (Result.Reference, new Mail_Object);
      declare
         Object : Mail_Object'Class renames Ptr (Result.Reference).all;
      begin
         Object.Texts (Mail_From)        := new String'(Trim (From));
         Object.Addresses (Mail_To).Set  := To.Set;
         Object.Addresses (Mail_Cc).Set  := Cc.Set;
         Object.Addresses (Mail_Bcc).Set := Bcc.Set;
         Object.Texts (Mail_Subject)     := new String'(Subject);
         Object.Dates (Mail_Date)        := Date;
         if MIME'Length > 0 then
            Set_MIME (Object);
            Prepend (Object, Create_String_Attachment (Contents, MIME));
         else
            Object.Contents := new String'(Contents);
         end if;
      end;
      return Result;
   end Create;

   function Create
            (  From     : String;
               Subject  : String;
               To       : String;
               Contents : String;
               Cc       : Mail_Address_List'Class := Empty;
               Bcc      : Mail_Address_List'Class := Empty;
               Date     : Time   := Clock;
               MIME     : String := "text/plain"
            )  return Mail is
   begin
      return Create
             (  From     => From,
                Subject  => Subject,
                To       => Empty / To,
                Contents => Contents,
                Cc       => Cc,
                Bcc      => Bcc,
                Date     => Date,
                MIME     => MIME
             );
   end Create;

   function Create
            (  From     : String;
               Subject  : String;
               To       : Mail_Address_List'Class;
               Cc       : Mail_Address_List'Class := Empty;
               Bcc      : Mail_Address_List'Class := Empty;
               Date     : Time := Clock
            )  return Mail is
      Result : Mail;
   begin
      Set (Result.Reference, new Mail_Object);
      declare
         Object : Mail_Object'Class renames Ptr (Result.Reference).all;
      begin
         Object.Texts (Mail_From)        := new String'(Trim (From));
         Object.Addresses (Mail_To).Set  := To.Set;
         Object.Addresses (Mail_Cc).Set  := Cc.Set;
         Object.Addresses (Mail_Bcc).Set := Bcc.Set;
         Object.Texts (Mail_Subject)     := new String'(Subject);
         Object.Dates (Mail_Date)        := Date;
      end;
      return Result;
   end Create;

   function Create
            (  From     : String;
               Subject  : String;
               To       : String;
               Cc       : Mail_Address_List'Class := Empty;
               Bcc      : Mail_Address_List'Class := Empty;
               Date     : Time := Clock
            )  return Mail is
   begin
      return Create
             (  From     => From,
                Subject  => Subject,
                To       => Empty / To,
                Cc       => Cc,
                Bcc      => Bcc,
                Date     => Date
             );
   end Create;

   function Create_Stream_Attachment
            (  Contents     : Stream_Ptr;
               Owned        : Boolean;
               Content_Type : String := "text/plain";
               Disposition  : String := "";
               Description  : String := ""
            )  return Attachment_Object_Ptr is
      Result : Attachment_Object_Ptr;
      Header : constant String :=
                        Get_Content_Type (Content_Type) &
                        Get_Content_Disposition (Disposition) &
                        Get_Content_Description (Description) &
                        "Content-Transfer-Encoding: base64" &
                        CRLF & CRLF;
   begin
      Result := new Attachment_Stream (Header'Length);
      Result.Header := Header;
      declare
         Object : Attachment_Stream renames
                  Attachment_Stream (Result.all);
      begin
         Object.Owned  := Owned;
         Object.Stream := Contents;
      end;
      return Result;
   end Create_Stream_Attachment;

   function Create_String_Attachment
            (  Contents     : String;
               Content_Type : String := "text/plain";
               Disposition  : String := "";
               Description  : String := ""
            )  return Attachment_Object_Ptr is
      Result : Attachment_Object_Ptr;
      Header : constant String :=
                        Get_Content_Type (Content_Type) &
                        Get_Content_Disposition (Disposition) &
                        Get_Content_Description (Description) &
                        "Content-Transfer-Encoding: base64" &
                        CRLF & CRLF;
   begin
      Result := new Attachment_String
                    (  Length        => Contents'Length,
                       Header_Length => Header'Length
                    );
      Result.Header := Header;
      Attachment_String (Result.all).Buffer := Contents;
      return Result;
   end Create_String_Attachment;

   procedure Delete (Message : in out Mail_Object_Ptr) is
   begin
      if Message /= null then
         declare
            This  : Mail_Object_Ptr  := Message;
            Empty : constant Boolean := This.Next = This;
         begin
            if Empty then -- Empty queue
               Message := null;
            else
               Message := This.Next;
            end if;
            This.Previous.Next := This.Next;
            This.Next.Previous := This.Previous;
            This.Previous      := null;
            This.Next          := null;
            Release (Entity_Ptr (This));
         end;
      end if;
   end Delete;

   procedure Disconnected (Client : in out SMTP_Client) is
      This  : Mail_Object_Ptr := Client.Queue;
      Count : Natural := 0;
   begin
      if This /= null then
         loop
            Count := Count + 1;
            This  := This.Next;
            exit when This = Client.Queue;
         end loop;
         declare
            Unsent : Mail_Array (1..Count);
         begin
            for Index in Unsent'Range loop
               Unsent (Index) := (Reference => Ref (Client.Queue));
               Delete (Client.Queue);
            end loop;
            Send_Abandoned (SMTP_Client'Class (Client), Unsent);
         end;
      end if;
      Disconnected (Connection (Client));
   end Disconnected;

   procedure Do_Quit (Client : in out SMTP_Client'Class) is
   begin
      Client.Command       := SMTP_QUIT;
      Client.Send_State    := Send_Command;
      Client.Receive_State := Receive_Code;
      Client.Count         := 0;
      Send_Text (Client, "QUIT" & CRLF);
   end Do_Quit;

   procedure Elevated (Client : in out SMTP_Client) is
   begin
      Client.Command := SMTP_EHLO;
      Send_Text
      (  Client,
         (  "EHLO "
         &  Official_Name (Get_Host_By_Name (Host_Name))
         &  CRLF
      )  );
   end Elevated;

   function Empty return Mail_Address_List is
      use Persistent.Catalogue;
      Result : Mail_Address_List;
   begin
      return Result;
   end Empty;

   procedure Erase (Object : in out Mail_Object) is
   begin
      Object.Status := Mail_Pending;
      for Index in Object.Texts'Range loop
         Free (Object.Texts (Index));
      end loop;
      for Index in Object.Addresses'Range loop
         Object.Addresses (Index) := Empty;
      end loop;
      Free (Object.Contents);
      Object.Last := null;
      while Object.First /= null loop
         declare
            This : Attachment_Object_Ptr := Object.First;
         begin
            Object.First := This.Next;
            Free (This);
         end;
      end loop;
   end Erase;

   procedure Erase (Message : in out Mail) is
   begin
      if Is_Valid (Message.Reference) then
         Erase (Ptr (Message.Reference).all);
      end if;
   end Erase;

   procedure Finalize (Object : in out Mail_Object) is
   begin
      if Object.Next /= null then
         Raise_Exception
         (  Program_Error'Identity,
            "Premature destruction of a queued mail object"
         );
      end if;
      Erase (Object);
   end Finalize;

   procedure Finalize (Attachment : in out Attachment_Stream) is
   begin
      if Attachment.Owned then
         Free (Attachment.Stream);
      end if;
      Finalize (Attachment_Object (Attachment));
   end Finalize;

   procedure Finalize (Attachment : in out Attachment_File) is
   begin
      Close (Attachment);
      Finalize (Attachment_Object (Attachment));
   end Finalize;

   procedure Finalize (Client : in out SMTP_Client) is
   begin
      while Client.Queue /= null loop
         Delete (Client.Queue);
      end loop;
      Free (Client.Encoded);
      Free (Client.User);
      Free (Client.Password);
      Finalize (Connection (Client));
   end Finalize;

   function Find
            (  List    : Mail_Address_List;
               Address : String
            )  return Natural is
      use Persistent.Catalogue;
   begin
      return Find (List.Set, Trim (Address));
   end Find;

   function From_String (List : String) return Mail_Address_List is
      use Persistent.Catalogue;
      Result : Mail_Address_List;
      Start  : Integer := List'First;
   begin
      for Index in List'Range loop
         if List (Index) = ',' then
            Add_Address (Result, List (Start..Index - 1));
            Start := Index + 1;
         end if;
      end loop;
      Add_Address (Result, List (Start..List'Last));
      return Result;
   end From_String;

   function Get
            (  Message : Mail_Object'Class;
               Header  : Text_Header
            )  return String is
   begin
      if Message.Texts (Header) = null then
         return "";
      else
         return Message.Texts (Header).all;
      end if;
   end Get;

   function Get
            (  Message : Mail_Object'Class;
               Header  : List_Header
            )  return Mail_Address_List is
   begin
      return (Set => Message.Addresses (Header).Set);
   end Get;

   function Get
            (  Message : Mail_Object'Class;
               Header  : Date_Header
            )  return Time is
   begin
      return Message.Dates (Header);
   end Get;

   function Get
            (  Message : Mail;
               Header  : Text_Header
            )  return String is
   begin
      if not Is_Valid (Message.Reference) then
         return "";
      else
         return Get (Ptr (Message.Reference).all, Header);
      end if;
   end Get;

   function Get
            (  Message : Mail;
               Header  : List_Header
            )  return Mail_Address_List is
   begin
      if not Is_Valid (Message.Reference) then
         return Empty;
      else
         return Get (Ptr (Message.Reference).all, Header);
      end if;
   end Get;

   function Get
            (  Message : Mail;
               Header  : Date_Header
            )  return Time is
   begin
      if Is_Valid (Message.Reference) then
         return Get (Ptr (Message.Reference).all, Header);
      else
         Raise_Exception
         (  Constraint_Error'Identity,
            "Uninitialized object"
         );
      end if;
   end Get;

   function Get_Address
            (  List  : Mail_Address_List;
               Index : Positive
            )  return String is
      use Persistent.Catalogue;
   begin
      return Get (List.Set, Index);
   end Get_Address;

   function Get_Accepted
            (  Client : SMTP_Client
            )  return SMTP_AUTH_Mechanism is
   begin
      return Client.Supported;
   end Get_Accepted;

   function Get_Authentication
            (  Client : SMTP_Client
            )  return SMTP_AUTH_Mechanism is
   begin
      return Client.Authentication;
   end Get_Authentication;

   function Get_Content_Type (Value : String) return String is
   begin
      if Value'Length = 0 then
         return "";
      else
         return "Content-Type: " & Value & CRLF;
      end if;
   end Get_Content_Type;

   function Get_Content_Disposition (Value : String) return String is
   begin
      if Value'Length = 0 then
         return "";
      else
         return "Content-Disposition: attachment; " & Value & CRLF;
      end if;
   end Get_Content_Disposition;

   function Get_Content_Description (Value : String) return String is
   begin
      if Value'Length = 0 then
         return "";
      else
         return "Content-Description: " & Value & CRLF;
      end if;
   end Get_Content_Description;

   function Get_Enhanced (Client : SMTP_Client) return Boolean is
   begin
      return Client.Force_ESMTP;
   end Get_Enhanced;

   function Get_Extension
            (  Client    : SMTP_Client;
               Extension : SMTP_Extension
            )  return Boolean is
   begin
      return Client.Extensions (Extension);
   end Get_Extension;

   function Get_Length (List : Mail_Address_List) return Natural is
      use Persistent.Catalogue;
   begin
      return Get_Size (List.Set);
   end Get_Length;

   function Get_Mail_Size (Client : SMTP_Client) return Natural is
   begin
      return Client.Mail_Size;
   end Get_Mail_Size;

   function Get_Password (Client : SMTP_Client) return String is
   begin
      return Value (Client.Password);
   end Get_Password;

   function Get_Status (Message : Mail) return Mail_Status is
   begin
      if Is_Valid (Message.Reference) then
         return Ptr (Message.Reference).Status;
      else
         return Mail_Pending;
      end if;
   end Get_Status;

   function Get_TLS (Client : SMTP_Client) return Boolean is
   begin
      return Client.Accept_TLS;
   end Get_TLS;

   function Get_TLS_Always (Client : SMTP_Client) return Boolean is
   begin
      return Client.Force_TLS;
   end Get_TLS_Always;

   function Get_User (Client : SMTP_Client) return String is
   begin
      return Value (Client.User);
   end Get_User;

   function Image (Header : Mail_Header) return String is
   begin
      case Header is
         when Mail_Message_ID   => return "Message-ID";
         when Mail_In_Reply_To  => return "In-Reply-To";
         when Mail_Subject      => return "Subject";
         when Mail_MIME_Version => return "MIME-Version";
         when Mail_Content_Type => return "Content-Type";
         when Mail_Precedence   => return "Predecence";
         when Mail_References   => return "References";
         when Mail_Reply_To     => return "Reply-To";
         when Mail_Sender       => return "Sender";
         when Mail_Archived_At  => return "Archived-At";
         when Mail_To           => return "To";
         when Mail_From         => return "From";
         when Mail_Bcc          => return "Bcc";
         when Mail_Cc           => return "Cc";
         when Mail_Date         => return "Date";
         when Mail_Body         => return "Body";
      end case;
   end Image;

   function Image (List  : Mail_Address_List) return String is
      use Persistent.Catalogue;
      Length : Natural := 0;
   begin
      for Index in 1..Get_Size (List.Set) loop
         Length := Length + Get (List.Set, Index)'Length;
      end loop;
      if Length = 0 then
         return "";
      end if;
      declare
         Result  : String (1..Length + Get_Size (List.Set) - 1);
         Pointer : Integer := Result'First;
      begin
         for Index in 1..Get_Size (List.Set) loop
            if Index > 1 then
               Put (Result, Pointer, ",");
            end if;
            Put (Result, Pointer, Get (List.Set, Index));
         end loop;
         return Result;
      end;
   end Image;

   function Is_Empty (List : Mail_Address_List) return Boolean is
      use Persistent.Catalogue;
   begin
      return Get_Size (List.Set) = 0;
   end Is_Empty;

   function Is_In
            (  List    : Mail_Address_List;
               Address : String
            )  return Boolean is
      use Persistent.Catalogue;
   begin
      return Is_In (List.Set, Trim (Address));
   end Is_In;

   function Is_Opportunistic (Client : SMTP_Client) return Boolean is
   begin
      return True;
   end Is_Opportunistic;

   procedure On_Auth (Client : in out SMTP_Client'Class) is
   begin
      if Client.Authentication >= SMTP_DIGEST_MD5 then
         case Client.Index is
            when 1 =>
               Client.Index := 2;
               Send_Text
               (  Client,
                  (  DIGEST_MD5
                     (  Image (Client.Get_Client_Address.Addr),
                        Value (Client.User),
                        Value (Client.Password),
                        From_Base64
                        (  Client.Reply (1..Client.Pointer - 1)
                        ),
                        "smtp",
                        Cnonce
                     )
                  & CRLF
               )  );
            when others =>
               Client.Command := SMTP_MAIL;
               On_Mail (Client);
         end case;
      elsif Client.Authentication >= SMTP_CRAM_MD5 then
         case Client.Index is
            when 1 =>
               Client.Index := 2;
               Send_Text
               (  Client,
                  (  CRAM_MD5
                     (  Value (Client.User),
                        Value (Client.Password),
                        From_Base64
                        (  Client.Reply (1..Client.Pointer - 1)
                     )  )
                  & CRLF
               )  );
            when others =>
               Client.Command := SMTP_MAIL;
               On_Mail (Client);
         end case;
      elsif Client.Authentication >= SMTP_LOGIN then
         case Client.Index is
            when 1 =>
               Client.Index := 2;
               Send_Text
               (  Client,
                  To_Base64 (Value (Client.User)) & CRLF
               );
            when 2 =>
               Client.Index := 3;
               Send_Text
               (  Client,
                  To_Base64 (Value (Client.Password)) & CRLF
               );
            when others =>
               Client.Command := SMTP_MAIL;
               On_Mail (Client);
         end case;
      else -- Success
         Client.Command := SMTP_MAIL;
         On_Mail (Client);
      end if;
   end On_Auth;

   procedure On_Content_End
             (  Client  : in out SMTP_Client'Class;
                Message : in out Mail_Object'Class
             )  is
   begin
      if Message.First = null then
         Client.Send_State := Send_Data_End;
         Client.Index      := Data_End'First;
      else
         Client.Send_State := Send_Boundary_Middle;
         Client.Attachment := Message.First;
         Client.Index      := Boundary'First;
      end if;
   end On_Content_End;

   procedure On_EHLO_Response
             (  Client : in out SMTP_Client'Class;
                Reply  : String
             )  is
      Got_It  : Boolean;
      Flag    : SMTP_Extension;
      Pointer : Integer := Reply'First;
   begin
      Get (Reply, Pointer, Extensions, Flag, Got_It);
      if not Got_It then
         return; -- Ignore unrecognized
      end if;
      Client.Extensions (Flag) := True;
      case Flag is
         when SMTP_AUTH =>
            declare
               Mode : SMTP_AUTH_Mechanism;
            begin
               loop
                  Get (Reply, Pointer);
                  exit when Pointer > Reply'Last;
                  begin
                     Get (Reply, Pointer, Authentications, Mode);
                     Client.Authentication :=
                        Client.Authentication or Mode;
                  exception
                     when End_Error => -- Skip an unsupported method
                        loop
                           case Reply (Pointer) is
                              when ' ' | Character'Val (9) =>
                                 Pointer := Pointer + 1;
                                 exit;
                              when others =>
                                 Pointer := Pointer + 1;
                           end case;
                           exit when Pointer > Reply'Last;
                        end loop;
                  end;
               end loop;
            exception
               when others =>
                  null;
            end;
         when SMTP_SIZE =>
            begin
               Get (Reply, Pointer);
               Get (Reply, Pointer, Client.Mail_Size, First => 1);
            exception
               when others =>
                  Client.Mail_Size := Natural'Last;
            end;
         when SMTP_STARTTLS =>
            Client.Offered_TLS := True;
         when others =>
            null;
      end case;
   exception
      when others => -- Ignore unrecognized
         null;
   end On_EHLO_Response;

   procedure On_Greeting
             (  Client : in out SMTP_Client'Class;
                Code   : Error_Code;
                Reply  : String
             )  is
   begin
      if Client.Force_ESMTP then
         Client.ESMTP := True;
      else
         declare
            Start : Boolean := True;
         begin
            Client.ESMTP := False;
            for Index in Reply'Range loop
               if (  Start
                  and then
                     Is_Prefix ("esmtp", Reply, Index, Lower_Case_Map)
                  and then
                     (  Index + 5 > Reply'Last
                     or else
                        Reply (Index + 5) = ' '
                  )  )
               then
                  Client.ESMTP := True;
                  exit;
               end if;
               Start := Reply (Index) = ' ';
            end loop;
         end;
      end if;
      Client.Receive_State := Receive_Code;
      Client.Count := 0;
      if Client.ESMTP then
         Client.Command := SMTP_EHLO;
         Send_Text
         (  Client,
            (  "EHLO "
            &  Official_Name (Get_Host_By_Name (Host_Name))
            &  CRLF
         )  );
      else
         Client.Command := SMTP_HELO;
         Send_Text
         (  Client,
            (  "HELO "
            &  Official_Name (Get_Host_By_Name (Host_Name))
            &  CRLF
         )  );
      end if;
   end On_Greeting;

   procedure On_Mail (Client : in out SMTP_Client'Class) is
   begin
      if Client.Queue = null then
         Completed (Client);
         if Client.Queue = null then
            Do_Quit (Client);
            return;
         end if;
      elsif Client.Command = SMTP_EHLO then
         if (  (  Client.Force_TLS
               or else
                  (Client.Offered_TLS and then Client.Accept_TLS)
               )
            and then
               Is_TLS_Capable (Client.Listener.Factory.all)
            and then
               not Is_Elevated (Client)
            )
         then -- Go TLS
            Client.Command       := SMTP_STARTTLS;
            Client.Receive_State := Receive_Code;
            Client.Count         := 0;
            Send_Text (Client, "STARTTLS" & CRLF);
            return;
         else -- Use authentication
            Client.Authentication :=
               Client.Authentication and Client.Supported;
            if Client.Authentication >= SMTP_DIGEST_MD5 then
               Client.Authentication := SMTP_DIGEST_MD5;
               Client.Command := SMTP_AUTH;
               Send_Text (Client, "AUTH DIGEST-MD5" & CRLF);
               Client.Send_State    := Send_Command;
               Client.Receive_State := Receive_Code;
               Client.Count         := 0;
               Client.Index         := 1;
               return;
            elsif Client.Authentication >= SMTP_CRAM_MD5 then
               Client.Authentication := SMTP_CRAM_MD5;
               Client.Command := SMTP_AUTH;
               Send_Text (Client, "AUTH CRAM-MD5" & CRLF);
               Client.Send_State    := Send_Command;
               Client.Receive_State := Receive_Code;
               Client.Count         := 0;
               Client.Index         := 1;
               return;
            elsif Client.Authentication >= SMTP_LOGIN then
               Client.Authentication := SMTP_LOGIN;
               Client.Command := SMTP_AUTH;
               Send_Text (Client, "AUTH LOGIN" & CRLF);
               Client.Send_State    := Send_Command;
               Client.Receive_State := Receive_Code;
               Client.Count         := 0;
               Client.Index         := 1;
               return;
            elsif Client.Authentication = SMTP_PLAIN then
               Client.Command := SMTP_AUTH;
               Send_Text
               (  Client,
                  (  "AUTH PLAIN "
                  &  To_Base64
                     (  NUL
                     &  Value (Client.User) & NUL
                     &  Value (Client.Password)
                     )
                  &  CRLF
               )  );
               Client.Send_State    := Send_Command;
               Client.Receive_State := Receive_Code;
               Client.Count         := 0;
               return;
            end if;
         end if;
      end if;
      declare
         Message : Mail_Object'Class renames Client.Queue.all;
      begin
         Client.Command       := SMTP_MAIL;
         Client.Send_State    := Send_Command;
         Client.Receive_State := Receive_Code;
         Client.Count         := 0;
         Send_Text
         (  Client,
            "MAIL FROM:" & Get (Message, Mail_From) & CRLF
         );
      end;
   end On_Mail;

   procedure On_Recipient (Client : in out SMTP_Client'Class) is
   begin
      if Client.Queue = null then
         Completed (Client);
         if Client.Queue = null then
            Do_Quit (Client);
            return;
         end if;
      end if;
      declare
         Message : Mail_Object'Class renames Client.Queue.all;
         List    : Mail_Address_List;
      begin
         loop
            List := Get (Message, Client.Header);
            Client.Index := Client.Index + 1;
            if Client.Index > Get_Length (List) then
               case Client.Header is
                  when Mail_To =>
                     Client.Header := Mail_Bcc;
                     Client.Index  := 0;
                  when Mail_Bcc =>
                     Client.Header := Mail_Cc;
                     Client.Index  := 0;
                  when Mail_Cc =>
                     Client.Command       := SMTP_DATA;
                     Client.Receive_State := Receive_Code;
                     Client.Count         := 0;
                     Client.Header        := Mail_Header'First;
                     Send_Text (Client, "DATA" & CRLF);
                     return;
                  when others =>
                     Raise_Exception
                     (  Data_Error'Identity,
                        (  "Internal error, "
                        &  "wrong address type"
                     )  );
               end case;
            else
               Client.Receive_State := Receive_Code;
               Client.Count         := 0;
               Send_Text
               (  Client,
                  "RCPT TO:" & Get_Address (List, Client.Index) & CRLF
               );
               return;
            end if;
         end loop;
      end;
   end On_Recipient;

   procedure On_Reply_Error (Client : in out SMTP_Client'Class) is
   begin
      case Client.Command is
         when SMTP_HELO | SMTP_EHLO | SMTP_RSET | SMTP_Sent |
              SMTP_HELP | SMTP_NOOP | SMTP_QUIT | SMTP_AUTH |
              SMTP_STARTTLS | SMTP_Greeting =>
            Send_Error
            (  Client,
               Client.Code,
               Client.Command,
               Client.Reply (1..Client.Pointer - 1)
            );
            raise Connection_Error;
         when SMTP_MAIL | SMTP_RCPT | SMTP_DATA =>
            if Client.Queue = null then
               Send_Error
               (  Client,
                  Client.Code,
                  Client.Command,
                  Client.Reply (1..Client.Pointer - 1)
               );
               raise Connection_Error;
            else
               Client.Queue.Status := Mail_Rejected;
               Send_Error
               (  Client,
                  Client.Code,
                  Client.Command,
                  Client.Reply (1..Client.Pointer - 1),
                  (Reference => Ref (Client.Queue))
               );
               Delete (Client.Queue);
               On_Mail (Client);
            end if;
      end case;
   end On_Reply_Error;

   procedure Prepend
             (  Object     : in out Mail_Object;
                Attachment : Attachment_Object_Ptr
             )  is
   begin
      Attachment.Next := Object.First;
      if Object.First = null then
         Object.Last := Attachment;
      end if;
      Object.First := Attachment;
   end Prepend;

   procedure Read
             (  Attachment : in out Attachment_String;
                Buffer     : in out Stream_Element_Array;
                Last       : out Stream_Element_Offset
             )  is
      Size : Integer := Attachment.Length - Attachment.Index + 1;
   begin
      Last := Buffer'First - 1;
      if Size > 0 then
         if Size > Buffer'Length then
            Size := Buffer'Length;
         end if;
         for Index in Attachment.Index..Attachment.Index + Size - 1 loop
            Last := Last + 1;
            Buffer (Last) := Character'Pos (Attachment.Buffer (Index));
         end loop;
         Attachment.Index := Attachment.Index + Size;
      end if;
   end Read;

   procedure Read
             (  Attachment : in out Attachment_Stream;
                Buffer     : in out Stream_Element_Array;
                Last       : out Stream_Element_Offset
             )  is
   begin
      Read (Attachment.Stream.all, Buffer, Last);
   exception
      when End_Error =>
         Last := Buffer'First - 1;
   end Read;

   procedure Read
             (  Attachment : in out Attachment_File;
                Buffer     : in out Stream_Element_Array;
                Last       : out Stream_Element_Offset
             )  is
   begin
      Stream_IO.Read (Attachment.File, Buffer, Last);
      if Last < Buffer'First then
         Stream_IO.Close (Attachment.File);
         Attachment.Open := False;
      end if;
   exception
      when End_Error =>
         Stream_IO.Close (Attachment.File);
         Attachment.Open := False;
         Last := Buffer'First - 1;
      when Error : others =>
         Raise_Exception
         (  Data_Error'Identity,
            (  "Error reading attached file "
            &  Quote (Attachment.Name)
            &  ": "
            &  Exception_Message (Error)
         )  );
   end Read;

   procedure Received
             (  Client  : in out SMTP_Client;
                Data    : Stream_Element_Array;
                Pointer : in out Stream_Element_Offset
             )  is
   begin
      Pointer := Data'First;
      if Client.Send_State /= Send_Command then
         Raise_Exception
         (  Data_Error'Identity,
            (  "Unsolicited response while sending state is "
            &  SMTP_Send_State'Image (Client.Send_State)
         )  );
      end if;
      while Pointer <= Data'Last loop
         case Client.Receive_State is
            when Receive_Code =>
               loop
                  case Data (Pointer) is
                     when Character'Pos ('0')..Character'Pos ('9') =>
                        if Client.Count = 0 then
                           Client.Pointer := Integer (Data (Pointer))
                                           - Character'Pos ('0');
                        elsif Client.Count > 2 then
                           Raise_Exception
                           (  Data_Error'Identity,
                              "Invalid reply code, longer than 3 digits"
                           );
                        else
                           Client.Pointer := Client.Pointer * 10
                                           + Integer (Data (Pointer))
                                           - Character'Pos ('0');
                        end if;
                        Client.Count := Client.Count + 1;
                        Pointer      := Pointer + 1;
                     when Character'Pos (' ') =>
                        if Client.Count = 0 then
                           Raise_Exception
                           (  Data_Error'Identity,
                              "Missing reply code"
                           );
                        elsif Client.Pointer not in 200..554 then
                           Raise_Exception
                           (  Data_Error'Identity,
                              (  "Invalid reply code "
                              &  Image (Client.Pointer)
                              &  " not in 200..554"
                           )  );
                        end if;
                        Client.Code :=
                           (False, Reply_Code (Client.Pointer));
                        Pointer              := Pointer + 1;
                        Client.Receive_State := Receive_Class;
                        Client.End_Of_Reply  := True;
                        Client.Pointer       := 1;
                        exit;
                     when Character'Pos ('-') =>
                        if Client.Count = 0 then
                           Raise_Exception
                           (  Data_Error'Identity,
                              "Missing continuation reply code "
                           );
                        elsif Client.Pointer not in 200..554 then
                           Raise_Exception
                           (  Data_Error'Identity,
                              (  "Invalid continuation reply code "
                              &  Image (Client.Pointer)
                              &  " not in 200..554"
                           )  );
                        end if;
                        Client.Code :=
                           (False, Reply_Code (Client.Pointer));
                        Pointer              := Pointer + 1;
                        Client.Receive_State := Receive_Line;
                        Client.End_Of_Reply  := False;
                        Client.Pointer       := 1;
                        exit;
                     when others =>
                        Raise_Exception
                        (  Data_Error'Identity,
                           "Invalid reply code, not numerical"
                        );
                  end case;
                  exit when Pointer > Data'Last;
               end loop;
            when Receive_Class =>
               if (  Pointer = Data'Last
                  or else
                     Data (Pointer + 1) /= Character'Pos ('.')
                  )
               then -- Assume plain code
                  Client.Receive_State := Receive_Line;
               else
                  case Data (Pointer) is
                     when Character'Pos ('0') |
                          Character'Pos ('1') |
                          Character'Pos ('3') |
                          Character'Pos ('6')..Character'Pos ('9') =>
                        Raise_Exception
                        (  Data_Error'Identity,
                           (  "Invalid extended status code class, "
                           &  "not 2,4,5"
                        )  );
                     when Character'Pos ('2') =>
                        Client.Receive_State := Receive_Subject;
                        Client.Count         := 0;
                        Pointer              := Pointer + 1;
                        Client.Code :=
                           (True, Client.Code.Reply, (Success, 0, 0));
                     when Character'Pos ('4') =>
                        Client.Receive_State := Receive_Subject;
                        Client.Count         := 0;
                        Pointer              := Pointer + 1;
                        Client.Code :=
                           (  True,
                              Client.Code.Reply,
                              (Persistent_Transient_Failure, 0, 0)
                           );
                     when Character'Pos ('5') =>
                        Client.Receive_State := Receive_Subject;
                        Client.Count         := 0;
                        Pointer              := Pointer + 1;
                        Client.Code :=
                           (  True,
                              Client.Code.Reply,
                              (Permanent_Failure, 0, 0)
                           );
                     when others =>
                        Client.Receive_State := Receive_Line;
                  end case;
               end if;
            when Receive_Subject =>
               case Data (Pointer) is
                  when Character'Pos ('.') =>
                     if Client.Count = 0 then
                        Client.Count := 1;
                        Client.Code.Error.Subject := 0;
                     elsif Client.Count = 1 then
                        Raise_Exception
                        (  Data_Error'Identity,
                           (  "Invalid extended status code, "
                           &  "missing numeric code subject"
                        )  );
                     else
                        Client.Receive_State     := Receive_Detail;
                        Client.Count             := 0;
                        Client.Code.Error.Detail := 0;
                     end if;
                  when Character'Pos ('0')..Character'Pos ('9') =>
                     if Client.Count = 0 then
                        Raise_Exception
                        (  Data_Error'Identity,
                           (  "Invalid extended status code, "
                           &  "missing (.) after the code class"
                        )  );
                     elsif Client.Count > 3 then
                        Raise_Exception
                        (  Data_Error'Identity,
                           (  "Invalid extended status code, "
                           &  "subject is longer than 3 digits"
                        )  );
                     end if;
                     Client.Count := Client.Count + 1;
                     Client.Code.Error.Subject :=
                        (  Client.Code.Error.Subject * 10
                        +  Code_Subject
                           (  Data (Pointer)
                           -  Character'Pos ('0')
                        )  );
                  when others =>
                     Raise_Exception
                     (  Data_Error'Identity,
                        (  "Invalid extended status code subject, "
                        &  "not numeric ended by a dot (.)"
                     )  );
               end case;
               Pointer := Pointer + 1;
            when Receive_Detail =>
               case Data (Pointer) is
                  when Character'Pos ('0')..Character'Pos ('9') =>
                     if Client.Count > 3 then
                        Raise_Exception
                        (  Data_Error'Identity,
                           (  "Invalid extended status code, "
                           &  "detail is longer than 3 digits"
                        )  );
                     end if;
                     Client.Count := Client.Count + 1;
                     Client.Code.Error.Detail :=
                        (  Client.Code.Error.Detail * 10
                        +  Code_Detail
                           (  Data (Pointer)
                           -  Character'Pos ('0')
                        )  );
                     Pointer := Pointer + 1;
                  when Character'Pos (' ') =>
                     if Client.Count = 0 then
                        Raise_Exception
                        (  Data_Error'Identity,
                           (  "Invalid extended status code, "
                           &  "missing numeric code detail"
                        )  );
                     end if;
                     Pointer := Pointer + 1;
                     Client.Receive_State := Receive_Line;
                  when others =>
                     if Client.Count = 0 then
                        Raise_Exception
                        (  Data_Error'Identity,
                           (  "Invalid extended status code, "
                           &  "missing numeric code detail"
                        )  );
                     end if;
                     Client.Receive_State := Receive_Line;
               end case;
            when Receive_Line =>
               loop
                  if Data (Pointer) = Stream_Element'Val (13) then
                     Client.Receive_State := Receive_LF;
                     Pointer := Pointer + 1;
                     exit;
                  elsif Client.Pointer > Client.Reply'Last then
                     Raise_Exception
                     (  Data_Error'Identity,
                        (  "The reply line is longer than "
                        &  Image (Client.Reply_Length)
                        &  " characters"
                     )  );
                  end if;
                  Client.Reply (Client.Pointer) :=
                     Character'Val (Data (Pointer));
                  Client.Pointer := Client.Pointer + 1;
                  Pointer := Pointer + 1;
                  exit when Pointer > Data'Last;
               end loop;
            when Receive_LF =>
               if Data (Pointer) /= Stream_Element'Val (10) then
                  Raise_Exception
                  (  Data_Error'Identity,
                     (  "Response terminating <LF> is expected "
                     &  "after <CR>"
                  )  );
               end if;
               Pointer := Pointer + 1;
               Client.Receive_State := Receive_Code;
               Client.Count := 0;
               if Client.Code.Reply >= 400 then -- Fatal error
                  On_Reply_Error (Client);
               elsif not Client.End_Of_Reply then -- Multiline response
                  case Client.Command is
                     when SMTP_DATA | SMTP_HELP | SMTP_MAIL |
                          SMTP_NOOP | SMTP_RCPT | SMTP_RSET |
                          SMTP_Sent | SMTP_QUIT | SMTP_AUTH |
                          SMTP_STARTTLS | SMTP_Greeting =>
                        null;
                     when SMTP_HELO | SMTP_EHLO =>
                        On_EHLO_Response
                        (  Client,
                           Client.Reply (1..Client.Pointer - 1)
                        );
                  end case;
               else
                  case Client.Command is
                     when SMTP_Greeting =>
                        On_Greeting
                        (  Client,
                           Client.Code,
                           Client.Reply (1..Client.Pointer - 1)
                        );
                     when SMTP_Sent =>
                        Client.Queue.Status := Mail_Sent;
                        Send_Success
                        (  SMTP_Client'Class (Client),
                           (Reference => Ref (Client.Queue))
                        );
                        Delete (Client.Queue);
                        On_Mail (Client);
                     when SMTP_HELO =>
                        On_Mail (Client);
                     when SMTP_EHLO =>
                        On_Mail (Client);
                     when SMTP_AUTH =>
                        On_Auth (Client);
                     when SMTP_MAIL =>
                        Client.Command := SMTP_RCPT;
                        Client.Header  := Mail_To;
                        Client.Index   := 0;
                        On_Recipient (Client);
                     when SMTP_RCPT =>
                        On_Recipient (Client);
                     when SMTP_STARTTLS =>
                        Create_Transport (Client);
                        Client.Command := SMTP_EHLO;
                        Client.Count := 0;
                        return;
                     when SMTP_DATA =>
                        Client.Send_State := Send_Header;
                        Client.Header     := Mail_Header'First;
                        Client.Index      := 1;
                        Sent (Client);
                     when SMTP_RSET =>
                        null;
                     when SMTP_HELP =>
                        null;
                     when SMTP_NOOP =>
                        null;
                     when SMTP_QUIT =>
                        Raise_Exception
                        (  Connection_Error'Identity,
                           "End of SMPT connection"
                        );
                  end case;
               end if;
         end case;
      end loop;
   exception
      when Connection_Error =>
         Shutdown (Client);
         raise;
      when Data_Error =>
         raise;
      when Error : others =>
         Raise_Exception
         (  Data_Error'Identity,
            Exception_Message (Error)
         );
   end Received;

   procedure Remove
             (  List    : in out Mail_Address_List;
                Address : String
             )  is
      use Persistent.Catalogue;
   begin
      Remove (List.Set, Trim (Address));
   end Remove;

   procedure Remove
             (  List  : in out Mail_Address_List;
                Index : Positive
             )  is
      use Persistent.Catalogue;
   begin
      Remove (List.Set, Index);
   end Remove;

   procedure Send
             (  Client  : in out SMTP_Client;
                Message : Mail
             )  is
   begin
      Check (Message);
      declare
         This : constant Mail_Object_Ptr := Ptr (Message.Reference);
      begin
         This.Status := Mail_Pending;
         if Client.Queue = null then -- Empty messages queue
            Client.Queue  := This;
            This.Next     := This;
            This.Previous := This;
         else -- Add to the queue tail
            This.Next                  := Client.Queue;
            This.Previous              := Client.Queue.Previous;
            Client.Queue.Previous.Next := This;
            Client.Queue.Previous      := This;
         end if;
         Increment_Count (This.all);
      end;
   end Send;

   procedure Send
             (  Client   : in out SMTP_Client;
                Messages : Mail_Array
             )  is
   begin
      for Index in Messages'Range loop
         Check (Messages (Index));
      end loop;
      for Index in Messages'Range loop
         declare
            This : constant Mail_Object_Ptr :=
                            Ptr (Messages (Index).Reference);
         begin
            This.Status := Mail_Pending;
            if Client.Queue = null then -- Empty messages queue
               Client.Queue  := This;
               This.Next     := This;
               This.Previous := This;
            else -- Add to the queue tail
               This.Next                  := Client.Queue;
               This.Previous              := Client.Queue.Previous;
               Client.Queue.Previous.Next := This;
               Client.Queue.Previous      := This;
            end if;
            Increment_Count (This.all);
         end;
      end loop;
   end Send;

   procedure Send_Abandoned
             (  Client   : in out SMTP_Client;
                Messages : Mail_Array
             )  is
   begin
      for Index in Messages'Range loop
         Trace
         (  Client.Listener.Factory.all,
            (  "Abandoning sending the mail "
            &  Quote (Get (Messages (Index), Mail_Subject))
            &  " to: "
            &  Image (Get (Messages (Index), Mail_To))
         )  );
      end loop;
   end Send_Abandoned;

   procedure Send_Data
             (  Client : in out SMTP_Client'Class;
                Data   : Stream_Element_Array
             )  is
      Pointer : Stream_Element_Offset := Data'First;
   begin
      Send (Client, Data, Pointer);
      if Pointer < Data'Last then
         Raise_Exception
         (  Data_Error'Identity,
            (  "The output buffer is too small. At least "
            &  Image (Integer (Data'Last - Pointer))
            &  " more elements required"
         )  );
      end if;
   end Send_Data;

   procedure Send_Error
             (  Client  : in out SMTP_Client;
                Code    : Error_Code;
                Context : SMTP_Command;
                Reply   : String
             )  is
   begin
      Trace
      (  Client.Listener.Factory.all,
         "Error: " & Image (Code) & ". " & Reply
      );
   end Send_Error;

   procedure Send_Error
             (  Client  : in out SMTP_Client;
                Code    : Error_Code;
                Context : SMTP_Command;
                Reply   : String;
                Message : Mail
             )  is
   begin
      Trace
      (  Client.Listener.Factory.all,
         (  "Error: "
         &  Image (Code)
         &  ". "
         &  Reply
         &  ". While sending mail "
         &  Quote (Get (Message, Mail_Subject))
         &  " to: "
         &  Image (Get (Message, Mail_To))
      )  );
   end Send_Error;

   procedure Send_Success
             (  Client  : in out SMTP_Client;
                Message : Mail
             )  is
   begin
      Trace
      (  Client.Listener.Factory.all,
         (  "Mail "
         &  Quote (Get (Message, Mail_Subject))
         &  " successfully sent to: "
         &  Image (Get (Message, Mail_To))
      )  );
   end Send_Success;

   procedure Send_Text
             (  Client : in out SMTP_Client'Class;
                Text   : String
             )  is
      Pointer : Integer := Text'First;
   begin
      Send (Client, Text, Pointer);
      if Pointer < Text'Last then
         Raise_Exception
         (  Data_Error'Identity,
            (  "The output buffer is too small. At least "
            &  Image (Text'Last - Pointer)
            &  " more elements required"
         )  );
      end if;
   end Send_Text;

   procedure Sent (Client : in out SMTP_Client) is
   begin
      loop
         case Client.Send_State is
            when Send_Boundary_First =>
               Send (Client, Boundary (3..Boundary'Last), Client.Index);
               if Client.Index <= Boundary'Last then
                  return;
               end if;
               declare
                  Message : Mail_Object'Class renames Client.Queue.all;
               begin
                  if Message.Contents /= null then
                     Client.Send_State := Send_String_Body;
                  elsif Message.First /= null then
                     if Client.Encoded = null then
                        Client.Encoded :=
                           new String (1..Encoded_Length + 3);
                     end if;
                     Client.Send_State := Send_Content_Header;
                  else
                     Client.Send_State := Send_Boundary_Last;
                  end if;
                  Client.Index := 1;
               end;
            when Send_Boundary_Middle =>
               Send (Client, Boundary (1..2 + 2 + 16 + 2), Client.Index);
               if Client.Index <= 2 + 2 + 16 + 2 then
                  return;
               end if;
               Client.Send_State := Send_Content_Header;
               Client.Index := Client.Attachment.Header'First;
            when Send_Boundary_Last =>
               Send
               (  Client,
                  Boundary (2 + 2..2 + 2 + 16),
                  Client.Index
               );
               if Client.Index <= 2 + 2 + 16 then
                  return;
               end if;
               Client.Send_State := Send_Multipart_End;
               Client.Index      := Multipart_End'First;
            when Send_Content_Header =>
               Send
               (  Client,
                  Client.Attachment.Header,
                  Client.Index
               );
               if Client.Index <= Client.Attachment.Header'Last
               then
                  return;
               end if;
               Client.Send_State   := Send_Content;
               Client.Index        := 1;
               Client.Encoded_Last := 0;
               if Client.Encoded = null then
                  Client.Encoded := new String (1..Encoded_Length + 3);
               end if;
            when Send_Colon =>
               Send (Client, Colon, Client.Index);
               if Client.Index <= Colon'Last then
                  return;
               end if;
               Client.Send_State := Send_Value;
               Client.Index      := 1;
            when Send_Command =>
               return;
            when Send_Content =>
               loop
                  if Client.Index > Client.Encoded_Last then
                     declare -- Get a next chunk of encoded data
                        Buffer : Stream_Element_Array (1..Chunk_Length);
                        Last   : Stream_Element_Offset;
                     begin
                        Read (Client.Attachment.all, Buffer, Last);
                        if Last < Buffer'First then -- No more data
                           Close (Client.Attachment.all);
                           Client.Attachment := Client.Attachment.Next;
                           if Client.Attachment = null then
                              Client.Send_State := Send_Boundary_Last;
                           else
                              Client.Send_State := Send_Boundary_Middle;
                           end if;
                           Client.Index := 1;
                           exit;
                        end if;
                        Client.Encoded_Last := Client.Encoded'First;
                        Put
                        (  Client.Encoded.all,
                           Client.Encoded_Last,
                           To_Base64 (To_String (Buffer (1..Last)))
                        );
                        Put
                        (  Client.Encoded.all,
                           Client.Encoded_Last,
                           CRLF
                        );
                        Client.Encoded_Last := Client.Encoded_Last - 1;
                        Client.Index        := Client.Encoded'First;
                     end;
                  end if;
                  Send
                  (  Client,
                     Client.Encoded (Client.Index..Client.Encoded_Last),
                     Client.Index
                  );
                  if Client.Index <= Client.Encoded_Last then
                     return;
                  end if;
               end loop;
            when Send_Header =>
               declare
                  Message : Mail_Object'Class renames Client.Queue.all;
               begin
                  case Client.Header is
                     when Text_Header =>
                        if Message.Texts (Client.Header) = null then
                           Client.Header :=
                              Mail_Header'Val
                              (  Mail_Header'Pos (Client.Header)
                              +  1
                              );
                        else
                           declare
                              Text : constant String :=
                                     Image (Client.Header);
                           begin
                              Send (Client, Text, Client.Index);
                              if Client.Index <= Text'Last then
                                 return;
                              end if;
                              Client.Send_State := Send_Colon;
                              Client.Index      := 1;
                           end;
                        end if;
                     when List_Header =>
                        if Is_Empty
                           (  Message.Addresses (Client.Header)
                           )  then
                           Client.Header :=
                              Mail_Header'Val
                              (  Mail_Header'Pos (Client.Header)
                              +  1
                              );
                        else
                           declare
                              Text : constant String :=
                                     Image (Client.Header);
                           begin
                              Send (Client, Text, Client.Index);
                              if Client.Index <= Text'Last then
                                 return;
                              end if;
                              Client.Send_State := Send_Colon;
                              Client.Index      := 1;
                           end;
                        end if;
                     when Mail_Date =>
                        declare
                           Text : constant String :=
                                  Image (Client.Header);
                        begin
                           Send (Client, Text, Client.Index);
                           if Client.Index <= Text'Last then
                              return;
                           end if;
                           Client.Send_State := Send_Colon;
                           Client.Index      := 1;
                        end;
                     when Mail_Body =>
                        declare
                           Message : Mail_Object'Class renames
                                     Client.Queue.all;
                        begin
                           if Message.First = null then -- Single part
                              Client.Send_State := Send_CRLF;
                              Client.Index      := 1;
                           else -- Multiple parts
                              Client.Attachment := Message.First;
                              Client.Send_State := Send_Boundary_First;
                              Client.Index      := 1;
                           end if;
                        end;
                  end case;
               end;
            when Send_Value =>
               declare
                  Message : Mail_Object'Class renames Client.Queue.all;
               begin
                  case Client.Header is
                     when Text_Header =>
                        declare
                           Text : constant String :=
                                  Get (Message, Client.Header);
                        begin
                           Send (Client, Text, Client.Index);
                           if Client.Index <= Text'Last then
                              return;
                           end if;
                           Client.Send_State := Send_CRLF;
                           Client.Index      := 1;
                        end;
                     when List_Header =>
                        declare
                           Text : constant String :=
                                  Image
                                  (  Message.Addresses (Client.Header)
                                  );
                        begin
                           Send (Client, Text, Client.Index);
                           if Client.Index <= Text'Last then
                              return;
                           end if;
                           Client.Send_State := Send_CRLF;
                           Client.Index      := 1;
                        end;
                     when Mail_Date =>
                        declare
                           Text : constant String :=
                                  To_String
                                  (  Message.Dates (Client.Header)
                                  );
                        begin
                           Send (Client, Text, Client.Index);
                           if Client.Index <= Text'Last then
                               return;
                            end if;
                           Client.Send_State := Send_CRLF;
                           Client.Index      := 1;
                        end;
                      when Mail_Body =>
                         Send (Client, CRLF, Client.Index);
                         if Client.Index <= CRLF'Last then
                            return;
                         end if;
                  end case;
               end;
            when Send_CRLF =>
               Send (Client, CRLF, Client.Index);
               if Client.Index <= CRLF'Last then
                  return;
               elsif Client.Header = Mail_Body then
                  declare
                     Message : Mail_Object'Class renames
                               Client.Queue.all;
                  begin
                     if Message.Contents /= null then
                        Client.Send_State := Send_String_Body;
                     elsif Message.First /= null then
                        Client.Send_State := Send_Boundary_First;
                     else
                        Client.Send_State := Send_Data_End;
                     end if;
                     Client.Index := 1;
                  end;
               else
                  Client.Header :=
                      Mail_Header'Val
                      (  Mail_Header'Pos (Client.Header)
                      +  1
                      );
                  Client.Send_State := Send_Header;
                  Client.Index      := 1;
               end if;
            when Send_Data_End =>
               Send (Client, Data_End, Client.Index);
               if Client.Index <= Data_End'Last then
                  return;
               end if;
               Client.Receive_State := Receive_Code;
               Client.Send_State    := Send_Command;
               Client.Command       := SMTP_Sent;
               Client.Index         := 1;
               Client.Count         := 0;
            when Send_Multipart_End =>
               Send (Client, Multipart_End, Client.Index);
               if Client.Index <= Multipart_End'Last then
                  return;
               end if;
               Client.Receive_State := Receive_Code;
               Client.Send_State    := Send_Command;
               Client.Command       := SMTP_Sent;
               Client.Index         := 1;
               Client.Count         := 0;
            when Send_String_Dot =>
               declare
                  Pointer : Integer := Dot'First;
               begin
                  Send (Client, Dot, Pointer);
                  if Pointer <= Dot'Last then
                     return;
                  end if;
                  Client.Send_State := Send_String_Body;
               end;
            when Send_String_Body =>
               declare
                  Message : Mail_Object'Class renames Client.Queue.all;
                  Index   : Integer;
               begin
                  loop
                     if Client.Index > Message.Contents'Last then
                        On_Content_End (Client, Message);
                        exit;
                     end if;
                     Index := Client.Index;
                     while Index <= Message.Contents'Last loop
                        case Message.Contents (Index) is
                           when '.' =>
                              if Index = Message.Contents'First then
                                 Index := Index + 1;
                                 Client.Send_State := Send_String_Dot;
                                 exit;
                              end if;
                              Index := Index + 1;
                           when CR =>
                              Index := Index + 1;
                              if Is_Prefix
                                 (  LF_Dot,
                                    Message.Contents.all,
                                    Index
                                 )
                              then
                                 Index := Index + 2;
                                 Client.Send_State := Send_String_Dot;
                                 exit;
                              end if;
                           when others =>
                              Index := Index + 1;
                        end case;
                     end loop;
                     Send
                     (  Client,
                        Message.Contents (Client.Index..Index - 1),
                        Client.Index
                     );
                     if Client.Index < Index then
                        Client.Send_State := Send_String_Body;
                        return;
                     elsif Client.Send_State = Send_String_Dot then
                        exit;
                     end if;
                  end loop;
               end;
         end case;
      end loop;
   end Sent;

   procedure Set (Data : in out String_Ptr; Value : String) is
   begin
      if Data /= null then
         if Data.all = Value then
            return;
         end if;
         Free (Data);
      end if;
      Data := new String'(Value);
   end Set;

   procedure Set
             (  Object : in out Mail_Object;
                Header : Text_Header;
                Text   : String
             )  is
   begin
      Set (Object.Texts (Header), Text);
   end Set;

   procedure Set
             (  Message : in out Mail;
                Header  : Text_Header;
                Text    : String
             )  is
   begin
      if not Is_Valid (Message.Reference) then
         Set (Message.Reference, new Mail_Object);
      end if;
      Set (Ptr (Message.Reference).all, Header, Text);
   end Set;

   procedure Set
             (  Message : in out Mail;
                Header  : List_Header;
                List    : Mail_Address_List'Class
             )  is
      use Persistent.Catalogue;
   begin
      if not Is_Valid (Message.Reference) then
         Set (Message.Reference, new Mail_Object);
      end if;
      Ptr (Message.Reference).Addresses (Header).Set := List.Set;
   end Set;

   procedure Set
             (  Message : in out Mail;
                Header  : Date_Header;
                Date    : Time
             )  is
   begin
      if not Is_Valid (Message.Reference) then
         Set (Message.Reference, new Mail_Object);
      end if;
      Ptr (Message.Reference).Dates (Header) := Date;
   end Set;

   procedure Set_Enhanced
             (  Client   : in out SMTP_Client;
                Enhanced : Boolean
             )  is
   begin
      Client.Force_ESMTP := Enhanced;
   end Set_Enhanced;

   procedure Set_MIME (Object : in out Mail_Object'Class) is
   begin
      Set (Object, Mail_MIME_Version, "1.0");
      Set
      (  Object,
         Mail_Content_Type,
         "multipart/mixed; boundary=""" & Boundary (7..16 + 4) & """"
      );
      if Object.Contents /= null then
         Prepend
         (  Object,
            Create_String_Attachment (Object.Contents.all)
         );
         Free (Object.Contents);
      end if;
   end Set_MIME;

   procedure Set_Credentials
             (  Client   : in out SMTP_Client;
                User     : String;
                Password : String;
                Accepted : SMTP_AUTH_Mechanism :=
                           SMTP_AUTH_Mechanism'Last
             )  is
   begin
      Set (Client.User, User);
      Set (Client.Password, Password);
      Client.Supported := Accepted;
   end Set_Credentials;

   procedure Set_TLS
             (  Client : in out SMTP_Client;
                Enable : Boolean;
                Always : Boolean := False
             )  is
   begin
      Client.Accept_TLS := Enable;
      Client.Force_TLS  := Always;
   end Set_TLS;

   function Value (Text : String_Ptr) return String is
   begin
      if Text = null then
         return "";
      else
         return Text.all;
      end if;
   end Value;

   function "/" (Left, Right : String) return Mail_Address_List is
      use Persistent.Catalogue;
      Result : Mail_Address_List;
   begin
      Add_Address (Result, Left);
      Add_Address (Result, Right);
      return Result;
   end "/";

   function "/"
             (  List    : Mail_Address_List;
                Address : String
             )  return Mail_Address_List is
      use Persistent.Catalogue;
      Result : Mail_Address_List := List;
   begin
      Add_Address (Result, Address);
      return Result;
   end "/";

   function "and" (Left, Right : Mail_Address_List)
      return Mail_Address_List is
      use Persistent.Catalogue;
   begin
      return (Set => Left.Set and Right.Set);
   end "and";

   function "or" (Left, Right : Mail_Address_List)
      return Mail_Address_List is
      use Persistent.Catalogue;
   begin
      return (Set => Left.Set or Right.Set);
   end "or";

   function "xor" (Left, Right : Mail_Address_List)
      return Mail_Address_List is
      use Persistent.Catalogue;
   begin
      return (Set => Left.Set xor Right.Set);
   end "xor";

begin
   Add (Extensions, "8BITMIME",            SMTP_8BITMIME);
   Add (Extensions, "ATRN",                SMTP_ATRN);
   Add (Extensions, "AUTH",                SMTP_AUTH);
   Add (Extensions, "AUTH=",               SMTP_AUTH);
   Add (Extensions, "BINARYMIME",          SMTP_BINARYMIME);
   Add (Extensions, "CHECKPOINT",          SMTP_CHECKPOINT);
   Add (Extensions, "CHUNKING",            SMTP_CHUNKING);
   Add (Extensions, "DSN",                 SMTP_DSN);
   Add (Extensions, "ENHANCEDSTATUSCODES", SMTP_ENHANCEDSTATUSCODES);
   Add (Extensions, "ETRN",                SMTP_ETRN);
   Add (Extensions, "EXPN",                SMTP_EXPN);
   Add (Extensions, "HELP",                SMTP_HELP);
   Add (Extensions, "ONEX",                SMTP_ONEX);
   Add (Extensions, "PIPELINING",          SMTP_PIPELINING);
   Add (Extensions, "RSET",                SMTP_RSET);
   Add (Extensions, "SAML",                SMTP_SAML);
   Add (Extensions, "SEND",                SMTP_SEND);
   Add (Extensions, "SIZE",                SMTP_SIZE);
   Add (Extensions, "SMTPUTF8",            SMTP_SMTPUTF8);
   Add (Extensions, "SOML",                SMTP_SOML);
   Add (Extensions, "STARTTLS",            SMTP_STARTTLS);
   Add (Extensions, "TIME",                SMTP_TIME);
   Add (Extensions, "TLS",                 SMTP_TLS);
   Add (Extensions, "TURN",                SMTP_TURN);
   Add (Extensions, "UTF8SMTP",            SMTP_UTF8SMTP);
   Add (Extensions, "VERB",                SMTP_VERB);
   Add (Extensions, "VRFY",                SMTP_VRFY);
   Add (Extensions, "X-EXPS",              SMTP_X_EXPS);
   Add (Extensions, "X-EXPS=LOGIN",        SMTP_X_EXPS_LOGIN);
   Add (Extensions, "X-LINK2STATE",        SMTP_X_LINK2STATE);
   Add (Extensions, "X-RCPTLIMIT",         SMTP_X_RCPTLIMIT);
   Add (Extensions, "X-TURNME",            SMTP_X_TURNME);
   Add (Extensions, "XADR",                SMTP_XADR);
   Add (Extensions, "XAUD",                SMTP_XAUD);
   Add (Extensions, "XDSN",                SMTP_XDSN);
   Add (Extensions, "XEXCH50",             SMTP_XEXCH50);
   Add (Extensions, "XGEN",                SMTP_XGEN);
   Add (Extensions, "XONE",                SMTP_XONE);
   Add (Extensions, "XQUE",                SMTP_XQUE);
   Add (Extensions, "XREMOTEQUEUE",        SMTP_XREMOTEQUEUE);
   Add (Extensions, "XSTA",                SMTP_XSTA);
   Add (Extensions, "XTRN",                SMTP_XTRN);
   Add (Extensions, "XUSR",                SMTP_XUSR);
   Add (Extensions, "XVRB",                SMTP_XVRB);

   Add (Authentications, "ANONYMOUS",  SMTP_ANONYMOUS);
   Add (Authentications, "CRAM-MD5",   SMTP_CRAM_MD5);
   Add (Authentications, "DIGEST-MD5", SMTP_DIGEST_MD5);
   Add (Authentications, "LOGIN",      SMTP_LOGIN);
   Add (Authentications, "PLAIN",      SMTP_PLAIN);

   Add (Challenges, "algorithm",  SMTP_ALGORITHM);
   Add (Challenges, "charset",    SMTP_CHARSET);
   Add (Challenges, "cnonce",     SMTP_CNONCE);
   Add (Challenges, "digest-uri", SMTP_DIGEST_URI);
   Add (Challenges, "nonce",      SMTP_NONCE);
   Add (Challenges, "qop",        SMTP_QOP);
   Add (Challenges, "realm",      SMTP_REALM);

end GNAT.Sockets.SMTP.Client;