File: ipmsg.pas

package info (click to toggle)
lazarus 2.0.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 214,460 kB
  • sloc: pascal: 1,862,622; xml: 265,709; cpp: 56,595; sh: 3,008; java: 609; makefile: 535; perl: 297; sql: 222; ansic: 137
file content (3913 lines) | stat: -rw-r--r-- 126,278 bytes parent folder | download | duplicates (4)
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
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
{******************************************************************}
{*               IPMSG.PAS - MIME message classes                 *}
{******************************************************************}

{ $Id: ipmsg.pas 49494 2015-07-04 23:08:00Z juha $ }

(* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is TurboPower Internet Professional
 *
 * The Initial Developer of the Original Code is
 * TurboPower Software
 *
 * Portions created by the Initial Developer are Copyright (C) 2000-2002
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Markus Kaemmerer <mk@happyarts.de> SourceForge: mkaemmerer
 *
 * ***** END LICENSE BLOCK ***** *)

{ Global defines potentially affecting this unit }

{$I IPDEFINE.INC}

unit IpMsg;

interface

uses
  {$IFDEF IP_LAZARUS}
  LCLType,
  LCLIntf,
  LazFileUtils, LazUTF8Classes,
  {$ELSE}
  Windows,
  {$ENDIF}
  Classes,
  SysUtils,
  IpStrms,
  {$IFNDEF IP_LAZARUS}
  //IpSock, //JMN
  {$ENDIF}
  IpUtils,
  IpConst;

type
  TIpMimeEncodingMethod = (em7Bit, em8Bit, emBase64, emBinary, emBinHex,
                           emQuoted, emUUEncode, emUnknown);


{ TIpMimeEntity }
type
  TIpCodingProgressEvent = procedure(Sender : TObject; Progress : Byte;
                                     var Abort : Boolean) of object;

{Begin !!.12}
type
  TIpHeaderTypes = (htBCC, htCC, htControl, htDate, htDispositionNotify,
                    htFollowUp, htFrom, htInReplyTo, htKeywords,
                    htMessageID, htNewsgroups, htNNTPPostingHost,
                    htOrganization, htPath, htPostingHost, htReceived,
                    htReferences, htReplyTo, htReturnPath, htSender,
                    htSubject, htTo, htUserFields, htXIpro);

  TIpHeaderInfo = record
    FieldType   : TIpHeaderTypes;
    FieldString : string;
  end;

const
  IpMaxHeaders = 24;

  IpHeaderXRef : array [0..IpMaxHeaders - 1] of  TIpHeaderInfo =
    ((FieldType : htBCC;               FieldString : 'BCC'),
     (FieldType : htCC;                FieldString : 'CC'),
     (FieldType : htControl;           FieldString : 'Control: '),
     (FieldType : htDate;              FieldString : 'Date'),
     (FieldType : htDispositionNotify; FieldString : 'Disposition-Notification-To'),
     (FieldType : htFollowUp;          FieldString : 'Followup-To: '),
     (FieldType : htFrom;              FieldString : 'From'),
     (FieldType : htInReplyTo;         FieldString : 'In-Reply-To'),
     (FieldType : htKeywords;          FieldString : 'Keywords'),
     (FieldType : htMessageID;         FieldString : 'Message-ID'),
     (FieldType : htNewsgroups;        FieldString : 'Newsgroups'),
     (FieldType : htNNTPPostingHost;   FieldString : 'NNTP-Posting-Host'),
     (FieldType : htOrganization;      FieldString : 'Organization'),
     (FieldType : htPath;              FieldString : 'Path'),
     (FieldType : htPostingHost;       FieldString : 'Posting-Host'),
     (FieldType : htReceived;          FieldString : 'Received'),
     (FieldType : htReferences;        FieldString : 'References'),
     (FieldType : htReplyTo;           FieldString : 'Reply-To'),
     (FieldType : htReturnPath;        FieldString : 'Return-Path'),
     (FieldType : htSender;            FieldString : 'Sender'),
     (FieldType : htSubject;           FieldString : 'Subject'),
     (FieldType : htTo;                FieldString : 'To'),
     (FieldType : htUserFields;        FieldString : 'X-'),
     (FieldType : htXIpro;             FieldString : 'X-Ipro'));

type
  TIpHeaderCollection = class;

  TIpHeaderItem = class (TCollectionItem)
    private
      FCollection  : TIpHeaderCollection;
      FName        : string;
      FNameL       : string;
        { Lower case version of FName. Used to speed up header searches. }
      FProperty    : Boolean;                                          {!!.13}
      FValue       : TStringList;
    protected
      procedure SetName(const Name : string);
      procedure SetValue (v : TStringList);
    public
      constructor Create (Collection : TCollection); override;
      destructor Destroy; override;
    published
      property Collection : TIpHeaderCollection
               read FCollection write FCollection;
      property Name : string read FName write SetName;
      property NameL : string read FNameL;
        { Lower case version of Name property. }
      property IsProperty : Boolean read FProperty write FProperty;    {!!.13}
        { Set to True if this header is exposed via an iPRO property. }{!!.13}
      property Value : TStringList read FValue write SetValue;
  end;

  TIpHeaderCollection = class (TCollection)
    private
      FOwner : TPersistent;                                              

    protected                                                            
      function GetItem (Index : Integer) : TIpHeaderItem;
      function GetOwner : TPersistent; override;                         
      procedure SetItem (Index : Integer; Value : TIpHeaderItem);        

    public                                                               
      constructor Create (AOwner : TPersistent);                         

      {$IFNDEF VERSION5}                                                 
      procedure Delete (Item : integer);                                 
      {$ENDIF}
      function HasHeader (AName : string) : Integer;
      procedure HeaderByName (AName   : string;
                              Headers : TStringList);
      procedure LoadHeaders (AHeaderList : TStringList;                  
                             Append      : Boolean);                     

      property Items[Index : Integer] : TIpHeaderItem                    
               read GetItem write SetItem;                               
  end;                                                                   
{End !!.12}

  TIpMimeParts = class; { Forwards }

  TIpMimeEntity = class(TPersistent)
  protected {private}
    FProgress                : Byte;
    PrevProgress             : Byte;
    FMimeParts               : TIpMimeParts;
    FParentBoundary          : string;
    FBody                    : TIpAnsiTextStream;
    FEntityName              : string;
    FBoundary                : string;
    FCharacterSet            : string;
    FContentDescription      : string;
    FContentDispositionType  : string;
    FContentID               : string;
    FContentSubtype          : string;
    FContentType             : string;
    FCreationDate            : string;
    FContentTransferEncoding : TIpMimeEncodingMethod;
    FFileName                : string;
    FIsMime                  : Boolean;
    FIsMultipart             : Boolean;
    FModificationDate        : string;
    FMimeVersion             : string;
    FOnCodingProgress        : TIpCodingProgressEvent;
    FOriginalSize            : Longint;
    FParent                  : TIpMimeEntity;
    FReadDate                : string;
    FRelatedType             : string;                                 {!!.02}
    FRelatedSubtype          : string;                                 {!!.02}
    FRelatedStart            : string;                                 {!!.02}
    FRelatedStartInfo        : string;                                 {!!.02}
    FAttachmentCount         : Integer;                                {!!.12}

  protected {methods}
    procedure Clear; virtual;
    procedure ClearBodyLargeAttach(const AttachmentSize : Longint); virtual;  {!!.12}
    function  ContainsSpecialChars(const Value : string) : Boolean;    {!!.14}
    procedure DecodeContentDisposition(const aDisp : string);
    procedure DecodeContentType(const aType : string);
    function  DecodeContentTransferEncoding(const aEncoding : string) :
                                            TIpMimeEncodingMethod;
    procedure DecodeMimeHeaders(RawHeaders : TStringlist);
    procedure DoOnCodingProgress(Count, TotalSize : Longint; var Abort : Boolean);
    procedure EncodeContentDisposition(RawHeaders : TStringList);
    procedure EncodeContentType(RawHeaders : TStringList);
    procedure EncodeContentTransferEncoding(RawHeaders : TStringList);
    procedure EncodeMimeHeaders(RawHeaders : TStringlist);
    procedure OctetStreamToHextetStream(InStream : TStream; OutStream : TIpAnsiTextStream;
                                        const Table; PadChar, Delim : AnsiChar);
    procedure Decode8Bit(OutStream : TStream);
    procedure DecodeBase64(OutStream : TStream);
    procedure DecodeBinHex(OutStream : TStream);
    procedure DecodeQuoted(OutStream : TStream);
    procedure DecodeUUEncode(OutStream : TStream);
    procedure Encode8Bit(InStream : TStream);
    procedure EncodeBase64(InStream : TStream);
    procedure EncodeBinHex(InStream : TStream; const aFileName : string);
    procedure EncodeQuoted(InStream : TStream);
    procedure EncodeUUEncode(InStream : TStream; const aFileName : string);
    function DecodeEntity(InStream : TIpAnsiTextStream) : string;
    function DecodeEntityAsAttachment(InStream : TIpAnsiTextStream) : string;  {!!.01}
    function EncodeEntity(OutStream : TIpAnsiTextStream) : string;
    procedure ReadBody(InStream : TIpAnsiTextStream; const StartLine : string); {!!.12}

  protected {properties}
    property OnCodingProgress : TIpCodingProgressEvent
      read FOnCodingProgress write FOnCodingProgress;

  public {methods}
    constructor Create(ParentEntity : TIpMimeEntity); virtual;
    destructor  Destroy; override;
    procedure ClearBody;
    procedure EncodeBodyFile(const InFile : string);
    procedure EncodeBodyStream(InStream : TStream; const aFileName : string);
    procedure EncodeBodyStrings(InStrings : TStrings; const aFileName : string);
    procedure ExtractBodyFile(const OutFile : string);
    procedure ExtractBodyStream(OutStream : TStream);
    procedure ExtractBodyStrings(OutStrings : TStrings);
    function FindNestedMimePart(const aType, aSubType, aContentID : string) : TIpMimeEntity; {!!.02}
    function  GetMimePart(const aType, aSubType, aContentID : string;
                              CanCreate : Boolean) : TIpMimeEntity;
    function  NewMimePart : TIpMimeEntity;

    property AttachmentCount : Integer read FAttachmentCount;          {!!.12}

  public {properties}
    property Body : TIpAnsiTextStream
      read FBody;

    property Boundary : string
      read FBoundary write FBoundary;

    property CharacterSet : string
      read FCharacterSet write FCharacterSet;

    property ContentDescription : string
      read FContentDescription write FContentDescription;

    property ContentDispositionType : string
      read FContentDispositionType write FContentDispositionType;

    property ContentID : string
      read FContentID write FContentID;

    property ContentSubtype : string
      read FContentSubtype write FContentSubtype;

    property ContentTransferEncoding : TIpMimeEncodingMethod
      read FContentTransferEncoding write FContentTransferEncoding;

    property ContentType : string
      read FContentType write FContentType;

    property CreationDate : string
      read FCreationDate write FCreationDate;

    property EntityName : string
      read FEntityName write FEntityName;

    property FileName : string
      read FFileName write FFileName;

    property IsMime : Boolean
      read FIsMime;

    property IsMultipart : Boolean
      read FIsMultipart;

    property MimeParts : TIpMimeParts
      read FMimeParts;

    property MimeVersion : string
      read FMimeVersion write FMimeVersion;

    property ModificationDate : string
      read FModificationDate write FModificationDate;

    property OriginalSize : Longint
      read FOriginalSize write FOriginalSize;

    property Parent : TIpMimeEntity
      read FParent;

    property ReadDate : string
      read FReadDate write FReadDate;

    property RelatedStart : string                                   {!!.02}
      read FRelatedStart write FRelatedStart;

    property RelatedStartInfo : string                               {!!.02}
      read FRelatedStartInfo write FRelatedStartInfo;

    property RelatedSubtype : string                                 {!!.02}
      read FRelatedSubtype write FRelatedSubtype;

    property RelatedType : string                                    {!!.02}
      read FRelatedType write FRelatedType;

  end;


{ TIpMimeParts }
  TIpMimeParts = class
  protected {private}
    Entitys : TList;
    function GetCount : Integer;
    function GetPart(aIndex : Integer) : TIpMimeEntity;
  public {methods}
    constructor Create;
    destructor  Destroy; override;
    function Add(aEntity : TIpMimeEntity) : Integer;
    function Remove(aEntity : TIpMimeEntity) : Integer;
    procedure Clear;
    procedure Delete(aIndex : Integer);
    function IndexOf(aEntity : TIpMimeEntity) : Integer;
  public {properties}
    property Count : Integer
      read GetCount;
    property Parts[aIndex : Integer] : TIpMimeEntity
      read GetPart; default;
  end;


{ TIpMessage }
type
  TIpMessage = class(TIpMimeEntity)
  protected {private}
    MsgStream : TIpAnsiTextStream;

  protected {property variables}
    FBCC             : TStringList;
    FCC              : TStringList;
    FDate            : string;
    FFrom            : string;
    FInReplyTo       : string;
    FKeywords        : string;
    FFollowupTo      : string;                                           {!!.12}
    FControl         : string;                                           {!!.12}
    FMessageID       : string;
    FMessageTag      : Integer;
    FNewsgroups      : TStringList;
    FNNTPPostingHost : string;
    FOrganization    : string;
    FPath            : TStringList;
    FPostingHost     : string;
    FReceived        : TStringList;
    FRecipients      : TStringList;
    FReferences      : TStringList;
    FReplyTo         : string;
    FReturnPath      : string;
    FSender          : string;
    FSubject         : string;
    FUserFields      : TStringList;
    FHeaders         : TIpHeaderCollection;                              {!!.12}
    FDispositionNotify: string;

  protected {methods}
    procedure CheckAllHeaders;                                           {!!.12}
    procedure CheckHeaderType (HeaderInfo : TIpHeaderItem;               {!!.12}
                               HeaderType : TIpHeaderTypes);             {!!.12}
    procedure Clear; override;
    procedure NewMessageStream;
    function  GetPosition : Longint;
    function  GetSize : Longint;
    procedure SetPosition(Value : Longint);
    procedure SetBCC(const Value: TStringList);
    procedure SetCC(const Value: TStringList);
    procedure SetNewsgroups(const Value: TStringList);
    procedure SetPath(const Value: TStringList);
    procedure SetReceived(const Value: TStringList);
    procedure SetRecipients(const Value: TStringList);
    procedure SetReferences(const Value: TStringlist);
    procedure SetUserFields(const Value: TStringList);

  public {methods}
    constructor CreateMessage; virtual;
    destructor  Destroy; override;

    procedure AddDefaultAttachment(const aFileName : string);          {!!.02}
    procedure AddDefaultAttachmentAs (const aFileName      : string;   {!!.12}
                                      const AttachmentName : string);  {!!.12}
    procedure Assign(Source : TPersistent); override;
    function  AtEndOfStream : Boolean;
    procedure DecodeMessage; virtual;
    procedure EncodeMessage; virtual;
    function  GetBodyHtml(CanCreate : Boolean) : TIpMimeEntity;
    function  GetBodyPlain(CanCreate : Boolean) : TIpMimeEntity;
    procedure LoadFromFile(const aFileName : string);
    procedure LoadFromStream(aStream : TStream);                       {!!.12}
    procedure NewMessage;
    function  ReadLine : string;
    function  ReadLineCRLF : string;
    procedure SaveToFile(const aFileName : string);
    procedure SaveToStream(Stream: TStream);                           {!!.12}
    procedure SetHeaders(Headers : TIpHeaderCollection);               {!!.12}
    procedure WriteLine(const aSt : string);

  public {properties}
    property BCC : TStringList
      read FBCC write SetBCC;                                          {!!.01}

    property CC : TStringList
      read FCC write SetCC;                                            {!!.01}

    property Control : string                                          {!!.12}
      read FControl write FControl;                                    {!!.12}

    property Date : string
      read FDate write FDate;

    property DispositionNotification : string                          {!!.12}
      read FDispositionNotify write FDispositionNotify;                {!!.12}

    property FollowupTo : String                                       {!!.12}
      read FFollowupTo Write FFollowupTo;                              {!!.12}

    property From : string
      read FFrom write FFrom;

    property Headers : TIpHeaderCollection                             {!!.12}
             read FHeaders write SetHeaders;                           {!!.12}

    property InReplyTo : string
      read FInReplyTo write FInReplyTo;

    property Keywords : string
      read FKeywords write FKeywords;

    property MessageID : string
      read FMessageID write FMessageID;

    property MessageStream : TIpAnsiTextStream                         {!!.03}
      read MsgStream;                                                  {!!.03}

    property MessageTag : Integer
      read FMessageTag write FMessageTag;

    property Newsgroups : TStringList
      read FNewsgroups write SetNewsgroups;                            {!!.01}

    property NNTPPostingHost : string
      read FNNTPPostingHost write FNNTPPostingHost;

    property Organization : string
      read FOrganization write FOrganization;

    property Path : TStringList
      read FPath write SetPath;                                        {!!.01}

    property Position : Longint
      read GetPosition write SetPosition;

    property PostingHost : string
      read FPostingHost write FPostingHost;

    property Received : TStringList
      read FReceived write SetReceived;                                {!!.01}

    property Recipients : TStringList
      read FRecipients write SetRecipients;                            {!!.01}

    property References : TStringlist
      read FReferences write SetReferences;                            {!!.01}

    property ReplyTo : string
      read FReplyTo write FReplyTo;

    property ReturnPath : string
      read FReturnPath write FReturnPath;

    property Sender : string
      read FSender write FSender;

    property Size : Longint
      read GetSize;

    property Subject : string
      read FSubject write FSubject;

    property UserFields : TStringList
      read FUserFields write SetUserFields;                            {!!.01}

  end;


{ TIpMailMessage}
type
  TIpMailMessage = class(TIpMessage)
  published {properties}
    property BCC;
    property CC;
    property ContentDescription;
    property ContentTransferEncoding;
    property ContentType;
    property Date;
    property From;
    property Keywords;
    property MailTo : TStringList
      read FRecipients write SetRecipients;                            {!!.01}
    property OnCodingProgress;
    property References;
    property ReplyTo;
    property Sender;
    property Subject;
    property UserFields;
end;


{ TIpNewsArticle }
type
  TIpNewsArticle = class(TIpMessage)
  published {properties}
    property ContentDescription;
    property ContentTransferEncoding;
    property ContentType;
    property Date;
    property From;
    property Keywords;
    property Newsgroups;
    property NNTPPostingHost;
    property OnCodingProgress;
    property Path;
    property References;
    property ReplyTo;
    property Sender;
    property Subject;
    property UserFields;
end;


{ TIpFormDataEntity }
type
  TIpFormDataEntity = class(TIpMimeEntity)
  protected
    FFilesEntity : TIpMimeEntity;
  public {methods}
    constructor Create(ParentEntity : TIpMimeEntity); override;
    destructor  Destroy; override;
    procedure AddFormData(const aName, aText : string);
    procedure AddFile(const aFileName, aContentType, aSubtype : string;
                      aEncoding : TIpMimeEncodingMethod);
    procedure SaveToStream(aStream : TStream);
  end;

 {$IFNDEF IP_LAZARUS}
 { dummy class so this unit will be added to the uses clause when an }
 { IpPop3Client, IpSmtpClient or IpNntpClient component is dropped on the form }
 (*** //JMN
 TIpCustomEmailClass = class(TIpCustomClient)
 end;
 **)
 {$ENDIF}

function IpBase64EncodeString(const InStr: string): string;       {!!.02}{!!.03}

{Begin !!.12}
const
  IpLgAttachSizeBoundry = 5 * 1024 * 1024;
    { Attachments over this size will be encoded using a TIpMemMapStream for
      greatly improved performance. This boundary also applies to the final
      encoding of messages with large attachments. }

implementation

const
  { standard headers }
  strBCC               = 'BCC: ';
  strCC                = 'CC: ';
  strDate              = 'Date: ';
  strDispositionNotify = 'Disposition-Notification-To: ';
  strFrom              = 'From: ';
  strInReplyTo         = 'In-Reply-To: ';
  strKeywords          = 'Keywords: ';
  strMessageID         = 'Message-ID: ';
  strNewsgroups        = 'Newsgroups: ';
  strNNTPPostingHost   = 'NNTP-Posting-Host: ';
  strOrganization      = 'Organization: ';
  strPath              = 'Path: ';
  strPostingHost       = 'Posting-Host: ';
  strReceived          = 'Received: ';
  strReferences        = 'References: ';
  strReplyTo           = 'Reply-To: ';
  strReturnPath        = 'Return-Path: ';
  strSender            = 'Sender: ';
  strSubject           = 'Subject: ';
  strTo                = 'To: ';
  strUserFields        = 'X-';
  strXIpro             = 'X-Ipro: ';
  strFollowUp          = 'Followup-To: ';                               {!!.12}
  strControl           = 'Control: ';                                   {!!.12}

{Begin !!.13}
  IpMimeHeaders : array [0..5] of string =
    { List of MIME headers that must be marked as public properties in
      the message's Headers collection. Marking them as a public property
      prevents them from being written out twice if the message is saved
      to a file or stream. }
    (
      'Content-Type',
      'MIME-Version',
      'Content-Transfer-Encoding',
      'Content-Description',
      'Content-ID',
      'Content-Disposition'
    );
{End !!.13}

  { MIME headers }
  strMimeVersion             = 'MIME-Version: ';
  strContent                 = 'Content-';
  strContentBase             = strContent + 'Base: ';
  strContentDescription      = strContent + 'Description: ';
  strContentDisposition      = strContent + 'Disposition: ';
  strContentID               = strContent + 'ID: ';
  strContentLanguage         = strContent + 'Language: ';
  strContentLocation         = strContent + 'Location: ';
  strContentTransferEncoding = strContent + 'Transfer-Encoding: ';
  strContentType             = strContent + 'Type: ';

  { MIME content types }
  strApplication = 'application';
  strAudio       = 'audio';
  strFiles       = 'files';
  strFormData    = 'form-data';
  strImage       = 'image';
  strMessage     = 'message';
  strMultiPart   = 'multipart';
  strText        = 'text';
  strVideo       = 'video';

  { MIME content subtypes and parameters }
  strBoundary    = 'boundary=';
  strCharSet     = 'charset=';
  strMixed       = 'mixed';
  strName        = 'name=';
  strPlain       = 'plain';
  strHTML        = 'html';
  strOctetStream = 'octet-stream';
  strAlternative = 'alternative';
  strRelated     = 'related';                                        {!!.02}

  { MIME content disposition parameters }
  strAttachment       = 'attachment';
  strInline           = 'inline';
  strCreationDate     = 'creation-date=';
  strFilename         = 'filename=';
  strModificationDate = 'modification-date=';
  strReadDate         = 'read-date=';
  strStart            = 'start=';                                    {!!.02}
  strStartInfo        = 'start-info=';                               {!!.02}
  strSize             = 'size=';
  strType             = 'type=';                                     {!!.02}


  { MIME encoding methods }
  str7Bit     = '7bit';
  str8Bit     = '8bit';
  strBase64   = 'base64';
  strBinary   = 'binary';
  strBinHex   = 'binhex';
  strQuoted   = 'quoted-printable';
  strUUEncode = 'uuencoded';


  { default MIME content type information }
{$I IPDEFCT.INC}

type
  TIp6BitTable = array[0..63] of AnsiChar;

const {- BinHex encoding table }
  IpBinHexTable : TIp6BitTable = (
    '!', '"', '#', '$', '%', '&', '''', '(',
    ')', '*', '+', ',', '-', '0', '1',  '2',
    '3', '4', '5', '6', '8', '9', '@',  'A',
    'B', 'C', 'D', 'E', 'F', 'G', 'H',  'I',
    'J', 'K', 'L', 'M', 'N', 'P', 'Q',  'R',
    'S', 'T', 'U', 'V', 'X', 'Y', 'Z',  '[',
    '`', 'a', 'b', 'c', 'd', 'e', 'f',  'h',
    'i', 'j', 'k', 'l', 'm', 'p', 'q',  'r');

const {-BinHex decoding table }
  IpHexBinTable : array[33..114] of Byte = (
    $00, $01, $02, $03, $04, $05, $06, $07,
    $08, $09, $0A, $0B, $0C, $FF, $FF, $0D,
    $0E, $0F, $10, $11, $12, $13, $FF, $14,
    $15, $FF, $FF, $FF, $FF, $FF, $FF, $16,
    $17, $18, $19, $1A, $1B, $1C, $1D, $1E,
    $1F, $20, $21, $22, $23, $24, $FF, $25,
    $26, $27, $28, $29, $2A, $2B, $FF, $2C,
    $2D, $2E, $2F, $FF, $FF, $FF, $FF, $30,
    $31, $32, $33, $34, $35, $36, $FF, $37,
    $38, $39, $3A, $3B, $3C, $FF, $FF, $3D,
    $3E, $3F);

const { Base64 encoding table }
  Ip64Table : TIp6BitTable = (
    #065, #066, #067, #068, #069, #070, #071, #072,
    #073, #074, #075, #076, #077, #078, #079, #080,
    #081, #082, #083, #084, #085, #086, #087, #088,
    #089, #090, #097, #098, #099, #100, #101, #102,
    #103, #104, #105, #106, #107, #108, #109, #110,
    #111, #112, #113, #114, #115, #116, #117, #118,
    #119, #120, #121, #122, #048, #049, #050, #051,
    #052, #053, #054, #055, #056, #057, #043, #047);

const { Base64 decoding table }
  IpD64Table : array[#43..#122] of Byte = (                          {!!.12}
    $3E, $7F, $7F, $7F, $3F, $34, $35, $36,
    $37, $38, $39, $3A, $3B, $3C, $3D, $7F,
    $7F, $7F, $7F, $7F, $7F, $7F, $00, $01,
    $02, $03, $04, $05, $06, $07, $08, $09,
    $0A, $0B, $0C, $0D, $0E, $0F, $10, $11,
    $12, $13, $14, $15, $16, $17, $18, $19,
    $7F, $7F, $7F, $7F, $7F, $7F, $1A, $1B,
    $1C, $1D, $1E, $1F, $20, $21, $22, $23,
    $24, $25, $26, $27, $28, $29, $2A, $2B,
    $2C, $2D, $2E, $2F, $30, $31, $32, $33);

const { UUEncode encoding table }
  IpUUTable : TIp6BitTable = (
    #96, #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);

const
  HexDigits : array[0..$F] of AnsiChar = '0123456789ABCDEF';
  RLEChar : Byte = $90;
  BinHexFileType : array[0..3] of Byte = ($49, $42, $4D, $3F);  { "IBM?" }
  CRLF = #13#10;
  MaxLine = 1000;                                                       {!!.12}
  MaxLineEncode = 77;                                                   {!!.13}
    { Maximum line length for QuotablePrintable & Base64 encoding. }    {!!.13}

type
  BinHexHeader = packed record
    Version  : Byte;
    FileType : array[0..3] of Byte;
    Creator  : array[0..3] of Byte;
    Flags    : Word;
    DFLong   : Longint;
    RFLong   : Longint;
  end;

function IsSameString (Str1          : string;                           {!!.12}
                       Str2          : string;                           {!!.12}
                       CaseSensitive : Boolean) : Boolean;               {!!.12}
begin                                                                    {!!.12}
  if CaseSensitive then                                                  {!!.12}
    Result := (Str1 = Str2)                                              {!!.12}
  else                                                                   {!!.12}
    Result := StrIComp (PChar (Str1), PChar (Str2)) = 0;                 {!!.12}
end;                                                                     {!!.12}

{ Parse string into string list }
procedure Parse(const Line : string; Delim : AnsiChar; var List : TStringList);
var
  iPos, jPos : Integer;
  Term : string;
begin
  iPos := 1;
  jPos := IpUtils.CharPos(Delim, Line);
  while (jPos > 0) do begin
    Term := Copy(Line, iPos, jPos - iPos);                           {!!.02}
    if (Term <> '') then
      List.Add(Trim(Term));
    iPos := jPos + 1;
    jPos := IpUtils.CharPosIdx(Delim, Line, iPos);
  end;
  if (iPos < Length(Line)) then
     List.Add(Trim(Copy(Line, iPos, Length(Line))));
end;

{ Return a particular parameter from a parsed header parameter list }
procedure DecodeSingleParameter(const ParamName : string;
                                RawParams : TStringList;
                                var ParamFieldStr : string);
var
  S : string;
  i, j : Integer;
begin
  ParamFieldStr := '';
  {find the line containing the parameter field name}
  for i := 1 to RawParams.Count do begin
    S := RawParams[i-1];
    if StrLIComp(PChar(ParamName), PChar(S), Length(ParamName)) = 0 then begin
      {strip off the parameter field name and remove quotes }
      ParamFieldStr := Copy(S, Length(ParamName) + 1, Length(S));
      j := IpUtils.CharPos('"', ParamFieldStr);
      while (j > 0) do begin
        Delete(ParamFieldStr, j, 1);
        j := IpUtils.CharPos('"', ParamFieldStr);
      end;
      Break;
    end;
  end;
end;

{ Return a particular header as string }
procedure DecodeSingleHeader(const HeaderName : string;
                             RawHeaders : TStringList;
                             var HeaderFieldStr : string);
var
  S, S2 : string;
  i, j : Integer;
begin
  HeaderFieldStr := '';
  {find the line containing the header field name}
  for i := 1 to RawHeaders.Count do begin
    S := RawHeaders[i-1];
    if StrLIComp(PChar(HeaderName), PChar(S), Length(HeaderName)) = 0 then begin
      {strip off the header field name}
      S := Copy(S, Length(HeaderName) + 1, Length(S));
      {unfold the header if continued on more than one line}
      if (i < RawHeaders.Count) then
        for j := i to Pred(RawHeaders.Count) do begin
          S2 := RawHeaders[j];
          if (Length(S2) > 0) and (S2[1] <> #09) and (S2[1] <> ' ') then
            Break
          else
            S := S + S2;
        end;
      HeaderFieldStr := S;
      Break;
    end;
  end;
end;

{ Return a particular header as string list }
(*procedure DecodeListHeader(const HeaderName : string;
                           RawHeaders, HeaderFieldList : TStringList);
var
  S : string;
  i, j : Integer;
begin
  {find the line containing the header field name}
  for i := 1 to RawHeaders.Count do begin
    S := RawHeaders[i-1];
    if StrLIComp(PChar(HeaderName), PChar(S), Length(HeaderName)) = 0 then begin
      {strip off the header field name}
      HeaderFieldList.Add(Copy(S, Length(HeaderName) + 1, Length(S)));
      {unfold the header if continued on more than one line}
      if (i < RawHeaders.Count) then
        for j := i to Pred(RawHeaders.Count) do begin
          S := RawHeaders[j];
          if (Length(S) > 0) and (S[1] <> #09) and (S[1] <> ' ') then
            Break
          else
            HeaderFieldList.Add(S);
        end;
      Break;
    end;
  end;
end;*)

{ Return multiple instance headers as string list }
(*procedure DecodeMultiHeader(const HeaderName : string;
                            RawHeaders, HeaderFieldList : TStringList);

var
  S, S2 : string;
  i, j : Integer;
begin
  {find the next line containing the header field name}
  for i := 1 to RawHeaders.Count do begin
    S := RawHeaders[i-1];
    if StrLIComp(PChar(HeaderName), PChar(S), Length(HeaderName)) = 0 then begin
      if HeaderName <> strUserFields then begin                         {!!.11}
        {strip off the header field name}
        S := Copy(S, Length(HeaderName) + 1, Length(S));
        {unfold the header if continued on more than one line}
        if (i < RawHeaders.Count) then
          for j := i to Pred(RawHeaders.Count) do begin
            S2 := RawHeaders[j];
            if (Length(S2) > 0) and (S2[1] <> #09) and (S2[1] <> ' ') then
              Break
            else
              S := S + S2;
          end;
      end;                                                              {!!.11}
      HeaderFieldList.Add(S);
    end;
  end;
end;*)

{ Add header string to raw headers }
procedure EncodeSingleHeader(const HeaderName : string;
                             RawHeaders : TStringList;
                             HeaderFieldStr : string);
begin
  if (HeaderFieldStr <> '') then
    RawHeaders.Add(HeaderName + HeaderFieldStr);
end;

{ Unfold multiple line header and add to raw headers }
procedure EncodeListHeader(const HeaderName : string;
                           RawHeaders, HeaderFieldList : TStringList;
                           const Delim : string;
                           Fold : Boolean);
var
  S : string;
  i : Integer;
begin
  if (HeaderFieldList.Count > 0) then begin
    S := HeaderName;
    for i := 0 to Pred(HeaderFieldList.Count) do begin
      if (Length(S + HeaderFieldList[i]) > MaxLine) then begin
        RawHeaders.Add(S);
        S := #09;
      end;
      S := S + HeaderFieldList[i];
      if (i < HeaderFieldList.Count - 1) and (S <> '') then begin
        S := S + Delim;                                                {!!.14}
        if Fold then begin
          RawHeaders.Add(S);
          S := #09;
        end;
      end;
    end;
    RawHeaders.Add(S);
  end;
end;

{ Add multiple instance header to raw headers }
procedure EncodeMultiHeader(const HeaderName : string;
                            RawHeaders, HeaderFieldList : TStringList;
                            Delim : AnsiChar;
                            Fold : Boolean);
var
  i, j : Integer;
  SL : TStringList;
  S : string;
begin
  if (HeaderFieldList.Count > 0) then
    for j := 1 to HeaderFieldList.Count do begin
      if not Fold then
        RawHeaders.Add(HeaderName + HeaderFieldList[j-1])
      else begin
        SL := TStringList.Create;
        try
          Parse(HeaderFieldList[j-1], Delim, SL);
          S := HeaderName;
          for i := 1 to SL.Count do begin
            S := S + SL[i-1];
            if (i < SL.Count) and (S <> '') then begin
{Begin !!.13}
              RawHeaders.Add(S);
              S := Delim;
{End !!.13}
            end;
          end;
        finally
          SL.Free;
        end;
        RawHeaders.Add(S);
      end;
    end;
end;

{ Generate "unique" boundary string }
function GenerateBoundary : string;
var
  Temp : TDateTime;
begin
  Temp := Now;
  Randomize;
  Result := '_NextPart_' + IntToHex(Trunc(Temp), 8) + '-' +
    IntToHex(Trunc(Frac(Temp) * 10000), 8) + '-' +
    IntToHex(GetTickCount64, 8) + '-' + IntToHex(Random($FFFF), 4);
end;

{ 16-bit CRC of stream between starting and ending offset }
function BinHexCRC(Stream : TStream; StartOffset, EndOffset : Longint) : Word;
var
  Crc : Word;
  InByte : Byte;
  ByteStream : TIpByteStream;

  procedure DoCRC(b : Byte);
    {- carry CRC division on with next byte }
  var
    j : Byte;
    t : Boolean;
  begin
    for j := 1 to 8 do begin
      t := (Crc and $8000) <> 0;
      Crc := (Crc shl 1) xor (b shr 7);
      if t then
        Crc := Crc xor $1021;
      b := b shl 1;
    end;
  end;

begin
  if (StartOffset > Stream.Size) or (EndOffset > Stream.Size) then
    raise EIpBaseException.Create(SBadOffset);

  Crc := 0;
  Stream.Position := StartOffset;
  ByteStream := TIpByteStream.Create(Stream);
  try
    while (ByteStream.Position < EndOffset) do begin
      if ByteStream.Read(InByte) then
        DoCrc(InByte);
    end;
  finally
    ByteStream.Free;
  end;
  DoCrc(0);
  DoCrc(0);
  Result := Swap(Crc);
end;

{ Reverse bytes and words }
function htonl(HostLong : Longint) : Longint;
var
  dw : Longint;
  wa : array[0..1] of Word absolute dw;
  w  : Word;
begin
  dw := HostLong;
  w := wa[0];
  wa[0] := Swap(wa[1]);
  wa[1] := Swap(w);
  Result := dw;
end;

{Begin !!.12}
{ TIpHeaderItem ****************************************************** }

constructor TIpHeaderItem.Create (Collection : TCollection);
begin
  inherited Create (Collection);
  FCollection := TIpHeaderCollection.Create (
                     TIpHeaderCollection(Collection).FOwner);

  FValue := TStringList.Create;
  FName  := '';
  FProperty := False;                                                  {!!.13}
end;                                                                     

destructor TIpHeaderItem.Destroy;                                        
begin                                                                    
  FCollection.Free;                                                      
  FCollection := nil;                                                    

  FValue.Free;                                                           
  FValue := nil;                                                         

  inherited Destroy;                                                     
end;                                                                     

procedure TIpHeaderItem.SetName(const Name : string);
begin
  FName := Name;
  FNameL := LowerCase(Name);
end;

procedure TIpHeaderItem.SetValue (v : TStringList);                      
begin                                                                    
  FValue.Assign (v);                                                     
end;                                                                     

{ TIpHeaderCollection ************************************************ } 

constructor TIpHeaderCollection.Create(AOwner : TPersistent);            
begin                                                                    
  inherited Create (TIpHeaderItem);                                      
  FOwner := AOwner;                                                      
end;                                                                     

{$IFNDEF VERSION5}                                                       
procedure TIpHeaderCollection.Delete(Item: integer);                     
begin                                                                    
  GetItem(Item).Free;                                                    
end;                                                                     
{$ENDIF}                                                                 

function TIpHeaderCollection.GetItem (Index : Integer) : TIpHeaderItem;  
begin                                                                    
  Result := TIpHeaderItem (inherited GetItem (Index));                   
end;                                                                     

function TIpHeaderCollection.GetOwner : TPersistent;                     
begin                                                                    
  Result := FOwner;                                                      
end;                                                                     

function TIpHeaderCollection.HasHeader (AName : string) : Integer;
var                                                                      
  i : Integer;                                                           
begin                                                                    
  Result := -1;                                                          
  AName := LowerCase(AName);
  for i := 0 to Count - 1 do
    if Items[i].NameL = AName then begin                      
      Result := i;                                                       
      Break;                                                             
    end;                                                                 
end;                                                                     

procedure TIpHeaderCollection.HeaderByName (AName   : string;            
                                            Headers : TStringList);      
var
  HeaderPos : Integer;                                                   
begin                                                                    
  Headers.Clear;                                                         
  HeaderPos := HasHeader (AName);                                        
  if HeaderPos >= 0 then                                                 
    Headers.Assign (Items[HeaderPos].Value);                             
end;                                                                     

procedure TIpHeaderCollection.LoadHeaders (AHeaderList : TStringList;
                                           Append      : Boolean);
var
  CurPos : Integer;

  function ExtractHeaderName (const AName : string) : string;
  {!!.15 - replaced local variable i with inx in order to avoid confusion with
    variable i in parent routine. }
  var
    inx     : Integer;
    NameLen : Integer;
  begin
    Result := '';
    CurPos := 0;

    inx := 0;
    NameLen := Length (AName);
    while (inx < NameLen) and (AName[inx + 1] <> ':') and
          (AName[inx + 1] >= #33) and (AName[inx + 1] <= #126) do
      Inc (inx);
    if (inx > 0) then
      Result := Copy (AName, 1, inx);
    CurPos := inx + 2;
  end;

  function IsWrappedLine (AHeaderList : TStringList;
                          LineToCheck : Integer) : Boolean;
  begin
    if LineToCheck < AHeaderList.Count then begin
      if Length (AHeaderList[LineToCheck]) > 0 then begin
        if (AHeaderList[LineToCheck][1] = ' ') or
           (AHeaderList[LineToCheck][1] = #09) then
          Result := True
        else
          Result := False;
      end else
        Result := False;
    end else
      Result := False;
  end;

  procedure GetFieldValue (    AHeaderList : TStringList;
                           var CurLine     : Integer;
                           var NewField    : TIpHeaderItem);
  var
    WorkLine : string;
    LineLen  : Integer;

  begin
    if CurLine >= AHeaderList.Count then
      Exit;
    LineLen  := Length (AHeaderList[CurLine]);
    while (CurPos < LineLen) and
          ((AHeaderList[CurLine][CurPos] = ' ') or
           (AHeaderList[CurLine][CurPos] = #09)) do
      Inc (CurPos);
    WorkLine := Copy (AHeaderList[CurLine],
                      CurPos, LineLen - CurPos + 1);
{Begin !!.13}
    Inc(CurLine);

    while IsWrappedLine (AHeaderList, CurLine) do begin
      WorkLine := WorkLine + #9 + Trim(AHeaderList[CurLine]);
      Inc(CurLine);
    end;
    NewField.Value.Add (Trim (WorkLine));
{End !!.13}
  end;

var                                                                      
  i          : Integer;                                                  
  HeaderName : string;                                                   
  NewHeader  : TIpHeaderItem;                                            
begin                                                                    
  if not Append then                                                     
    Clear;

  i := 0;                                                                
  while i < AHeaderList.Count do begin                                   
    HeaderName := ExtractHeaderName (AHeaderList[i]);                    
    if HeaderName <> '' then begin                                       
      NewHeader := TIpHeaderItem (Add);                                  
      NewHeader.Name := HeaderName;                                      
      GetFieldValue (AHeaderList, i, NewHeader);
{Begin !!.15}
    end
    else
      Inc(i);
{End !!.15}
  end;
end;                                                                     

procedure TIpHeaderCollection.SetItem (Index : Integer;                  
                                       Value : TIpHeaderItem);           
begin                                                                    
  inherited SetItem (Index, Value);                                      
end;
{End !!.12}

{ TIpMimeParts }
constructor TIpMimeParts.Create;
begin
  inherited Create;
  Entitys := TList.Create;
end;

destructor TIpMimeParts.Destroy;
begin
  Clear;
  Entitys.Free;
  inherited Destroy;
end;

{ Add Mime block to list }
function TIpMimeParts.Add(aEntity : TIpMimeEntity) : Integer;
begin
  Result := Entitys.Add(aEntity);
end;

{ Clear list }
procedure TIpMimeParts.Clear;
var
  i : Integer;
begin
  for i := Pred(Entitys.Count) downto 0 do
    Delete(i);
end;

{ Delete block from list }
procedure TIpMimeParts.Delete(aIndex : Integer);
begin
  if (aIndex >= 0) and (aIndex < Entitys.Count) then begin
    TIpMimeEntity(Entitys[aIndex]).Free;
  end;
end;

{ Remove block from list }
function TIpMimeParts.Remove(aEntity : TIpMimeEntity) : Integer;
begin
  Result := Entitys.Remove(Pointer(aEntity));
end;

{ Count property read access method }
function TIpMimeParts.GetCount : Integer;
begin
  Result := Entitys.Count;
end;

{ Parts property read access method }
function TIpMimeParts.GetPart(aIndex : Integer) : TIpMimeEntity;
begin
  if (aIndex >= 0) and (aIndex < Entitys.Count) then
    Result := TIpMimeEntity(Entitys[aIndex])
  else
    Result := nil;
end;

{ Returns list index of specified Mime block }
function TIpMimeParts.IndexOf(aEntity : TIpMimeEntity) : Integer;
begin
  Result := Entitys.IndexOf(aEntity);
end;


{ TIpMimeEntity }
constructor TIpMimeEntity.Create(ParentEntity : TIpMimeEntity);
begin
  inherited Create;
  FBody := TIpAnsiTextStream.CreateEmpty;
  FBody.Stream := TMemoryStream.Create;
  FMimeParts := TIpMimeParts.Create;
  FParent := ParentEntity;
  if (FParent <> nil) then
    FParentBoundary := FParent.Boundary;
end;

destructor TIpMimeEntity.Destroy;
begin
  FMimeParts.Free;
  FBody.FreeStream;
  FBody.Free;
  if (FParent <> nil) then
    FParent.MimeParts.Remove(Self);
  inherited Destroy;
end;

{ Clear Body property }
procedure TIpMimeEntity.ClearBody;
begin
  FBody.FreeStream;
  FBody.Stream := TMemoryStream.Create;
end;

{Begin !!.12}
{ Clear Body property in preparation for large attachment }
procedure TIpMimeEntity.ClearBodyLargeAttach(const AttachmentSize : Longint);
var
  FileName : string;
  Strm : TIpMemMapStream;
begin
  FBody.FreeStream;
  FileName := GetTemporaryFile(GetTemporaryPath);
  if FileExistsUTF8(FileName) then
    DeleteFileUTF8(FileName);
  Strm := TIpMemMapStream.Create(FileName, False, True);
  Strm.Size := Trunc(AttachmentSize * 1.3695);
  Strm.Open;
  FBody.Stream := Strm;
end;
{End !!.12}

{ Clear all properties }
procedure TIpMimeEntity.Clear;
begin
  ClearBody;
  FMimeParts.Clear;
  FBoundary := '';
  FCharacterSet := '';
  FContentDescription := '';
  FContentDispositionType := '';
  FContentID := '';
  FContentSubtype := '';
  FContentType := '';
  FContentTransferEncoding := emUnknown;
  FFileName := '';
  FIsMime := False;
  FIsMultipart := False;
  FMimeVersion := '';
  FEntityName := '';
  FRelatedType := '';                                                {!!.02}
  FRelatedSubtype := '';                                             {!!.02}
  FRelatedStart := '';                                               {!!.02}
  FRelatedStartInfo := '';                                           {!!.02}
end;

{ Build Mime (and nested Mime) block(s) from incoming text stream }
function TIpMimeEntity.DecodeEntity(InStream : TIpAnsiTextStream) : string;
var
  Blk : TIpMimeEntity;
  RawHeaders : TStringList;
  Decoded : Boolean;                                                   {!!.12}
  i,                                                                   {!!.13}
  LeadingBlankLines : Integer;                                         {!!.13}
begin
  Decoded := False;                                                    {!!.12}
  LeadingBlankLines := 0;                                              {!!.13}
  { skip blank lines in front of mime headers or body }
  Result := InStream.ReadLine;
  while (Result = '') and not InStream.AtEndOfStream do begin
    inc(LeadingBlankLines);
    Result := InStream.ReadLine;
  end;

  { decode mime headers if any }
{Begin !!.15}
  if (StrLIComp(PChar(strContent), PChar(Result), Length(strContent)) = 0) or
     (StrLIComp(PChar(strMimeVersion), PChar(Result),
                Length(strMimeVersion)) = 0) then begin
{End !!.15}
    RawHeaders := TStringList.Create;
    try
      repeat
        RawHeaders.Add(Result);
        Result := InStream.ReadLine;
      until (Result = '') or (InStream.AtEndOfStream);
      DecodeMimeHeaders(RawHeaders);
    finally
      RawHeaders.Free;
    end;
    Result := InStream.ReadLine;
    { skip blank lines between mime headers and mime body }
    while (Result = '') and not InStream.AtEndOfStream do
      Result := InStream.ReadLine;
  end;

  { decode body - main loop }
{Begin !!.15}
  if (FParentBoundary <> '') and
     (Result = '--' + FParentBoundary) then
    { The body of this entity is empty & we are now positioned at the boundary
      marker for the next entity. }
    Decoded := True
  else
{End !!.15}
  while not (((FParentBoundary <> '') and                              {!!.12}
              (Result = '--' + FParentBoundary)                        {!!.12}
             ) or InStream.AtEndOfStream) do begin                     {!!.12}
    Decoded := True;
    { check for ending boundary - in which case were done }
    if (FParentBoundary <> '') then
      if Pos('--' + FParentBoundary + '--', Result) = 1 {> 0} then begin
        Result := InStream.ReadLine;
        Exit;
      end;

    { decode any nested mime parts - recursively }
    if IsMultiPart and (Boundary <> '') and                            {!!.03}
      (Pos('--' + Boundary, Result) = 1)  then begin
      Blk := TIpMimeEntity.Create(Self);
      Result := Blk.DecodeEntity(Instream);
      FMimeParts.Add(Blk);
    end else begin
      { read raw text line into body }
      for i := 1 to LeadingBlankLines do                               {!!.13}
        Body.WriteLine('');                                            {!!.13}
      Body.WriteLine(Result);
      Result := InStream.ReadLine;
    end;
    if InStream.AtEndOfStream then break;                              {!!.12}
    LeadingBlankLines := 0;                                            {!!.13}
  end;
{Begin !!.12}
  { If did not find a MIME entity then assume the body is text &
    read it into the Body property. }
  if not Decoded then
    ReadBody(InStream, Result)
  else if (not (Pos('--' + FParentBoundary, Result) = 1)) then
    { If the last line is not a MIME separator then add the last line
      to the Body. }
    Body.WriteLine(Result);
{End !!.12}
end;

{!!.01}
{ Build Mime block as subpart from incoming text stream }
function TIpMimeEntity.DecodeEntityAsAttachment(InStream : TIpAnsiTextStream) : string;
var
  Blk : TIpMimeEntity;
begin
  Blk := TIpMimeEntity.Create(Self);
  Blk.ContentType := FContentType;
  Blk.ContentSubtype := FContentSubtype;
  Blk.ContentDispositionType := FContentDispositionType;
  Blk.ContentDescription := FContentDescription;
  Blk.ContentTransferEncoding := FContentTransferEncoding;
  Blk.CharacterSet := FCharacterSet;
  Blk.CreationDate := FCreationDate;
  Blk.FileName := FFileName;
  Blk.EntityName := FEntityName;
  Blk.FIsMime := True;
  Blk.FIsMultipart := False;
  Blk.ModificationDate := FModificationDate;
  Blk.MimeVersion := FMimeVersion;
  Blk.OriginalSize := FOriginalSize;
  Blk.ReadDate := FReadDate;

  Result := Blk.DecodeEntity(Instream);
  FMimeParts.Add(Blk);
  Body.Position := 0;
end;

{ Decode Content-Disposition header field and sub-fields }
procedure TIpMimeEntity.DecodeContentDisposition(const aDisp : string);
var
  RawParams : TStringList;
  S : string;
begin
  { split up parameters }
  RawParams := TStringList.Create;
  try
    Parse(aDisp, ';', RawParams);

    { decode disposition type and parameters }
    if (RawParams.Count > 0) then begin
      FContentDispositionType := RawParams[0];
      if (RawParams.Count > 1) then begin
        DecodeSingleParameter(strFileName, RawParams, FFileName);
        DecodeSingleParameter(strCreationDate, RawParams, FCreationDate);
        DecodeSingleParameter(strModificationDate, RawParams, FModificationDate);
        DecodeSingleParameter(strReadDate, RawParams, FReadDate);
        DecodeSingleParameter(strSize, RawParams, S);
        FOriginalSize := StrToIntDef(S, 0);
      end;
    end else
      FContentDispositionType := '';
  finally
    RawParams.Free;
  end;
end;

{ Decode Content-Type header field and sub-fields }
procedure TIpMimeEntity.DecodeContentType(const aType : string);
var
  RawParams : TStringList;
  S : string;
  i : Integer;
begin
  { split up parameters }
  RawParams := TStringList.Create;
  try
    Parse(aType, ';', RawParams);

    { decode type and subtype }
    FContentType := '';
    FContentSubType := '';
    if (RawParams.Count > 0) then begin
      S := RawParams[0];
      i := IpUtils.CharPos('/', S);
      if (i > 0) then begin
        FContentType := Copy(S, 1, i - 1);
        FContentSubType := Copy(S, i + 1, Length(S));
      end else
        FContentType := S;
    end;
    FIsMultipart := StrIComp(PChar(FContentType), PChar(strMultipart)) = 0;

    { decode the parameters }
    DecodeSingleParameter(strName, RawParams, FEntityName);
    DecodeSingleParameter(strBoundary, RawParams, FBoundary);
    DecodeSingleParameter(strCharSet, RawParams, FCharacterSet);

    {!!.02}
    { decode multipart/related parameters }
    DecodeSingleParameter(strType, RawParams, S);
    if (S <> '') then begin
      i := IpUtils.CharPos('/', S);
      if (i > 0) then begin
        FRelatedType := Copy(S, 1, i - 1);
        FRelatedSubType := Copy(S, i + 1, Length(S));
      end else
        FRelatedType := S;
      DecodeSingleParameter(strStart, RawParams, FRelatedStart);
      DecodeSingleParameter(strStartInfo, RawParams, FRelatedStartInfo);
    end;
    {!!.02}

  finally
    RawParams.Free;
  end;
end;

{ Decode Content-TranferEncoding header field }
function TIpMimeEntity.DecodeContentTransferEncoding(const aEncoding : string) :
  TIpMimeEncodingMethod;
begin
  if (UpperCase(aEncoding) = UpperCase(str7Bit)) then
    Result := em7bit
  else if (UpperCase(aEncoding) = UpperCase(str8Bit)) then
    Result := em8bit
  else if (UpperCase(aEncoding) = UpperCase(strBase64)) then
    Result := emBase64
  else if (UpperCase(aEncoding) = UpperCase(strBinary)) then
    Result := emBinary
  else if (UpperCase(aEncoding) = UpperCase(strBinHex)) then
    Result := emBinHex
  else if (UpperCase(aEncoding) = UpperCase(strQuoted)) then
    Result := emQuoted
  else if (UpperCase(aEncoding) = UpperCase(strUUEncode)) then
    Result := emUUEncode
  else
    Result := emUnknown;
end;


{ Decode Mime headers from raw header list }
procedure TIpMimeEntity.DecodeMimeHeaders(RawHeaders : TStringList);
var
  S : string;
begin
  { decode content type header }
  DecodeSingleHeader(strContentType, RawHeaders, S);
  if (S <> '') then begin
    FIsMime := True;
    DecodeContentType(S);
    if FIsMultipart and (FBoundary = '') then
      raise EIpBaseException.Create(SNoBoundary);
  end else begin
    FIsMime := False;
    Exit;
  end;

  { decode the others }
  DecodeSingleHeader(strMIMEVersion, RawHeaders, FMimeVersion);
  DecodeSingleHeader(strContentTransferEncoding, RawHeaders, S);
  FContentTransferEncoding := DecodeContentTransferEncoding(S);
  DecodeSingleHeader(strContentDescription, RawHeaders, FContentDescription);
  DecodeSingleHeader(strContentID, RawHeaders, FContentID);
  DecodeSingleHeader(strContentDisposition, RawHeaders, S);
  if (S <> '') then
    DecodeContentDisposition(S);
  if (FContentDispositionType = strAttachment) then                    {!!.12}
    Inc (FParent.FAttachmentCount);                                    {!!.12}{!!.15}
end;

{ Compute attachment coding progress and fire OnCodingProgress event }
procedure TIpMimeEntity.DoOnCodingProgress(Count, TotalSize : Longint;
                                          var Abort : Boolean);
  { IMPORTANT: The progress event must only be fired by the root parent }
begin
  if (Parent = nil) or (Parent = Self) then begin
    FProgress := ((Count*100) div TotalSize);
    if (FProgress > 100) then
      FProgress := 100;
    if (FProgress div 10) = 0 then
      PrevProgress := 0;

    { report progress in 10% increments }
    if ((FProgress div 10) > (PrevProgress div 10)) then begin
      PrevProgress := FProgress;
      if Assigned(FOnCodingProgress) then
        FOnCodingProgress(Self, FProgress, Abort);
    end;
  end else
    Parent.DoOnCodingProgress(Count, TotalSize, Abort);
end;

{ Generate Mime message stream from properties (and nested Mime blocks) }
function TIpMimeEntity.EncodeEntity(OutStream : TIpAnsiTextStream) : string;
var
  i : Integer;
  S : string;
  RawHeaders : TStringList;
  Ch : AnsiChar;
begin
  Result := FParentBoundary;

  { write out mime headers }
  if (Result <> '') then begin
    OutStream.WriteLine('--' + Result);
    RawHeaders := TStringList.Create;
    try
      EncodeMimeHeaders(RawHeaders);
      if (RawHeaders.Count > 0) then
        for i := 0 to Pred(RawHeaders.Count) do
          if (RawHeaders[i] <> '') then
            OutStream.WriteLine(RawHeaders[i]);
      OutStream.WriteLine('');
    finally
      RawHeaders.Free;
    end;
  end;

  // flush to update underlaying memory streams
  Body.Flush;
  { write out mime body }
  if (Body.FastSize > 0) then
  begin
    // presize stream for more speed
    OutStream.Stream.Size := OutStream.Stream.Size + Body.FastSize;
    // use optimal method depending on the source stream to copy the stream
    if Body.Stream is TIpMemMapStream then
      OutStream.Write((Body.Stream as TIpMemMapStream).Memory^, Body.FastSize)
    else   
      if Body.Stream is TMemoryStream then
        OutStream.Write((Body.Stream as TMemoryStream).Memory^, Body.Stream.Size)
      else 
        OutStream.CopyFrom(Body, 0); // copy the entire stream from the beginning

    { make sure the body is properly terminated }                    {!!.01}
    OutStream.Position := OutStream.Size - 1;                        {!!.01}
    TIpBufferedStream(OutStream).ReadChar(Ch);                       {!!.01}
    if ((Ch <> #13) and (Ch <> #10)) then                            {!!.01}
      OutStream.WriteLine('');                                       {!!.01}
  end;

  { encode nested mime parts - recursively }
  if (FMimeParts.Count > 0) then begin
    for i := 0 to Pred(FMimeParts.Count) do
      S := FMimeParts[i].EncodeEntity(OutStream);
    OutStream.WriteLine('--' + S + '--');
  end;
end;

{Begin !!.14}
function TIpMimeEntity.ContainsSpecialChars(const Value : string) : Boolean;
var
  Inx : Integer;
begin
  Result := False;
  for Inx := 1 to Length(Value) do
    if (Ord(Value[Inx]) <= 32) or
       (Value[Inx] in ['(', ')', '<', '>', '@',
                       ',', ';', ':', '\', '"',
                       '/', '[', ']', '?', '=']) then begin
      Result := True;
      Break;
    end; { if }
end;
{End !!.14}

{ Generate Content-Disposition header into raw header list }
procedure TIpMimeEntity.EncodeContentDisposition(RawHeaders : TStringList);
var
  Params : TStringList;
begin
  if (FContentDispositionType = '') then
    Exit;

  Params := TStringList.Create;
  try
    Params.Add(FContentDispositionType);
{Begin !!.14}
    if (FFileName <> '') then begin
      { If the filename contains spaces, control characters, or any of the
        special characters identified in RFC 1521 then wrap the filename in
        quotes.

        Assumption: FFileName length is <= 78 characters. Future enhancement
        is to support RFC 2184. }
      if ContainsSpecialChars(FFileName) then
        Params.Add(strFileName + '"' + FFileName + '"')
      else
        Params.Add(strFileName + FFileName);
    end;  { if }
{End !!.14}
    if (FCreationDate <> '') then
      Params.Add(strCreationDate + FCreationDate);
    if (FModificationDate <> '') then
      Params.Add(strModificationDate + FModificationDate);
    if (FReadDate <> '') then
      Params.Add(strReadDate + FReadDate);
    if (FOriginalSize > 0) then
      Params.Add(strSize + IntToStr(FOriginalSize));
    EncodeListHeader(strContentDisposition, RawHeaders, Params, ';', False);
  finally
    Params.Free;
  end;
end;

{ Generate Content-Type header into raw header list }
procedure TIpMimeEntity.EncodeContentType(RawHeaders : TStringList);
var
  S : string;
  Params : TStringList;
begin
  if (FContentType = '') then
    Exit;

  Params := TStringList.Create;
  try
    S := FContentType;
    if (FContentSubType <> '') then
      S := S + '/' + FContentSubType;
    Params.Add(S);
    if IsMultipart then
      Params.Add(strBoundary + '"' + FBoundary + '"');
    if (FEntityName <> '') then
      Params.Add(strName + '"' + FEntityName + '"');
    if (FCharacterSet <> '') then
      Params.Add(strCharSet + FCharacterSet); {no quotes}

    {!!.02}
    { encode multipart/related parameters }
    if (FRelatedType <> '') then begin
      if (FRelatedSubtype <> '') then
        Params.Add(strType + '"' + FRelatedType + '/' + FRelatedSubtype + '"')
      else
        Params.Add(strType + '"' + FRelatedType + '"');
      if (FRelatedStart <> '') then
        Params.Add(strStart + '"' + FRelatedStart + '"');
      if (FRelatedStartInfo <> '') then
        Params.Add(strStartInfo + '"' + FRelatedStartInfo + '"');
    end;
    {!!.02}

    EncodeListHeader(strContentType, RawHeaders, Params, ';', False);
  finally
    Params.Free;
  end;
end;

{ Generate Content-TranferEncoding header into raw header list }
procedure TIpMimeEntity.EncodeContentTransferEncoding(RawHeaders : TStringList);
begin
  case FContentTransferEncoding of
    em7bit     : EncodeSingleHeader(strContentTransferEncoding, RawHeaders, str7Bit);
    em8bit     : EncodeSingleHeader(strContentTransferEncoding, RawHeaders, str8Bit);
    emBase64   : EncodeSingleHeader(strContentTransferEncoding, RawHeaders, strBase64);
    emBinary   : EncodeSingleHeader(strContentTransferEncoding, RawHeaders, strBinary);
    emBinHex   : EncodeSingleHeader(strContentTransferEncoding, RawHeaders, strBinHex);
    emQuoted   : EncodeSingleHeader(strContentTransferEncoding, RawHeaders, strQuoted);
    emUUEncode : EncodeSingleHeader(strContentTransferEncoding, RawHeaders, strUUEncode);
  end;
end;

{ Generate Mime headers into raw header list }
procedure TIpMimeEntity.EncodeMimeHeaders(RawHeaders : TStringList);
begin
  if (FContentType <> '') then begin
    EncodeSingleHeader(strMimeVersion, RawHeaders, FMimeVersion);
    EncodeContentType(RawHeaders);
    EncodeSingleHeader(strContentDescription, RawHeaders, FContentDescription);
    EncodeSingleHeader(strContentID, RawHeaders, FContentID);
    EncodeContentTransferEncoding(RawHeaders);
    EncodeContentDisposition(RawHeaders);
  end;
end;

{ Encode Mime body from TStream - file name is optional }
procedure TIpMimeEntity.EncodeBodyStream(InStream : TStream; const aFileName : string);
{Begin !!.12}
var
  LargeAttachment : Boolean;
    { Large attachments are handled with memory map streams in order to avoid
      whacko memory issues with TMemoryStream. }
begin
  if (Instream.Size > 0) then begin
    LargeAttachment := (InStream.Size > IpLgAttachSizeBoundry);
    if LargeAttachment then
      ClearBodyLargeAttach(InStream.Size)
    else
    begin
      ClearBody;
      // presize stream for more speed
      FBody.Stream.Size := Trunc(InStream.Size * 1.3695);
    end;
{End !!.12}
    case FContentTransferEncoding of
      em7Bit     : Encode8Bit(InStream);
      em8Bit     : Encode8Bit(InStream);
      emBase64   : EncodeBase64(InStream);
      emBinary   : Encode8Bit(InStream);
      emBinHex   : EncodeBinHex(InStream, aFileName);
      emQuoted   : EncodeQuoted(InStream);
      emUUEncode : EncodeUUEncode(InStream, aFileName);
      emUnknown  : Encode8Bit(InStream);
    end;
  {Begin !!.12}
    FBody.Flush;
    if LargeAttachment then
      { This is a large attachment that was written to a memory map stream.
        Memory map streams are usually created larger than necessary so shrink
        it down to the correct size. }
      TIpMemMapStream(FBody.Stream).Size := TIpMemMapStream(FBody.Stream).DataSize;
  {End !!.12}
  end;
  FOriginalSize := InStream.Size;
  FFileName := ExtractFileName(aFileName);
end;

{ Encode Mime body from TStrings - file name is optional }
procedure TIpMimeEntity.EncodeBodyStrings(InStrings : TStrings; const aFileName : string);
var
  MS : TMemoryStream;
begin
  if (InStrings.Count > 0) then begin
    MS := TMemoryStream.Create;
    try
      InStrings.SaveToStream(MS);
      MS.Position := 0;                                              {!!.03}
      FOriginalSize := MS.Size;
      FFileName := ExtractFileName(aFileName);
      EncodeBodyStream(MS, aFileName);
    finally
      MS.Free;
    end;
  end;
end;

{ Encode Mime body from file }
procedure TIpMimeEntity.EncodeBodyFile(const InFile : string);
var
  FS : TIpMemMapStream;                                                {!!.12}
  i : Integer;
  aExt, aTyp, aSub : string;
  aEnc : TIpMimeEncodingMethod;
begin
  { If content-type, has not been defined for this entity,    }
  { default values for that file extension  will be used.     }
  { These values are defined in the include file, IPDEFCT.INC }
  aTyp := strApplication;
  aSub := strOctetStream;
  aEnc := emBase64;
  aExt := ExtractFileExt(InFile);
  for i := 0 to High(DefExtensions) do
    if (aExt = DefExtensions[i]) then begin
      aTyp := DefContent[i].Typ;
      aSub := DefContent[i].Sub;
      aEnc := DefContent[i].Enc;
      Break;
    end;
  if (FContentType = '') then begin
    FContentType := aTyp;
    FContentSubtype := aSub;
    FContentTransferEncoding := aEnc;
  end;
  if (FContentTransferEncoding = emUnknown) then
    FContentTransferEncoding := aEnc;

  FS := TIpMemMapStream.Create(InFile, True, False);                   {!!.12}
  try
    FS.Open;                                                           {!!.12}
    FOriginalSize := FS.Size;
    FFileName := ExtractFileName(InFile);
    EncodeBodyStream(FS, FFileName);
  finally
    FS.Free;
  end;
end;

{ Decode encoded Mime block body to TStream }
procedure TIpMimeEntity.ExtractBodyStream(OutStream : TStream);
var
  MS : TMemoryStream;
begin
  if (FBody.Size > 0) then begin
   { We want to append the decoded data to the end of OutStream, }
   { so a local memory stream is used since OutStream may be a   }
   { TIpAnsiTextStream, in which case the decoding algorithms    }
   { will overwrite its existing contents.                       }
    MS := TMemoryStream.Create;
    try
      case FContentTransferEncoding of
        em7Bit     : Decode8Bit(MS);
        em8Bit     : Decode8Bit(MS);
        emBase64   : DecodeBase64(MS);
        emBinary   : OutStream.CopyFrom(FBody, FBody.Size);            {!!.14}
        emBinHex   : DecodeBinHex(MS);
        emQuoted   : DecodeQuoted(MS);
        emUUEncode : DecodeUUEncode(MS);
        emUnknown  : Decode8Bit(MS);
      end;
      OutStream.CopyFrom(MS, 0);
    finally
      MS.Free;
    end;
  end;
end;

{ Decode encoded Mime block body to TStrings }
procedure TIpMimeEntity.ExtractBodyStrings(OutStrings : TStrings);
var
  MS : TMemoryStream;
begin
  if (FBody.Size > 0) then begin
    MS := TMemoryStream.Create;
    try
      ExtractBodyStream(MS);
      MS.Position := 0;
      OutStrings.LoadFromStream(MS);
    finally
      MS.Free;
    end;
  end;
end;

{ Decode encoded Mime block body to file }
procedure TIpMimeEntity.ExtractBodyFile(const OutFile : string);
var
  FS : TFileStream;
begin
  if (FBody.Size > 0) then begin
    FS := TFileStreamUTF8.Create(OutFile, fmCreate);
    try
      ExtractBodyStream(FS);
    finally
      FS.Free;
    end;
  end;
end;

{ Access/create specified MIME part }
function TIpMimeEntity.GetMimePart(const aType, aSubType, aContentID : string;
                                       CanCreate : Boolean) : TIpMimeEntity;
var
  i : Integer;
begin
  Result := nil;
  if (MimeParts.Count > 0) then
    for i := 0 to Pred(MimeParts.Count) do
      { ContentID is primary search key }
      if (aContentID <> '') then begin
        if (MimeParts[i].ContentID = aContentID) then begin
          Result := MimeParts[i];
          Break;
        end;
      end else begin
        if (MimeParts[i].ContentType = aType) and
           (MimeParts[i].ContentSubtype = aSubType) then begin
          Result := MimeParts[i];
          Break;
        end;
      end;

  if Assigned(Result) then
    Result.Body.Position := 0
  else if CanCreate then begin
    Result := NewMimePart;
    Result.ContentType := aType;
    Result.ContentSubtype := aSubtype;
    Result.ContentID := aContentID;
  end;
end;

{!!.02}
{ Search all nested levels for specified MIME part }
function TIpMimeEntity.FindNestedMimePart(const aType, aSubType, aContentID : string) : TIpMimeEntity;
var
  i : Integer;
  Blk : TIpMimeEntity;
begin
  Result := nil;
  if (MimeParts.Count > 0) then
    for i := 0 to Pred(MimeParts.Count) do begin
      { ContentID is primary search key }
      if (aContentID <> '') and                                          {!!.12}
         (IsSameString (MimeParts[i].ContentID,                          {!!.12}
                        aContentID, False)) then begin                   {!!.12}
        Result := MimeParts[i];
        Break;
      end else if (IsSameString (MimeParts[i].ContentType,               {!!.12}
                                 aType, False)) and                      {!!.12}
                  (IsSameString (MimeParts[i].ContentSubtype,            {!!.12}
                                 aSubType, False)) then begin            {!!.12}
        Result := MimeParts[i];
        Break;
      end else begin
        Blk := MimeParts[i];
        Result := Blk.FindNestedMimePart(aType, aSubType, aContentID);
        if Assigned(Result) then
          Break;
      end;
    end;
  if Assigned(Result) then
    Result.Body.Position := 0;
end;

{ Create nested Mime block and add to list }
function TIpMimeEntity.NewMimePart : TIpMimeEntity;
begin
  {parent Entity is now multipart}
  FIsMime := True;
  FIsMultipart := True;
  FContentType := strMultipart;
  if (FBoundary = '') then
    FBoundary := GenerateBoundary;

  Result := TIpMimeEntity.Create(Self);
  FMimeParts.Add(Result);
end;

{ Copy Instream to OutStream as is - no decoding }
procedure TIpMimeEntity.Decode8Bit(OutStream : TStream);
var
  FS : TIpAnsiTextStream;
  Abort : Boolean;
begin
  Abort := False;
  FS := TIpAnsiTextStream.Create(OutStream);
  try
    FBody.Position := 0;
    while (FBody.Position < FBody.Size) and not Abort do begin
      FS.WriteLine(FBody.ReadLine);
      DoOnCodingProgress(OutStream.Position, FBody.Size, Abort);
    end;
  finally
    FS.Free;
  end;
end;

{ Decode InStream to OutStream - Base64 }
procedure TIpMimeEntity.DecodeBase64(OutStream : TStream);
  { rewritten }                                                      {!!.12}
var
  I : Integer;                                                         {!!.16}
  C : Char;
  InBuf  : array[0..3] of Char;
  OutBuf : array[0..2] of Byte;
  Done  : Boolean;
  Abort : Boolean;
  BufStream : TIpBufferedStream;
begin
  BufStream := (FBody as TIpBufferedStream);
  BufStream.Position := 0;
  Done := False;
  Abort := False;

  while not (Done or Abort) do begin
    { read in the next 4 valid Base64 characters }
    I := 0;
    InBuf := '====';                                                   {!!.15}
    while (I < 4) do begin
      if not BufStream.ReadChar(C) then begin
        Done := True;
        Break;
      end;

      { skip bad characters }
      if (Low(IpD64Table) <= C) and (C <= High(IpD64Table)) then
        if (IpD64Table[C] <> $7F) then begin
          InBuf[I] := C;
          Inc(I);
        end;
    end;

    { Decode 4 characters to 3 bytes }
    I := 0;
    OutBuf[0] := ((IpD64Table[InBuf[0]] shl 2) or (IpD64Table[InBuf[1]] shr 4));
    Inc(I);
    if InBuf[2] <> '=' then begin
      OutBuf[1] := ((IpD64Table[InBuf[1]] shl 4) or (IpD64Table[InBuf[2]] shr 2));
      Inc(I);
      if InBuf[3] <> '=' then begin
        OutBuf[2] := ((IpD64Table[InBuf[2]] shl 6) or IpD64Table[InBuf[3]]);
        Inc(I);
      end else
        Done := True;
    end else
        Done := True;
    OutStream.Write(OutBuf, I);
    DoOnCodingProgress(OutStream.Position, BufStream.FastSize, Abort); {!!.16}
  end;
end;

{ Decode InStream to OutStream - BinHex }
procedure TIpMimeEntity.DecodeBinHex(OutStream : TStream);
var
  InBuf : array[1..4] of Byte;
  OutBuf : array[1..3] of Byte;
  i : Byte;
  btThis, btLast, btNext : Byte;
  ch : AnsiChar;
  // headerlength is encoded as byte, HeaderFileName can only 256 bytes long
  HeaderFileName : Array [0..MaxByte] of Byte;                   {!!.12}{!!.16}
  HeaderLength : byte;                                                  {!!.12}
  CRC : Word;
  DataOffset, DataEnd, HeaderEnd : Longint;
  WS1, WS2 : TMemoryStream;
  Header : BinHexHeader;
  Abort : Boolean;
  BufStream : TIpBufferedStream;

  function NextChar : AnsiChar;
    {- skip past any CRLF's and return the next message stream char }
  var
    c : AnsiChar;
  begin
    c := #0;
    repeat
      BufStream.ReadChar(c);
    until ((c <> #13) and (c <> #10)) or (BufStream.Position = BufStream.Size);
    Result := c;
  end;

  function ValidChar(ch : AnsiChar) : Boolean;
    {- test if ch is a valid BinHex encoded char }
  var
    b : Byte;
  begin
    Result := False;
    b := Ord(ch);
    if (b > 32) and (b < 115) then
      if IpHexBinTable[b] <> $0FF then
        Result := True;
  end;

begin
  Abort := False;
  FBody.Position := 0;
  if Pos('(This file must be converted with BinHex', FBody.ReadLine) = 0 then
    raise EIpBaseException.Create(SBinHexBadFormat);
  if (NextChar <> ':') then
    raise EIpBaseException.Create(SBinHexColonExpected);

  { decode attachment into working stream }
  BufStream := (FBody as TIpBufferedStream);
  WS1 := TMemoryStream.Create;
  try
    i := 0;
    ch := NextChar;
    while (ch <> ':') and (BufStream.Position < BufStream.Size) and not Abort do begin
      if not ValidChar(ch) then
        raise EIpBaseException.Create(SBinHexBadChar);
      Inc(i);
      InBuf[i] := IpHexBinTable[Ord(ch)];
      { decode 4 characters into 3 bytes }
      if (i = 4) then begin
        i := 0;
        { 1st :    upper 6          lower 2 }
        OutBuf[1] := (InBuf[1] shl 2) or ((InBuf[2] shr 4) and $03);
        { 2nd :    upper 4          lower 4 }
        OutBuf[2] := (InBuf[2] shl 4) or ((InBuf[3] shr 2) and $0F);
        { 3rd :    upper 2          lower 6 }
        OutBuf[3] := (InBuf[3] shl 6) or (InBuf[4] and $03F);
        WS1.Write(OutBuf, SizeOf(OutBuf));
      end;
      ch := NextChar;
    end;

    { handle odd characters }
    if (i > 0) then begin
      if (i = 1) then
        raise EIpBaseException.Create(SBinHexOddChar);
      OutBuf[1] := (InBuf[1] shl 2) or ((InBuf[2] shr 4) and $03);
      if (i = 2) then
        WS1.Write(OutBuf, 1)
      else begin
        OutBuf[2] := (InBuf[2] shl 4) or ((InBuf[3] shr 2) and $0F);
        WS1.Write(OutBuf, 2);
      end;
      DoOnCodingProgress(BufStream.Position, BufStream.Size, Abort);
    end;
    if Abort then
      Exit;

    { should be the end of file marker }
    if (ch <> ':') then
      raise EIpBaseException.Create(SBinHexColonExpected);

    { expand RLE sequences }
    WS2 := TMemoryStream.Create;
    try
      WS1.Position := 0;
      btThis := 0;
      while (WS1.Position < WS1.Size) and not Abort do begin
        btLast := btThis;
        WS1.Read(btThis, 1);
        if (btThis <> RLEChar) then
          WS2.Write(btThis, 1)
        else begin
          WS1.Read(btNext, 1);
          if (btNext = 0) then
            WS2.Write(btThis, 1)
          else begin
            btThis := btLast;
            for i := 1 to (btNext - 1) do
              WS2.Write(btThis, 1);
          end;
        end;
        DoOnCodingProgress(WS1.Position, WS1.Size, Abort);
      end;
      if Abort then
        WS2.Free;

      { strip off header }
      FillChar (HeaderFileName, SizeOf (HeaderFileName), $00);           {!!.12}
      FillChar(Header, SizeOf(Header), #0);
      WS2.Position := 0;
      WS2.Read(HeaderLength, SizeOf (Byte));                             {!!.12}
      WS2.Read(HeaderFileName, HeaderLength);                            {!!.12}
      WS2.Read(Header, SizeOf(Header));

      { check header CRC }
      HeaderEnd := WS2.Position;
      WS2.Read(CRC, 2);
      DataOffset := WS2.Position;
      if (CRC <> BinHexCRC(WS2, 0, HeaderEnd)) then
        raise EIpBaseException.Create(SBinHexBadHeaderCRC);
      DataEnd := DataOffset + htonl(Header.DFLong);
      if (DataEnd > WS2.Size) then
        raise EIpBaseException.Create(SBinHexLengthErr);
      if (htonl(Header.RFLong) > 0) then
        raise EIpBaseException.Create(SBinHexResourceForkErr);

      { check data fork CRC - follows data fork }
      WS2.Position := DataEnd;
      WS2.Read(CRC, 2);
      if (CRC <> BinHexCRC(WS2, DataOffset, DataEnd)) then
        raise EIpBaseException.Create(SBinHexBadDataCRC);

      { copy data fork to OutStream }
      WS2.Position := DataOffset;
      OutStream.CopyFrom(WS2, DataEnd - DataOffset);
    finally
      WS2.Free;
    end;
  finally
    WS1.Free;
  end;
end;

{ Decode InStream to OutStream - QuotedPrintable }
procedure TIpMimeEntity.DecodeQuoted(OutStream : TStream);
var
  O, Count, WS : Byte;                                                   {!!.12}
  I : integer;                                                           {!!.12}
  InBuf  : array[0..pred (MaxLine)] of Byte;                             {!!.15}
  OutBuf : array[0..pred (MaxLine)] of Byte;                             {!!.15}
  Decoding : Boolean;
  Keeper : Boolean;
  Abort : Boolean;
  BufStream : TIpBufferedStream;
begin
  Abort := False;
  FBody.Position := 0;
  BufStream := FBody as TIpBufferedStream;
  FillChar(InBuf, SizeOf(InBuf), #0);
  WS := $FF;
  Decoding := True;
  Keeper := False;

  { Skip any CR/LF's to get to the encoded stuff }
  while True do begin
    if not BufStream.ReadChar(Char(InBuf[0])) then
      Exit;
    if ((InBuf[0] <> $0D) and (InBuf[0] <> $0A)) then begin
      Keeper := True;
      Break;
    end;
  end;

  while Decoding and not Abort do begin
    { Initialize }
    if Keeper then begin
      I := 1;
      Keeper := False;
    end else begin
      I := 0;
    end;
    O := 0;

    { Read in one line at a time - skipping over bad characters }
    while True do begin
      if (I > High(InBuf)) then                                        {!!.01}
        raise EIpBaseException.Create(SLineLengthErr);                 {!!.01}
      if not BufStream.ReadChar(Char(InBuf[I])) then
        Break;
      case InBuf[I] of
        $0A : Continue;
        $0D : begin
                Inc(I);
                Break;
              end;
       { Test for potential end of data }
       { '--' is probably the next Mime boundary }
       { $2D : if (I = 1) and (InBuf[0] = $2D) then Exit;}             {!!.03}
      end;
      Inc(I);
    end;

    if I = 0 then Exit;
    Count := I;
    I := 0;

    { Decode data to output stream }
    while I < Count do begin
      case InBuf[I] of
        9       : begin
                    if WS = $FF then
                      WS := O;
                    OutBuf[O] := InBuf[I];
                    Inc(O);
                    Inc(I);
                  end;
        13      : if WS = $FF then begin
                    OutBuf[O] := 13;
                    OutBuf[O+1] := 10;
                    Inc(O, 2);
                    Inc(I);
                  end else begin
                    OutBuf[WS] := 13;
                    OutBuf[WS+1] := 10;
                    O := WS+2;
                    Inc(I);
                  end;
        32      : begin
                    if WS = $FF then
                      WS := O;
                    OutBuf[O] := InBuf[I];
                    Inc(O);
                    Inc(I);
                  end;
        33..60  : begin
                    WS := $FF;
                    OutBuf[O] := InBuf[I];
                    Inc(O);
                    Inc(I);
                  end;
        61      : begin
                    WS := $FF;
                    if I+2 >= Count then Break;
                    case InBuf[I+1] of
                      48 : OutBuf[O] := 0;    {0}
                      49 : OutBuf[O] := 16;   {1}
                      50 : OutBuf[O] := 32;   {2}
                      51 : OutBuf[O] := 48;   {3}
                      52 : OutBuf[O] := 64;   {4}
                      53 : OutBuf[O] := 80;   {5}
                      54 : OutBuf[O] := 96;   {6}
                      55 : OutBuf[O] := 112;  {7}
                      56 : OutBuf[O] := 128;  {8}
                      57 : OutBuf[O] := 144;  {9}
                      65 : OutBuf[O] := 160;  {A}
                      66 : OutBuf[O] := 176;  {B}
                      67 : OutBuf[O] := 192;  {C}
                      68 : OutBuf[O] := 208;  {D}
                      69 : OutBuf[O] := 224;  {E}
                      70 : OutBuf[O] := 240;  {F}
                      97 : OutBuf[O] := 160;  {a}
                      98 : OutBuf[O] := 176;  {b}
                      99 : OutBuf[O] := 192;  {c}
                     100 : OutBuf[O] := 208;  {d}
                     101 : OutBuf[O] := 224;  {e}
                     102 : OutBuf[O] := 240;  {f}
                    end;
                    case InBuf[I+2] of
                      48 : ;                             {0}
                      49 : OutBuf[O] := OutBuf[O] + 1;   {1}
                      50 : OutBuf[O] := OutBuf[O] + 2;   {2}
                      51 : OutBuf[O] := OutBuf[O] + 3;   {3}
                      52 : OutBuf[O] := OutBuf[O] + 4;   {4}
                      53 : OutBuf[O] := OutBuf[O] + 5;   {5}
                      54 : OutBuf[O] := OutBuf[O] + 6;   {6}
                      55 : OutBuf[O] := OutBuf[O] + 7;   {7}
                      56 : OutBuf[O] := OutBuf[O] + 8;   {8}
                      57 : OutBuf[O] := OutBuf[O] + 9;   {9}
                      65 : OutBuf[O] := OutBuf[O] + 10;  {A}
                      66 : OutBuf[O] := OutBuf[O] + 11;  {B}
                      67 : OutBuf[O] := OutBuf[O] + 12;  {C}
                      68 : OutBuf[O] := OutBuf[O] + 13;  {D}
                      69 : OutBuf[O] := OutBuf[O] + 14;  {E}
                      70 : OutBuf[O] := OutBuf[O] + 15;  {F}
                      97 : OutBuf[O] := OutBuf[O] + 10;  {a}
                      98 : OutBuf[O] := OutBuf[O] + 11;  {b}
                      99 : OutBuf[O] := OutBuf[O] + 12;  {c}
                     100 : OutBuf[O] := OutBuf[O] + 13;  {d}
                     101 : OutBuf[O] := OutBuf[O] + 14;  {e}
                     102 : OutBuf[O] := OutBuf[O] + 15;  {f}
                    end;
                    Inc(I, 3);
                    Inc(O);
                  end;
        62..126 : begin
                    WS := $FF;
                    OutBuf[O] := InBuf[I];
                    Inc(O);
                    Inc(I);
                  end;
        else
          Inc(I);
      end;
    end;

    if O>0 then
      OutStream.Write(OutBuf, O)
    else
      Break;   { OutBuf is empty }
    DoOnCodingProgress(OutStream.Position, FBody.Size, Abort);
  end;
end;

{ Decode InStream to OutStream - UUEncode }
procedure TIpMimeEntity.DecodeUUEncode(OutStream : TStream);
var
  I, O, Len, Count : Byte;
  InBuf  : array[0..85] of Byte;
  OutBuf : array[0..65] of Byte;
  FirstLine : Boolean;
  Abort : Boolean;
  BufStream : TIpBufferedStream;
begin
  Abort := False;
  FBody.Position := 0;
  BufStream := FBody as TIpBufferedStream;
  FirstLine := True;
  while True and not Abort do begin
    { Initialize }
    I := 0;
    O := 0;

    { Skip any CR/LF's to get to the encoded stuff }
    while True do begin
      if not BufStream.ReadChar(Char(InBuf[0])) then
        Exit;
      if FirstLine then begin
        if ((InBuf[0] <> $0D) and (InBuf[0] <> $0A)) then begin
          FirstLine := False;
          Break;
        end;
     end else begin
        if ((InBuf[0] = $0D) or (InBuf[0] = $0A)) then FirstLine := True;
      end;
    end;

    { We're done }
    if AnsiChar(InBuf[0]) = '`' then Exit;

    { Get count for this line }
    Len := (((InBuf[0] - $20) and $3F) * 4) div 3;
    if (((InBuf[0] - $20) and $3F) * 4) mod 3 <> 0 then
      Inc(Len);

    Count := FBody.Read(InBuf, Len);

    { Unexpected situation }
    if (Count <> Len) or (Count > 63) then
      raise EIpBaseException.Create(SUUEncodeCountErr);

    { Decode buffer }
    while (I < Count) do begin
      if ((Count - I) >= 4) then begin
        OutBuf[O] := (((InBuf[I] - $20) and $3F) shl 2) or
          (((InBuf[I+1] - $20) and $3F) shr 4);
        OutBuf[O+1] := (((InBuf[I+1] - $20) and $3F) shl 4) or
          (((InBuf[I+2] - $20) and $3F) shr 2);
        OutBuf[O+2] := (((InBuf[I+2] - $20) and $3F) shl 6) or
          (((InBuf[I+3] - $20) and $3F));
        Inc(O, 3);
      end else begin
        if (Count >= 2) then begin
          OutBuf[O] := (((InBuf[I] - $20) and $3F) shl 2) or
            (((InBuf[I+1] - $20) and $3F) shr 4);
          Inc(O);
        end;
        if (Count >= 3) then begin
          OutBuf[O+1] := (((InBuf[I+1] - $20) and $3F) shl 4) or
            (((InBuf[I+2] - $20) and $3F) shr 2);
          Inc(O);
        end;
      end;
      Inc(I, 4);
    end;
    OutStream.Write(OutBuf, O);
    DoOnCodingProgress(OutStream.Position, FBody.Size, Abort);
  end;
end;

{ Encode InStream to OutStream - as is, no encoding }
procedure TIpMimeEntity.Encode8Bit(InStream : TStream);
var
  FS : TIpAnsiTextStream;
  Abort : Boolean;
begin
  Abort := False;
  FS := TIpAnsiTextStream.Create(InStream);
  try
    while not (FS.AtEndOfStream or Abort) do begin
      FBody.WriteLine(FS.ReadLine);
      DoOnCodingProgress(FS.Position, FS.Size, Abort);
    end;
  finally
    FS.Free;
  end;
end;

{ Encode InStream to OutStream - Base64 }
procedure TIpMimeEntity.EncodeBase64(InStream : TStream);
begin
  OctetStreamToHextetStream(InStream, FBody, Ip64Table, '=', #0);
end;

{ Encode InStream to OutStream - BinHex }
procedure TIpMimeEntity.EncodeBinHex(InStream : TStream;
                                     const aFileName : string);
var
  HeaderFileName : string;                                              {!!.12}
  CRC : Word;
  DataOffset : DWord;
  PrevByte, CurrByte, i : Byte;
  Header : BinHexHeader;
  WS1, WS2 : TMemoryStream;
  Abort : Boolean;

begin
  Abort := False;
  WS1 := TMemoryStream.Create;
  try
    { start with file name }
    if (Length(aFileName) < MaxLine) then
      HeaderFileName := UpperCase(ExtractFileName(aFileName))
    else
      HeaderFileName := Copy(UpperCase(ExtractFileName(aFileName)), 1, MaxLine);
    WS1.Write(HeaderFileName, Length(HeaderFileName) + 1);

    { build rest of file header and header CRC and add to working stream }
    FillChar(Header, SizeOf(Header), #0);
    Move(BinHexFileType, Header.FileType, SizeOf(Header.FileType));
    Move(BinHexFileType, Header.Creator, SizeOf(Header.Creator));
    Header.DFLong := htonl(InStream.Size);
    Header.RFLong := 0;
    WS1.Write(Header, SizeOf(Header));
    CRC := BinHexCRC(WS1, 0, WS1.Size);
    WS1.Write(CRC, 2);

    { append data fork and data CRC to working stream }
    DataOffset := WS1.Position;
    InStream.Position := 0;
    WS1.CopyFrom(InStream, InStream.Size);
    CRC := BinHexCRC(WS1, DataOffset, WS1.Size);
    WS1.Write(CRC, 2);

    { tack on resource fork CRC - not used but still required }
    CRC := 0;
    WS1.Write(CRC, 2);

    { go back and compress RLE sequences }
    WS2 := TMemoryStream.Create;
    try
      WS1.Position := 0;
      CurrByte := 0;
      while (WS1.Position < WS1.Size) and not Abort do begin
        PrevByte := CurrByte;
        WS1.Read(CurrByte, 1);
        if (CurrByte <> PrevByte) then
          WS2.Write(CurrByte, 1)
        else begin
          i := 1;
          repeat
            i := i + WS1.Read(CurrByte, 1);
          until (CurrByte <> PrevByte) or (i = 255) or
                (WS1.Position = WS1.Size);
          if (i > 2) then begin
            WS2.Write(RLEChar, 1);
            WS2.Write(i, 1);
            WS2.Write(CurrByte, 1);
          end else begin
            WS2.Write(PrevByte, 1);
            WS2.Write(CurrByte, 1);
          end;
        end;
        DoOnCodingProgress(WS1.Position, WS1.Size, Abort);
      end;
      if Abort then
        Exit;

      { write out preamble }
      FBody.WriteLine('(This file must be converted with BinHex 4.0)');

      { Encode compressed stream and stream it out }
      WS2.Position := 0;
      OctetStreamToHextetStream(WS2, FBody, IpBinHexTable, #0, ':');
    finally
      WS2.Free;
    end;
  finally
    WS1.Free;
  end;
end;

{ Encode InStream to OutStream - QuotedPrintable }
procedure TIpMimeEntity.EncodeQuoted(InStream : TStream);
var
  O, W : Integer;
  WordBuf, OutBuf : array[0..80] of AnsiChar;
  CurChar : AnsiChar;
  Abort : Boolean;
  ByteStream : TIpByteStream;

  procedure SendLine;
  begin
    if (OutBuf[O-1] = #9) or (OutBuf[O-1] = #32) then begin
      OutBuf[O] := '=';
      Inc(O);
    end;
    FBody.WriteLineZ(OutBuf);
    FillChar(OutBuf, SizeOf(OutBuf), #0);
    O := 0;
  end;

  procedure AddWordToOutBuf;
  var
    J : Integer;
  begin
    if (O + W) > 74 then SendLine;
    for J := 0 to (W - 1) do begin
      OutBuf[O] := WordBuf[J];
      Inc(O);
    end;
    W := 0;
  end;

  procedure AddHexToWord(B : Byte);
  begin
    if W > 73 then AddWordToOutBuf;
    WordBuf[W] := '=';
    WordBuf[W+1] := HexDigits[B shr 4];
    WordBuf[W+2] := HexDigits[B and $F];
    Inc(W, 3)
  end;

begin
  Abort := False;
  O := 0;
  W := 0;
  FillChar(OutBuf, SizeOf(OutBuf), #0);
  ByteStream := TIpByteStream.Create(InStream);
  try
    while ByteStream.Read(Byte(CurChar)) and not Abort do begin
      if (Ord(CurChar) in [33..60, 62..126]) then begin
        WordBuf[W] := CurChar;
        Inc(W);
        if W > 74 then AddWordToOutBuf;
      end else if (CurChar = ' ') or (CurChar = #9) then begin
        WordBuf[W] := CurChar;
        Inc(W);
        AddWordToOutBuf;
      end else if (CurChar = #13) then begin
        AddWordToOutBuf;
        SendLine;
      end else if (CurChar = #10) then begin
        { Do nothing }
      end else begin
        AddHexToWord(Byte(CurChar));
      end;
      DoOnCodingProgress(ByteStream.Position, ByteStream.Size, Abort);
    end;
  finally
    ByteStream.Free;
  end;
end;

{ Encode InStream to OutStream - UUEncode }
procedure TIpMimeEntity.EncodeUUEncode(InStream : TStream;
                                       const aFileName : string);
var
  I, O, Count, Temp : Byte;
  InBuf  : array[1..45] of Byte;
  OutBuf : array[0..63] of AnsiChar;
  Abort : Boolean;
begin
  Abort := False;
  FBody.WriteLine('begin 600 ' + aFileName);

  { Encode and stream the attachment }
  repeat
    Count := InStream.Read(InBuf, SizeOf(InBuf));
    if Count <= 0 then Break;
    I := 1;
    O := 0;
    OutBuf[O] := AnsiChar(IpUUTable[Count and $3F]);
    Inc(O);
    while I+2 <= Count do begin
      { Encode 1st byte }
      Temp := (InBuf[I] shr 2);
      OutBuf[O] := AnsiChar(IpUUTable[Temp and $3F]);

      { Encode 1st/2nd byte }
      Temp := (InBuf[I] shl 4) or (InBuf[I+1] shr 4);
      OutBuf[O+1] := AnsiChar(IpUUTable[Temp and $3F]);

      { Encode 2nd/3rd byte }
      Temp := (InBuf[I+1] shl 2) or (InBuf[I+2] shr 6);
      OutBuf[O+2] := AnsiChar(IpUUTable[Temp and $3F]);

      { Encode 3rd byte }
      Temp := (InBuf[I+2] and $3F);
      OutBuf[O+3] := AnsiChar(IpUUTable[Temp]);

      Inc(I, 3);
      Inc(O, 4);
    end;

    { Are there odd bytes to add? }
    if (I <= Count) then begin
      Temp := (InBuf[I] shr 2);
      OutBuf[O] := AnsiChar(IpUUTable[Temp and $3F]);

      { One odd byte }
      if (I = Count) then begin
        Temp := (InBuf[I] shl 4) and $30;
        OutBuf[O+1] := AnsiChar(IpUUTable[Temp and $3F]);
        Inc(O, 2);
      { Two odd bytes }
      end else begin
        Temp := ((InBuf[I] shl 4) and $30) or ((InBuf[I+1] shr 4) and $0F);
        OutBuf[O+1] := AnsiChar(IpUUTable[Temp and $3F]);
        Temp := (InBuf[I+1] shl 2) and $3C;
        OutBuf[O+2] := AnsiChar(IpUUTable[Temp and $3F]);
        Inc(O, 3);
      end;
    end;

    { Add CR/LF }
    OutBuf[O] := #13;
    OutBuf[O+1] := #10;

    { Write line to stream }
    FBody.Write(OutBuf, (O + 2));
    DoOnCodingProgress(InStream.Position, InStream.Size, Abort);
  until (Count < SizeOf(InBuf)) or Abort;

  { Add terminating end }
  FBody.WriteLine('`');
  FBody.WriteLine('end');
end;

{ Translate each 3 bytes into 4 hextets and encode according to table }
procedure TIpMimeEntity.OctetStreamToHextetStream(InStream : TStream;
                                                  OutStream : TIpAnsiTextStream;
                                                  const Table;
                                                  PadChar, Delim : AnsiChar);
var
  OutBuf: array[0..MaxLineEncode-1] of Char;                           {!!.12}{!!.13}
  OutBufLen: Integer;                                                  {!!.12}
  Abort : Boolean;

  procedure FlushOutBuf;
    {- write out encoded buffer to message stream }
  begin
    if OutBufLen > 0 then begin                                        {!!.12}
      OutStream.WriteLineArray(OutBuf, OutBufLen);
      OutBufLen := 0;                                                  {!!.12}
    end;
  end;

  procedure OutChar(ch : AnsiChar);
    {- buffer the character to go out }
  begin
    if OutBufLen >= MaxLineEncode - 1 then                             {!!.12}{!!.13}
      FlushOutBuf;
    OutBuf[OutBufLen] := Ch;                                           {!!.12}
    inc(OutBufLen);                                                    {!!.12}
  end;

type
  TBuffer = array[0..MaxInt-1] of Byte;
var
  Buffer: ^TBuffer;
  I, Count: Cardinal;
begin
  if InStream is TMemoryStream then
    Buffer := (InStream as TMemoryStream).Memory
  else
    if InStream is TIpMemMapStream then
      Buffer := (InStream as TIpMemMapStream).Memory
    else
      raise EIpBaseException.Create(SNoMemoryStreamErr);

  Abort := False;
  OutBufLen := 0;                                                      {!!.12}
  if (Delim <> #0) then
    OutChar(Delim);

  { Encode and stream the attachment }
  I := 0;
  Count := InStream.Size div 3 * 3;
  while I < Count do
  begin
    { Encode 1st byte }
    OutBuf[OutBufLen] := Char(TIp6BitTable(Table)[Buffer[I] shr 2]);

    { Encode 1st/2nd byte }
    OutBuf[OutBufLen+1] := Char(TIp6BitTable(Table)[((Buffer[I] shl 4) or (Buffer[I+1] shr 4)) and $3F]);

    { Encode 2nd/3rd byte }
    OutBuf[OutBufLen+2] := Char(TIp6BitTable(Table)[((Buffer[I+1] shl 2) or (Buffer[I+2] shr 6)) and $3F]);

    { Encode 3rd byte }
    OutBuf[OutBufLen+3] := Char(TIp6BitTable(Table)[Buffer[I+2] and $3F]);

    Inc(OutBufLen, 4);
    if OutBufLen >= MaxLineEncode - 1 then                             {!!.12}{!!.13}
    begin
      FlushOutBuf;
      if i mod 100 = 0 then
        DoOnCodingProgress(I, Count, Abort);
      if Abort then
        break;
    end;
    Inc(I, 3);
  end;

  Count := InStream.Size;
  { Are there odd bytes to add? }
  if (I < Count) then begin
    OutChar(TIp6BitTable(Table)[Buffer[I] shr 2]);

    { One odd byte }
    if I = Count-1 then begin
      OutChar(TIp6BitTable(Table)[(Buffer[I] shl 4) and $30]);

      if (PadChar <> #0) then
        OutChar(PadChar);
    { Two odd bytes }
    end else begin
      OutChar(TIp6BitTable(Table)[((Buffer[I] shl 4) and $30) or (((Buffer[I+1] shr 4) and $0F)) and $3F]);
      OutChar(TIp6BitTable(Table)[(Buffer[I+1] shl 2) and $3C]);
    end;
    { Add padding }
      if (PadChar <> #0) then
        OutChar(PadChar);
  end;

  if (Delim <> #0) then
    OutChar(Delim);
  FlushOutBuf;
end;

{Begin !!.12}
procedure TIpMIMEEntity.ReadBody(InStream : TIpAnsiTextStream; const StartLine : string);
var
  S : string;
begin
  S := StartLine;
  { read in message body up to message terminator '.' }
  {while not ((S = '.') or AtEndOfStream) do begin}
  while not InStream.AtEndOfStream do begin
    Body.WriteLine(S);
    S := InStream.ReadLine;
  end;
  { write final line }
  Body.WriteLine(S);
end;
{End !!.12}


{ TIpMessage }
constructor TIpMessage.CreateMessage;
begin
  inherited Create(nil);
  FBCC        := TStringList.Create;
  FCC         := TStringList.Create;
  FNewsgroups := TStringList.Create;
  FPath       := TStringList.Create;
  FReceived   := TStringList.Create;
  FRecipients := TStringList.Create;
  FReferences := TStringList.Create;
  FUserFields := TStringList.Create;
  FHeaders    := TIpHeaderCollection.Create (Self);                    {!!.12}
  MsgStream := TIpAnsiTextStream.CreateEmpty;
  NewMessageStream;
end;

destructor TIpMessage.Destroy;
begin
  Clear;
  FBCC.Free;
  FCC.Free;
  FNewsgroups.Free;
  FPath.Free;
  FReceived.Free;
  FRecipients.Free;
  FReferences.Free;
  FUserFields.Free;
  FHeaders.Free;                                                         {!!.12}
  MsgStream.FreeStream;
  MsgStream.Free;
  inherited Destroy;
end;

{Begin !!.13}
procedure TIpMessage.CheckAllHeaders;
var
  i         : Integer;
  j         : Integer;
  HeaderNum : Integer;
begin
  FAttachmentCount := 0;

  { Roll through the list of headers specifically handled by iPRO.
    When one is found, move it into the data structure specific to that
    header field. }
  for i := 0 to IpMaxHeaders - 1 do begin
    if (IpHeaderXRef[i].FieldType = htUserFields) or
       (IpHeaderXRef[i].FieldType = htReceived) then begin
      for j := 0 to Headers.Count - 1 do begin
        if StrLIComp (PChar (IpHeaderXRef[i].FieldString),
                      PChar (Headers.Items[j].Name),
                      Length (IpHeaderXRef[i].FieldString)) = 0 then
          CheckHeaderType (Headers.Items[j],
                           IpHeaderXRef[i].FieldType);
      end;
      
    end else begin
      HeaderNum := Headers.HasHeader (IpHeaderXRef[i].FieldString);
      if HeaderNum >= 0 then
        CheckHeaderType (Headers.Items[HeaderNum],
                         IpHeaderXRef[i].FieldType);
    end;
  end;
end;

procedure TIpMessage.CheckHeaderType (HeaderInfo : TIpHeaderItem;
                                      HeaderType : TIpHeaderTypes);

  function ExtractSingleHeader(HeaderInfo : TIpHeaderItem) : string;
  begin
    Result := Trim(HeaderInfo.Value.Text);
    HeaderInfo.IsProperty := True;                                     {!!.13}
  end;

  procedure ExtractCSVHeader(HeaderInfo : TIpHeaderItem;
                         var AList      : TStringList);
  var
    WorkString : string;
  begin
    WorkString := ExtractSingleHeader(HeaderInfo);
    Parse (WorkString, ',', AList);
    HeaderInfo.IsProperty := True;                                     {!!.13}
  end;

  procedure ExtractListHeader(HeaderInfo : TIpHeaderItem;
                           var AList      : TStringList);
  begin
    AList.Assign (HeaderInfo.Value);
    HeaderInfo.IsProperty := True;                                     {!!.13}
  end;

  procedure ExtractAppendListHeader(HeaderInfo : TIpHeaderItem;
                              const IncludeName : Boolean;             {!!.13}
                                var AList      : TStringList);
  var
    i : Integer;
  begin
    for i := 0 to HeaderInfo.Value.Count - 1 do
{Begin !!.13}
      if IncludeName then
        AList.Add (HeaderInfo.Name + ': ' + HeaderInfo.Value[i])
      else
        AList.Add (HeaderInfo.Value[i]);
    HeaderInfo.IsProperty := True;
{End !!.13}
  end;

begin
  case HeaderType of
    htBCC             :
      ExtractCSVHeader(HeaderInfo, FBCC);
    htCC              :
      ExtractCSVHeader(HeaderInfo, FCC);
    htControl         :
      FControl := ExtractSingleHeader(HeaderInfo);
    htDate            :
      FDate := ExtractSingleHeader(HeaderInfo);
    htDispositionNotify :
      FDispositionNotify := ExtractSingleHeader(HeaderInfo);
    htFrom            :
      FFrom := ExtractSingleHeader(HeaderInfo);
    htFollowUp        :
      FFollowUpTo := ExtractSingleHeader(HeaderInfo);
    htInReplyTo       :
      FInReplyTo := ExtractSingleHeader(HeaderInfo);
    htKeywords        :
      FKeywords := ExtractSingleHeader(HeaderInfo);
    htMessageID       :
      FMessageID := ExtractSingleHeader(HeaderInfo);
    htNewsgroups      :
      ExtractCSVHeader(HeaderInfo, FNewsgroups);
    htNNTPPostingHost :
      FNNTPPostingHost := ExtractSingleHeader(HeaderInfo);
    htOrganization    :
      FOrganization := ExtractSingleHeader(HeaderInfo);
    htPath            :
      ExtractListHeader(HeaderInfo, FPath);
    htPostingHost     :
      FPostingHost := ExtractSingleHeader(HeaderInfo);
    htReceived        :
      ExtractAppendListHeader(HeaderInfo, False, FReceived);           {!!.13}
    htReferences      :
      ExtractListHeader(HeaderInfo, FReferences);
    htReplyTo         :
      FReplyTo := ExtractSingleHeader(HeaderInfo);
    htReturnPath      :
      FReturnPath := ExtractSingleHeader(HeaderInfo);
    htSender          :
      FSender := ExtractSingleHeader(HeaderInfo);
    htSubject         :
      FSubject := ExtractSingleHeader(HeaderInfo);
    htTo              :
      ExtractCSVHeader(HeaderInfo, FRecipients);
    htUserFields      :
      ExtractAppendListHeader(HeaderInfo, True, FUserFields);          {!!.13}
    htXIpro           : begin
    end;
  end;
end;
{End !!.12}

{ Clear properties and free message stream }
procedure TIpMessage.Clear;
begin
  inherited Clear;

  FAttachmentCount := 0;                                               {!!.12}
  FMessageTag := 0;                                                    {!!.15}

  FBCC.Clear;
  FCC.Clear;
  FDate := '';
  FDispositionNotify := '';                                            {!!.12}
  FFrom := '';
  FInReplyTo := '';
  FKeywords := '';
  FFollowupTo := '';                                                   {!!.15}
  FControl := '';                                                      {!!.15}
  FMessageID := '';
  FNewsgroups.Clear;
  FNNTPPostingHost := '';
  FOrganization := '';
  FPath.Clear;
  FPostingHost := '';
  FReceived.Clear;
  FRecipients.Clear;
  FReferences.Clear;
  FReplyTo := '';
  FReturnPath := '';
  FSender := '';
  FSubject := '';
  FUserFields.Clear;
  FHeaders.Clear;                                                      {!!.15}
  MsgStream.FreeStream;
end;

{Begin !!.12}
{ Get headers, body, and MIME parts (if any) }
procedure TIpMessage.DecodeMessage;

var
  AttDepth     : Integer;

  function IsAttachmentStart (const s : string) : Boolean;
  type
    TAttState = (asBegin, asHaveBegin,
                 asNumber1, asNumberSp,
                 asOpenCurly, asNumber2, asNumber2Sp, asCloseCurly,
                 asQuote1, asDblQuote1, AsAlnum1);

  var
    State : TAttState;
    i     : Integer;
    SLen  : Integer;

  begin
    Result := False;
    State  := asBegin;
    i      := 1;
    SLen   := Length (s);

    while i < SLen do begin
      case State of
        asBegin     : begin
          if s[i] in [' ', #09] then
            Inc (i)
          else if LowerCase (Copy (s, i, 5)) = 'begin' then begin
            State := asHaveBegin;
            Inc (i, 5);
          end else
            Break;
        end;

        asHaveBegin : begin
          if s[i] in [' ', #09] then
            Inc (i)
          else if s[i] = '{' then begin
            Inc (i);
            State := asNumber2;
          end else if s[i] in ['0'..'9'] then begin
            Inc (i);
            State := asNumber1;
          end else
            Break;
        end;

        asNumber1 : begin
          if s[i] in ['0'..'9'] then
            Inc (i)
          else if s[i] in [' ', #09] then begin
            Inc (i);
            State := asNumberSp;
          end else
            Break;
        end;

        asNumberSp : begin
          if s[i] in [' ', #09] then
            Inc (i)
          else if s[i] = '"' then begin
            Inc (i);
            State := asDblQuote1;
          end else if s[i] = '''' then begin
            Inc (i);
            State := asQuote1;
          end else if s[i] in ['!'..'~'] then begin
            Inc (i);
            State := asAlNum1;
          end else
            Break;
        end;

        asOpenCurly : begin
          if s[i] in [' ', #09] then
            Inc (i)
          else if s[i] in ['0'..'9'] then begin
            Inc (i);
            State := asNumber2;
          end else
            Break;
        end;

        asNumber2 : begin
          if s[i] in ['0'..'9'] then
            Inc (i)
          else if s[i] in [' ', #09] then begin
            Inc (i);
            State := asNumber2Sp;
          end else if s[i] = '}' then begin
            State := asCloseCurly;
            Inc (i);
          end else
            Break;
        end;

        asNumber2Sp : begin
          if s[i] in [' ', #09] then
            Inc (i)
          else if s[i] = '}' then begin
            Inc (i);
            State := asCloseCurly;
          end else
            Break;
        end;

        asCloseCurly : begin
          if s[i] in [' ', #09] then
            Inc (i)
          else if s[i] = '"' then begin
            Inc (i);
            State := asDblQuote1;
          end else if s[i] = '''' then begin
            Inc (i);
            State := asQuote1;
          end else
            Break;
        end;

        asQuote1 : begin
          if s[i] in [' '..'&', '('..'~'] then
            Inc (i)
          else if s[i] = '''' then begin
            Result := True;
            Break;
          end else
            Break;
        end;

        asDblQuote1 : begin
          if s[i] in [' '..'!', '#'..'~'] then
            Inc (i)
          else if s[i] = '"' then begin
            Result := True;
            Break;
          end else
            Break;
        end;

        AsAlnum1 : begin
          if s[i] in ['!'..'~'] then begin
            Result := True;
            Break;
          end else
            Break;
        end;

      end;
    end;
  end;

  function IsAttachmentEnd (const s : string) : Boolean;
  begin
    if LowerCase (Copy (s, 1, 3)) = 'end' then
      Result := True
    else
      Result := False;
  end;

  procedure CheckForAttachment (const s : string);
  begin
    if IsAttachmentStart (s) then begin
      if AttDepth = 0 then
        Inc (FAttachmentCount);
      Inc (AttDepth);
    end else if (IsAttachmentEnd (s)) and
                (FAttachmentCount > 0) then
      Dec (AttDepth);
  end;
{End !!.12}
var
  RawHeaders : TStringList;
  S : string;
  i, j : Integer;                                                      {!!.13}
begin
  { get message headers}
  Position := 0;
  RawHeaders := TStringList.Create;
  try
    S := ReadLine;
    repeat
      if S <> '' then                                                  {!!.15}
        RawHeaders.Add(S);
      S := ReadLine;
    until (S = '');

    FHeaders.Clear;                                                    {!!.12}
    FHeaders.LoadHeaders (RawHeaders, False);                          {!!.12}
    CheckAllHeaders;                                                   {!!.12}

    { decode MIME headers }
    DecodeMimeHeaders(RawHeaders);

{Begin !!.13}
    { If this is a MIME message, mark the MIME headers as being exposed via an
      iPRO property. }
    if FIsMime then
      for i := Low(IpMimeHeaders) to High(IpMimeHeaders) do begin
        j := FHeaders.HasHeader(IpMimeHeaders[i]);
        if j > -1 then
          FHeaders.Items[j].IsProperty := True;
      end;
{End !!.13}
  finally
    RawHeaders.Free;
  end;

  { if message is mime, then decode mime parts }
  if IsMime then begin                                                 {!!.01}
    if (FContentDispositionType = strAttachment) then begin            {!!.12}
      Inc (FParent.FAttachmentCount);                                  {!!.12}{!!.15}
      DecodeEntityAsAttachment(MsgStream)                              {!!.01}
    end else                                                           {!!.12}
      DecodeEntity(MsgStream);
  end else begin
    { otherwise, just read in the message body. }
    repeat  { skip over blank lines between headers and body }
      S := ReadLine;
    until (S <> '') or AtEndOfStream;

    { read in message body up to message terminator '.' }
    {while not ((S = '.') or AtEndOfStream) do begin}                  {!!.10}
    while not AtEndOfStream do begin                                   {!!.10}
      Body.WriteLine(S);
      AttDepth := 0;                                                   {!!.12}
      CheckForAttachment (S);                                          {!!.12}
      S := ReadLine;
    end;
    { write final line }                                               {!!.10}
    if S <> '' then                                                    {!!.13}
      Body.WriteLine(S);                                               {!!.10}

{Begin !!.12}
    { Read the message body. }
    {ReadBody(MsgStream, S); }
{End !!.12}
  end;
  Body.Position := 0;
end;

{ Build message stream with headers, body, and MIME parts (if any) }
procedure TIpMessage.EncodeMessage;
var
  i : Integer;
  Size : Longint;                                                      {!!.12}
  FileName : string;                                                   {!!.12}
  Strm : TIpMemMapStream;                                              {!!.12}
  RawHeaders : TStringList;
begin
  NewMessageStream;
{Begin !!.12}
  { If we have some very large attachments then we need to use a memory mapped
    file stream instead of TMemory, in order to improve performance. }
  Size := 0;
  for i := 0 to Pred(FMimeParts.Count) do
    inc(Size, FMimeParts[i].FOriginalSize);
  if Size > IpLgAttachSizeBoundry then begin
    MsgStream.FreeStream;
    FileName := GetTemporaryFile(GetTemporaryPath);
    if FileExistsUTF8(FileName) then
      DeleteFileUTF8(FileName);
    Strm := TIpMemMapStream.Create(FileName, False, True);
    Strm.Size := Trunc(Size * 1.5);
    Strm.Open;
    MsgStream.Stream := Strm;
  end;
{End !!.12}
  if (FContentType <> '') then begin
    FIsMime := True;
    FMimeVersion := '1.0';
  end;
  RawHeaders := TStringList.Create;
  try
    EncodeSingleHeader(strReturnPath, RawHeaders, FReturnPath);
    EncodeMultiHeader(strReceived, RawHeaders, FReceived, #09, True);
    EncodeListHeader(strPath, RawHeaders, FPath, ',', True);
    EncodeListHeader(strNewsgroups, RawHeaders, FNewsgroups, ',', False); {!!.14}
    EncodeSingleHeader(strMessageID, RawHeaders, FMessageID);
    EncodeSingleHeader (strDispositionNotify, RawHeaders,                {!!.12}
                        FDispositionNotify);                             {!!.12}
    EncodeSingleHeader(strReplyTo, RawHeaders, FReplyTo);
    EncodeSingleHeader(strFrom, RawHeaders, FFrom);
    EncodeListHeader(strTo, RawHeaders, FRecipients, ',', True);
    EncodeSingleHeader(strSubject, RawHeaders, FSubject);
    EncodeSingleHeader(strDate, RawHeaders, FDate);
    EncodeSingleHeader(strOrganization, RawHeaders, FOrganization);
    EncodeListHeader(strCC, RawHeaders, FCC, ',', False);
    EncodeListHeader(strBCC, RawHeaders, FBCC, ',', False);
    EncodeSingleHeader(strInReplyTo, RawHeaders, FInReplyTo);
    EncodeListHeader(strReferences, RawHeaders, FReferences, '', False);
    EncodeSingleHeader(strSender, RawHeaders, FSender);
    EncodeSingleHeader(strKeywords, RawHeaders, FKeywords);
    EncodeMultiHeader('', RawHeaders, FUserFields, Char(0), False);
    EncodeSingleHeader(strControl, RawHeaders, FControl);               {!!.12}
    EncodeSingleHeader(strFollowUp, RawHeaders, FFollowupTo);           {!!.12}
{Begin !!.13}
    for i := 0 to Pred(Headers.Count) do
      { Write the header out only if it is not a header exposed via an iPRO
        property. }
      if (not Headers.Items[i].IsProperty) then begin
        if Headers.Items[i].Value.Count = 1 then
          EncodeSingleHeader(Headers.Items[i].Name + ': ', RawHeaders,
                             Headers.Items[i].Value[0])
        else
          EncodeMultiheader(Headers.Items[i].Name + ': ', RawHeaders,
                            Headers.Items[i].Value, #09, True);
      end;
{End !!.13}
    if IsMime then
      EncodeMimeHeaders(RawHeaders);
    if (RawHeaders.Count = 0) then
      Exit;
    for i := 0 to Pred(RawHeaders.Count) do
      WriteLine(RawHeaders[i]);
  finally
    RawHeaders.Free;
  end;

{Begin !!.13}
  WriteLine('');
  if IsMime then
    EncodeEntity(MsgStream)
  else if (FBody.Size > 0) then begin
    FBody.Position := 0;
    repeat
      WriteLine(Body.ReadLine);
    until FBody.AtEndOfStream;
  end;  { if }
{End !!.13}
end;

{ Load message from file stream and decode }
procedure TIpMessage.LoadFromFile(const aFileName : string);
{Begin !!.12}
var
  SourceStream : TIpMemMapStream;
{End !!.12}
begin
  Clear;
  NewMessageStream;                                                    {!!.03}
{Begin !!.12}
  SourceStream := TIpMemMapStream.Create(aFileName, True, False);
  try
    SourceStream.Open;
{Begin !!.15}
    if SourceStream.Size > IpLgAttachSizeBoundry then begin
      MsgStream.FreeStream;
      MsgStream.Stream := SourceStream;
    end
    else
      MsgStream.CopyFrom(SourceStream, 0);
  finally
    if MsgStream.Stream <> SourceStream then
      SourceStream.Free;
{End !!.15}
  end;
{End !!.12}

  try                                                                  {!!.03}
    DecodeMessage;
  except                                                               {!!.03}
    { just eat the exception, the messge might be corrupt, but the }
    { raw text (MessageStream property) will still be available    }
  end;                                                                 {!!.03}
end;

{Begin !!.12}
procedure TIpMessage.LoadFromStream(aStream : TStream);
var
  FileName : string;
  Strm : TIpMemMapStream;
begin
  Clear;
  NewMessageStream;
  if aStream.Size > IpLgAttachSizeBoundry then begin
    MsgStream.FreeStream;
    FileName := GetTemporaryFile(GetTemporaryPath);
    if FileExistsUTF8(FileName) then
      DeleteFileUTF8(FileName);
    Strm := TIpMemMapStream.Create(FileName, False, True);
    Strm.Size := aStream.Size;
    Strm.Open;
    MsgStream.Stream := Strm;
  end;
  MsgStream.CopyFrom(aStream, 0);

  try
    DecodeMessage;
  except
    { just eat the exception, the messge might be corrupt, but the }
    { raw text (MessageStream property) will still be available    }
  end;                                                               
end;


{ Create new message stream but retain existing decoded message }
procedure TIpMessage.NewMessageStream;
begin
  MsgStream.FreeStream;
  MsgStream.Stream := TMemoryStream.Create;
  MsgStream.bsInitForNewStream;                                        {!!.02}
end;

{ Clear all and create new empty message stream }
procedure TIpMessage.NewMessage;
begin
  Clear;
  NewMessageStream;
end;

{ Position property read access method }
function TIpMessage.GetPosition : Longint;
begin
  if Assigned(MsgStream) then
    Result := MsgStream.Position
  else
    Result := 0;
end;

{ Size property read access method }
function TIpMessage.GetSize : Longint;
begin
  if Assigned(MsgStream) then
    Result := MsgStream.Size
  else
    Result := 0;
end;

{ Return next line from the message stream (CRLF stripped) }
function TIpMessage.ReadLine : string;
begin
  if Assigned(MsgStream) then
    Result := MsgStream.ReadLine
  else
    Result := '';
end;

{ Return next line from the message stream (CRLF retained) }
function TIpMessage.ReadLineCRLF : string;
begin
  if Assigned(MsgStream) then
    Result := MsgStream.ReadLine + CRLF
  else
    Result := '';
end;

{- Save raw message stream to file }
procedure TIpMessage.SaveToFile(const aFileName : string);
var
  FS : TFileStream;
begin
  EncodeMessage;
  Position := 0;
  FS := TFileStreamUTF8.Create(aFileName, fmCreate);
  try
    FS.CopyFrom(MsgStream, MsgStream.Size);
  finally
    FS.Free;
  end;
end;

{Begin !!.12}
{- Save raw message stream }
procedure TIpMessage.SaveToStream(Stream: TStream);
begin
  Position := 0;
  Stream.CopyFrom(MsgStream, MsgStream.Size);
end;

procedure TIpMessage.SetHeaders(Headers : TIpHeaderCollection);
begin
  FHeaders.Assign(Headers);
end;
{End !!.12}

{ Position property write access method }
procedure TIpMessage.SetPosition(Value : Longint);
begin
  if Assigned(MsgStream) then
    MsgStream.Position := Value;
end;

{ Write string onto the message stream and append CRLF terminator }
procedure TIpMessage.WriteLine(const aSt : string);
begin
  if Assigned(MsgStream) then
    MsgStream.WriteLine(aSt);
end;

{ Indicates whether or not we're at the end of the message stream }
function TIpMessage.AtEndOfStream : Boolean;
begin
  if Assigned(MsgStream) then
    Result := MsgStream.AtEndOfStream
  else
    Result := True;
end;

{ Return 'alternative' text/plain mime part }
function TIpMessage.GetBodyPlain(CanCreate : Boolean) : TIpMimeEntity;
var
  aParent : TIpMimeEntity;
begin
  aParent := FindNestedMimePart(strMultipart, strAlternative, '');   {!!.02}
  if not Assigned(aParent) then
    aParent := Self;
{Begin !!.15}
  Result := aParent.FindNestedMimePart(strText, strPlain, '');
  if (Result = nil) and CanCreate then begin
    Result := NewMimePart;
    Result.ContentType := strText;
    Result.ContentSubtype := strPlain;
  end;
{End !!.15}
end;

{ Return 'alternative' text/html mime part }
function TIpMessage.GetBodyHtml(CanCreate : Boolean) : TIpMimeEntity;
var
  aParent : TIpMimeEntity;
begin
  aParent := FindNestedMimePart(strMultipart, strAlternative, '');   {!!.02}
  if not Assigned(aParent) then
    aParent := Self;
{Begin !!.15}
  Result := aParent.FindNestedMimePart(strText, strHtml, '');
  if (Result = nil) and CanCreate then begin
    Result := NewMimePart;
    Result.ContentType := strText;
    Result.ContentSubtype := strHTML;
  end;
{End !!.15}
end;

{ Add a file attachment using default types }
procedure TIpMessage.AddDefaultAttachment(const aFileName: string);     {!!.02}
begin
  with NewMimePart do begin
    EntityName := ExtractFileName(aFileName);
    ContentDispositionType := 'attachment';
    EncodeBodyFile(aFileName);
  end;
end;

procedure TIpMessage.AddDefaultAttachmentAs (const aFileName      : string;  {!!.12}
                                             const AttachmentName : string); {!!.12}
begin                                                                    {!!.12}
  with NewMimePart do begin                                              {!!.12}
    EntityName := ExtractFileName (AttachmentName);                      {!!.12}
    ContentDispositionType := 'attachment';                              {!!.12}
    EncodeBodyFile (aFileName);                                          {!!.12}
  end;                                                                   {!!.12}
end;                                                                     {!!.12}

{ Set message properties from another TIpMessage }
procedure TIpMessage.Assign(Source: TPersistent);
var
  SourcePos : Integer;
  SourceMsg : TIpMessage;
begin
  if Source is TIpMessage then begin
    SourceMsg := TIpMessage(Source);
    { clear our streams and properties }
    NewMessage;
    { ensure we are at the beginning of our streams }
    Position := 0;
    SourcePos := SourceMsg.Position;
    SourceMsg.Position := 0;
    MsgStream.CopyFrom(SourceMsg.MsgStream, 0);
    Position := 0;
    SourceMsg.Position := SourcePos;
    try                                                                {!!.03}
      DecodeMessage;
    except                                                             {!!.03}
      { just eat the exception, the messge might be corrupt, but the }
      { raw text (MessageStream property) will still be available    }
    end;                                                               {!!.03}
  end else
    inherited Assign(Source);
end;

procedure TIpMessage.SetBCC(const Value: TStringList);                 {!!.01}
begin
  FBCC.Assign(Value);
end;

procedure TIpMessage.SetCC(const Value: TStringList);                  {!!.01}
begin
  FCC.Assign(Value);
end;

procedure TIpMessage.SetNewsgroups(const Value: TStringList);          {!!.01}
begin
  FNewsgroups.Assign(Value);
end;

procedure TIpMessage.SetPath(const Value: TStringList);                {!!.01}
begin
  FPath.Assign(Value);
end;

procedure TIpMessage.SetReceived(const Value: TStringList);            {!!.01}
begin
  FReceived.Assign(Value);
end;

procedure TIpMessage.SetRecipients(const Value: TStringList);          {!!.01}
begin
  FRecipients.Assign(Value);
end;

procedure TIpMessage.SetReferences(const Value: TStringlist);          {!!.01}
begin
  FReferences.Assign(Value);
end;

procedure TIpMessage.SetUserFields(const Value: TStringList);          {!!.01}
begin
  FUserFields.Assign(Value);
end;



{ TIpFormDataEntity }
constructor TIpFormDataEntity.Create(ParentEntity : TIpMimeEntity);
begin
  inherited Create(ParentEntity);
  ContentType := strMultipart;
  ContentSubType := strFormData;
  Boundary := GenerateBoundary;
end;

destructor TIpFormDataEntity.Destroy;
begin
  inherited Destroy;
end;

{ Add file as nested Mime part of FilesEntity block }
procedure TIpFormDataEntity.AddFile(const aFileName,
                                    aContentType,
                                    aSubtype : string;
                                    aEncoding : TIpMimeEncodingMethod);
var
  Blk : TIpMimeEntity;
  MS : TIpMemMapStream;
begin
  if not Assigned(FFilesEntity) then begin
    FFilesEntity := NewMimePart;
    FFilesEntity.EntityName := strFiles;
    FFilesEntity.ContentDispositionType := strFormData;
    FFilesEntity.ContentType := strMultipart;
    FFilesEntity.ContentSubtype := strMixed;
  end;

  Blk := FFilesEntity.NewMimePart;
  Blk.ContentDispositionType := strAttachment;
  Blk.ContentType := aContentType;
  Blk.ContentSubtype := aSubtype;
  Blk.ContentTransferEncoding := aEncoding;

  MS := TIpMemMapStream.Create(aFileName, True, False);
  try
    MS.Open;
    Blk.EncodeBodyStream(MS, aFileName);
  finally
    MS.Free;
  end;
end;

{ Add FormData Mime part }
procedure TIpFormDataEntity.AddFormData(const aName, aText : string);
var
  Blk : TIpMimeEntity;
begin
  Blk := NewMimePart;
  Blk.EntityName := aName;
  Blk.ContentDispositionType := strFormData;
  Blk.Body.WriteLine(aText);
end;

{ Generate raw Mime message and save to stream }
procedure TIpFormDataEntity.SaveToStream(aStream : TStream);
var
  TS : TIpAnsiTextStream;
  SL : TStringList;
begin
  TS := TIpAnsiTextStream.Create(aStream);
  try
    SL := TStringList.Create;
    try
      EncodeMimeHeaders(SL);
      SL.SaveToStream(TS);
      EncodeEntity(TS);
    finally
      SL.Free;
    end;
  finally
    TS.Free;
  end;
end;

{HTTP Authentication Support -- .02}
function IpBase64EncodeString(const InStr: string): string;              {!!.03}
{
encode a string into Base64, intended for producing short ( < 100 chars or so)
coded strings to be passed as part of HTTP authentications via HTTP headers.

NO LINE ORIENTED SMARTS: if you need to work with blocks of text use the
IpMsg class
}
var
  CvtBuff: PChar;
  I, Ct, Count, OutLen: Cardinal;

function CodeByte(byt : Byte) : char;
{- encode 6-bit value to BinHex char and send it }
begin
  Result := Ip64Table[byt and $3F];
end;

begin
  Result := '';
  Count := Length(InStr);
  if Count = 0 then // empty input string nothing to encode              {!!.03}
    Exit;                                                                {!!.03}
  OutLen := Count * 2; // leave plenty of room for encoded string        {!!.03}
  GetMem(CvtBuff, OutLen + 1);

  Ct := 0;
  I := 1;

  if Count >= 3 then begin                                               {!!.03}
    while I <= (Count - 2) do begin
      { Encode 1st byte }
      CvtBuff[Ct] := CodeByte(Ord(InStr[I]) shr 2);
      Inc(Ct);

      { Encode 1st/2nd byte }
      CvtBuff[Ct]  := CodeByte((Ord(InStr[I]) shl 4) or (Ord(InStr[I+1]) shr 4));
      Inc(Ct);

      { Encode 2nd/3rd byte }
      CvtBuff[Ct] := CodeByte((Ord(InStr[I+1]) shl 2) or (Ord(InStr[I+2]) shr 6));
      Inc(Ct);

      { Encode 3rd byte }
      CvtBuff[Ct] := CodeByte(Ord(InStr[I+2]) and $3F);
      Inc(Ct);

      Inc(I, 3);
    end;
  end;                                                                   {!!.03}

  { Are there odd bytes to add? }
  if (I <= Count) then begin
    CvtBuff[Ct] := CodeByte(Ord(InStr[I]) shr 2);
    Inc(Ct);

    { One odd byte }
    if I = Count then begin
      CvtBuff[Ct] := CodeByte((Ord(InStr[I]) shl 4) and $30);
      Inc(Ct);
      CvtBuff[Ct] := '='; // pad char
      Inc(Ct);
    { Two odd bytes }
    end else begin
      CvtBuff[Ct] := CodeByte(((Ord(InStr[I]) shl 4) and $30)
        or ((Ord(InStr[I+1]) shr 4) and $0F));
      Inc(Ct);
      CvtBuff[Ct] := CodeByte((Ord(InStr[I+1]) shl 2) and $3C);
      Inc(Ct);
    end;
    { Add padding }
      CvtBuff[Ct] := '=';
      Inc(Ct);
  end;

  CvtBuff[Ct] := #0;
  Result := StrPas(CvtBuff);
  FreeMem(CvtBuff, OutLen + 1);
end;


end.