daaki-message 0.1.0

RFC 5322 email message parser and builder
Documentation
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
//! RFC 5322 email message builder.
//!
//! Constructs email message bytes from structured input for sending via SMTP
//! or saving as drafts via IMAP `APPEND`.
//!
//! # References
//! - RFC 5322 (Internet Message Format)
//! - RFC 2045 (MIME Part One — Content-Transfer-Encoding)
//! - RFC 2046 (MIME Part Two — multipart boundaries)
//! - RFC 2183 (Content-Disposition: attachment)

use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

use base64::Engine as _;

use crate::error::Error;
use crate::types::{Address, BuiltMessage, DateTime, OutgoingAttachment, OutgoingEmail};

/// Atomic counter for Message-ID uniqueness.
static MSG_ID_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Builds an RFC 5322 message from an [`OutgoingEmail`].
///
/// Returns raw bytes, the list of all envelope recipients (to + cc + bcc)
/// for SMTP `RCPT TO`, and the generated Message-ID.
///
/// BCC addresses are included in [`BuiltMessage::envelope_recipients`] but
/// are **not** present in the message headers (RFC 5322 Section 3.6.3).
///
/// # Errors
///
/// Returns [`Error::InvalidAddress`] for syntactically invalid email addresses,
/// or [`Error::Build`] for other construction failures.
///
/// # References
/// - RFC 5322 (message format)
/// - RFC 2046 (MIME multipart)
/// - RFC 2045 (Content-Transfer-Encoding)
#[allow(clippy::too_many_lines)]
pub fn build_message(email: &OutgoingEmail) -> Result<BuiltMessage, Error> {
    // Validate all addresses (RFC 5322 Section 3.4)
    validate_address(&email.from)?;
    for addr in &email.to {
        validate_address(addr)?;
    }
    for addr in &email.cc {
        validate_address(addr)?;
    }
    for addr in &email.bcc {
        validate_address(addr)?;
    }
    if let Some(ref reply_to) = email.reply_to {
        validate_address(reply_to)?;
    }

    if email.to.is_empty() && email.cc.is_empty() && email.bcc.is_empty() {
        return Err(Error::Build("at least one recipient required".into()));
    }

    // Generate Message-ID (RFC 5322 Section 3.6.4)
    let domain = extract_domain(&email.from.email).unwrap_or("daaki.local");
    let message_id = generate_message_id(domain);

    let mut raw = Vec::new();

    // --- Headers ---
    // All user-provided values are sanitized to strip CR/LF and prevent
    // header injection (RFC 5322 Section 2.1).

    // From (RFC 5322 Section 3.6.2)
    write_header(
        &mut raw,
        "From",
        &sanitize_header_value(&format_address(&email.from)),
    );

    // To (RFC 5322 Section 3.6.3)
    if !email.to.is_empty() {
        write_header(
            &mut raw,
            "To",
            &sanitize_header_value(&format_address_list(&email.to)),
        );
    }

    // Cc (RFC 5322 Section 3.6.3)
    if !email.cc.is_empty() {
        write_header(
            &mut raw,
            "Cc",
            &sanitize_header_value(&format_address_list(&email.cc)),
        );
    }

    // BCC MUST NOT appear in message headers (RFC 5322 Section 3.6.3)

    // Reply-To (RFC 5322 Section 3.6.2)
    if let Some(ref reply_to) = email.reply_to {
        write_header(
            &mut raw,
            "Reply-To",
            &sanitize_header_value(&format_address(reply_to)),
        );
    }

    // Subject (RFC 5322 Section 3.6.5, RFC 2047 for non-ASCII)
    write_header(
        &mut raw,
        "Subject",
        &encode_rfc2047_if_needed(&sanitize_header_value(&email.subject)),
    );

    // Date (RFC 5322 Section 3.6.1)
    write_header(&mut raw, "Date", &DateTime::now().to_rfc5322_string());

    // Message-ID (RFC 5322 Section 3.6.4)
    write_header(&mut raw, "Message-ID", &format!("<{message_id}>"));

    // MIME-Version (RFC 2045 Section 4)
    write_header(&mut raw, "MIME-Version", "1.0");

    // In-Reply-To (RFC 5322 Section 3.6.4)
    if let Some(ref in_reply_to) = email.in_reply_to {
        let sanitized = sanitize_header_value(in_reply_to);
        // Strip existing angle brackets defensively before wrapping
        // (API contract says bare addr-spec, but be tolerant).
        let bare = strip_angle_brackets(&sanitized);
        write_header(&mut raw, "In-Reply-To", &format!("<{bare}>"));
    }

    // References (RFC 5322 Section 3.6.4)
    if let Some(ref references) = email.references {
        let sanitized = sanitize_header_value(references);
        let refs: String = sanitized
            .split_whitespace()
            .map(|id| {
                // Strip existing angle brackets before wrapping
                let bare = strip_angle_brackets(id);
                format!("<{bare}>")
            })
            .collect::<Vec<_>>()
            .join(" ");
        write_header(&mut raw, "References", &refs);
    }

    // --- Body ---

    let has_text = email.body_text.is_some();
    let has_html = email.body_html.is_some();
    let has_attachments = !email.attachments.is_empty();

    // Collect all encapsulated content so that generated boundaries can be
    // verified not to collide with it (RFC 2046 Section 5.1.1: "The boundary
    // delimiter MUST NOT appear within the encapsulated material.").
    let encapsulated_content = {
        let mut buf = Vec::new();
        if let Some(ref text) = email.body_text {
            buf.extend_from_slice(text.as_bytes());
        }
        if let Some(ref html) = email.body_html {
            buf.extend_from_slice(html.as_bytes());
        }
        for att in &email.attachments {
            buf.extend_from_slice(&att.data);
            buf.extend_from_slice(att.filename.as_bytes());
        }
        buf
    };

    if has_attachments {
        // Outer multipart/mixed (RFC 2046 Section 5.1.3)
        let mixed_boundary = generate_boundary_not_in(&encapsulated_content);
        write_header(
            &mut raw,
            "Content-Type",
            &format!("multipart/mixed; boundary=\"{mixed_boundary}\""),
        );
        raw.extend_from_slice(b"\r\n");

        // Body part(s) — first part of multipart/mixed
        write_boundary(&mut raw, &mixed_boundary, false);

        if has_text && has_html {
            // Wrap text + html in multipart/alternative (RFC 2046 Section 5.1.4)
            // RFC 2046 Section 5.1.1: boundary parameter values for nested
            // multipart levels must be distinct. Loop until we get a value
            // different from mixed_boundary (astronomically unlikely to need
            // more than one retry with 32 hex chars of randomness, but a
            // single `if` left a theoretical collision window).
            let mut alt_boundary = generate_boundary_not_in(&encapsulated_content);
            while alt_boundary == mixed_boundary {
                alt_boundary = generate_boundary_not_in(&encapsulated_content);
            }
            write_header(
                &mut raw,
                "Content-Type",
                &format!("multipart/alternative; boundary=\"{alt_boundary}\""),
            );
            raw.extend_from_slice(b"\r\n");

            write_boundary(&mut raw, &alt_boundary, false);
            write_text_part(
                &mut raw,
                email.body_text.as_deref().unwrap_or(""),
                "text/plain",
            );

            write_boundary(&mut raw, &alt_boundary, false);
            write_text_part(
                &mut raw,
                email.body_html.as_deref().unwrap_or(""),
                "text/html",
            );

            write_boundary(&mut raw, &alt_boundary, true);
        } else if has_text {
            write_text_part(
                &mut raw,
                email.body_text.as_deref().unwrap_or(""),
                "text/plain",
            );
        } else if has_html {
            write_text_part(
                &mut raw,
                email.body_html.as_deref().unwrap_or(""),
                "text/html",
            );
        } else {
            // No body — empty text/plain (requirements: "No body → Empty text/plain part")
            write_text_part(&mut raw, "", "text/plain");
        }

        // Attachment parts
        for attachment in &email.attachments {
            write_boundary(&mut raw, &mixed_boundary, false);
            write_attachment_part(&mut raw, attachment);
        }

        write_boundary(&mut raw, &mixed_boundary, true);
    } else if has_text && has_html {
        // multipart/alternative (RFC 2046 Section 5.1.4)
        let alt_boundary = generate_boundary_not_in(&encapsulated_content);
        write_header(
            &mut raw,
            "Content-Type",
            &format!("multipart/alternative; boundary=\"{alt_boundary}\""),
        );
        raw.extend_from_slice(b"\r\n");

        write_boundary(&mut raw, &alt_boundary, false);
        write_text_part(
            &mut raw,
            email.body_text.as_deref().unwrap_or(""),
            "text/plain",
        );

        write_boundary(&mut raw, &alt_boundary, false);
        write_text_part(
            &mut raw,
            email.body_html.as_deref().unwrap_or(""),
            "text/html",
        );

        write_boundary(&mut raw, &alt_boundary, true);
    } else if has_html {
        // Single text/html — delegate to write_text_part which handles
        // quoted-printable fallback for long lines (RFC 2045 Section 2.8).
        write_text_part(
            &mut raw,
            email.body_html.as_deref().unwrap_or(""),
            "text/html",
        );
    } else {
        // Single text/plain or empty body — delegate to write_text_part which
        // handles quoted-printable fallback for long lines (RFC 2045 Section 2.8).
        write_text_part(
            &mut raw,
            email.body_text.as_deref().unwrap_or(""),
            "text/plain",
        );
    }

    // Collect envelope recipients (to + cc + bcc) for SMTP RCPT TO
    let mut envelope_recipients: Vec<String> = email.to.iter().map(|a| a.email.clone()).collect();
    envelope_recipients.extend(email.cc.iter().map(|a| a.email.clone()));
    envelope_recipients.extend(email.bcc.iter().map(|a| a.email.clone()));

    Ok(BuiltMessage {
        raw,
        envelope_recipients,
        message_id,
    })
}

// ---------------------------------------------------------------------------
// Address formatting and validation
// ---------------------------------------------------------------------------

/// Normalizes line endings to CRLF per RFC 5322 Section 2.1.
///
/// Converts bare `\n` to `\r\n` and bare `\r` to `\r\n`, while leaving
/// existing `\r\n` pairs unchanged. This ensures the message body conforms
/// to the canonical form required by RFC 5322.
///
/// # References
/// - RFC 5322 Section 2.1 (CRLF line endings)
fn normalize_line_endings(input: &str) -> String {
    let mut result = String::with_capacity(input.len());
    let mut chars = input.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '\r' => {
                // CR or CRLF → CRLF
                result.push_str("\r\n");
                // Consume a following LF so CRLF counts as one line ending
                if chars.peek() == Some(&'\n') {
                    chars.next();
                }
            }
            '\n' => {
                // Bare LF → CRLF
                result.push_str("\r\n");
            }
            _ => {
                // Preserve all other characters including multi-byte UTF-8
                result.push(c);
            }
        }
    }
    result
}

/// Strips bare CR and LF characters from a string to prevent header injection.
///
/// RFC 5322 Section 2.1 defines header fields as terminated by CRLF.
/// Bare CR/LF in user-provided values (display names, subjects, etc.)
/// could inject new headers. This function removes them entirely.
///
/// # References
/// - RFC 5322 Section 2.1 (header line structure)
fn sanitize_header_value(value: &str) -> String {
    value.chars().filter(|&c| c != '\r' && c != '\n').collect()
}

/// RFC 2047 encodes text as Base64 encoded words if it contains non-ASCII.
///
/// Returns the original text unchanged if it is pure ASCII. Otherwise
/// encodes the entire text as one or more `=?UTF-8?B?...?=` encoded words,
/// each at most 75 characters long per RFC 2047 Section 2. Multiple encoded
/// words are separated by a single space so that [`write_header`] can fold
/// at word boundaries.
///
/// # References
/// - RFC 2047 Section 2 (encoded-word syntax, 75-char limit)
/// - RFC 2047 Section 5 (use in message header bodies)
/// - RFC 5322 Section 2.2 (field bodies must be US-ASCII)
pub(crate) fn encode_rfc2047_if_needed(text: &str) -> String {
    if text.bytes().all(|b| b.is_ascii()) {
        return text.to_string();
    }

    // Max encoded word = 75 chars (RFC 2047 Section 2).
    // Overhead: "=?UTF-8?B?" (10) + "?=" (2) = 12 chars.
    // Max base64 payload: 75 - 12 = 63 chars.
    // 63 base64 chars encodes 63/4*3 = 47.25 bytes → use 45 bytes (= 60 base64
    // chars) to keep chunks aligned to 3-byte base64 groups.
    let max_raw_bytes: usize = 45;

    let bytes = text.as_bytes();
    let mut words: Vec<String> = Vec::new();
    let mut pos = 0;

    while pos < bytes.len() {
        let chunk_end = snap_utf8_chunk_end(bytes, pos, max_raw_bytes);

        let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes[pos..chunk_end]);
        words.push(format!("=?UTF-8?B?{b64}?="));
        pos = chunk_end;
    }

    // Space-separate: RFC 2047 Section 6.2 says whitespace between adjacent
    // encoded words is collapsed (not part of the decoded text).
    words.join(" ")
}

/// Validates that an address has a syntactically valid email (RFC 5322 Section 3.4).
fn validate_address(addr: &Address) -> Result<(), Error> {
    let email = &addr.email;
    if email.is_empty() {
        return Err(Error::InvalidAddress("empty email address".into()));
    }
    let at_pos = email
        .find('@')
        .ok_or_else(|| Error::InvalidAddress(format!("missing '@' in email: {email}")))?;
    let local = &email[..at_pos];
    let domain = &email[at_pos + 1..];
    if local.is_empty() {
        return Err(Error::InvalidAddress(format!("empty local part: {email}")));
    }
    if domain.is_empty() {
        return Err(Error::InvalidAddress(format!("empty domain part: {email}")));
    }
    if email
        .chars()
        .any(|c| c.is_ascii_whitespace() || c.is_ascii_control())
    {
        return Err(Error::InvalidAddress(format!(
            "email contains invalid characters: {email}"
        )));
    }
    Ok(())
}

/// Formats an address for a header value (RFC 5322 Section 3.4).
///
/// Non-ASCII display names are RFC 2047 encoded (RFC 5322 Section 2.2,
/// RFC 2047 Section 5). ASCII names containing RFC 5322 specials are
/// wrapped in a quoted-string with backslash-escaping (RFC 5322 Section 3.2.4).
/// Escapes backslashes and double-quotes in a quoted-string per RFC 5322
/// Section 3.2.4 (`quoted-pair = "\" (VCHAR / WSP)`).
fn escape_quoted_string(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

fn format_address(addr: &Address) -> String {
    match &addr.name {
        Some(name) if !name.is_empty() => {
            if name.bytes().any(|b| !b.is_ascii()) {
                // Non-ASCII display name: RFC 2047 encoded words in phrase
                // context (RFC 2047 Section 5). No quoting needed — encoded
                // words replace "text" tokens in the phrase production.
                let encoded = encode_rfc2047_if_needed(name);
                format!("{encoded} <{}>", addr.email)
            } else if needs_quoting(name) {
                // Escape backslashes and double-quotes (RFC 5322 Section 3.2.4)
                let escaped = escape_quoted_string(name);
                format!("\"{escaped}\" <{}>", addr.email)
            } else {
                format!("{name} <{}>", addr.email)
            }
        }
        _ => addr.email.clone(),
    }
}

/// Returns `true` if a display name must be quoted per RFC 5322 Section 3.2.3.
///
/// Quoting is required when the name contains any RFC 5322 specials:
/// `( ) < > [ ] : ; @ \ , . "`
fn needs_quoting(name: &str) -> bool {
    name.chars().any(|c| {
        matches!(
            c,
            '(' | ')' | '<' | '>' | '[' | ']' | ':' | ';' | '@' | '\\' | ',' | '.' | '"'
        )
    })
}

/// Formats a list of addresses as a comma-separated header value.
fn format_address_list(addrs: &[Address]) -> String {
    addrs
        .iter()
        .map(format_address)
        .collect::<Vec<_>>()
        .join(", ")
}

/// Strips surrounding angle brackets from a message-id if present.
///
/// Tolerates callers that pass `<id@host>` instead of bare `id@host`
/// (RFC 5322 Section 3.6.4 — msg-id uses angle brackets, but the API
/// contract stores bare addr-spec).
fn strip_angle_brackets(s: &str) -> &str {
    s.strip_prefix('<')
        .and_then(|s| s.strip_suffix('>'))
        .unwrap_or(s)
}

/// Extracts the domain part of an email address.
fn extract_domain(email: &str) -> Option<&str> {
    let at = email.find('@')?;
    let domain = &email[at + 1..];
    if domain.is_empty() {
        None
    } else {
        Some(domain)
    }
}

// ---------------------------------------------------------------------------
// Message-ID and boundary generation
// ---------------------------------------------------------------------------

/// Generates a unique Message-ID using timestamp + PID + counter.
///
/// Format: `{hex}@{domain}` where hex is 16 bytes (32 hex chars).
///
/// # References
/// - RFC 5322 Section 3.6.4
fn generate_message_id(domain: &str) -> String {
    let hex = generate_unique_hex();
    format!("{hex}@{domain}")
}

/// Generates a unique MIME boundary string.
///
/// # References
/// - RFC 2046 Section 5.1.1
fn generate_boundary() -> String {
    let hex = generate_unique_hex();
    format!("----=_Part_{hex}")
}

/// Generates a MIME boundary that does not appear in `content`.
///
/// Tries up to 10 times with different random values. Falls back to a
/// counter-based boundary if all attempts collide (astronomically unlikely
/// with 32 hex chars, but avoids an infinite loop).
///
/// # References
/// - RFC 2046 Section 5.1.1: "The boundary delimiter MUST NOT appear within
///   the encapsulated material."
fn generate_boundary_not_in(content: &[u8]) -> String {
    for _ in 0..10 {
        let boundary = generate_boundary();
        if !contains_boundary(content, &boundary) {
            return boundary;
        }
    }
    // Fallback: use a counter-based suffix to guarantee uniqueness.
    // This path is astronomically unlikely with 32 hex chars of randomness,
    // but prevents an infinite loop.
    let count = MSG_ID_COUNTER.fetch_add(1, Ordering::Relaxed);
    let boundary = format!("----=_Part_fallback_{count:016x}");
    // Even the fallback should not collide, but we accept it — the caller
    // is responsible for providing finite content.
    boundary
}

/// Returns `true` if `content` contains the boundary string.
///
/// Checks for the boundary as it would appear in a MIME message, i.e.,
/// preceded by `--` (the MIME boundary delimiter prefix per RFC 2046
/// Section 5.1.1). Also checks for the bare boundary string to be safe.
///
/// # References
/// - RFC 2046 Section 5.1.1
fn contains_boundary(content: &[u8], boundary: &str) -> bool {
    let boundary_bytes = boundary.as_bytes();
    // Check if the bare boundary string appears anywhere in the content.
    // This is conservative: a MIME parser only looks for CRLF + "--" + boundary,
    // but checking bare occurrence is safer and matches the RFC requirement that
    // the boundary "MUST NOT appear within the encapsulated material".
    content
        .windows(boundary_bytes.len())
        .any(|w| w == boundary_bytes)
}

/// Generates 32 hex characters (16 bytes) of crypto-random data.
///
/// Uses `/dev/urandom` for crypto-quality randomness. Falls back to
/// timestamp + PID + counter if `/dev/urandom` is unavailable.
fn generate_unique_hex() -> String {
    // Try crypto-random first (RFC 5322 Section 3.6.4 — Message-ID uniqueness)
    let mut buf = [0u8; 16];
    if read_urandom(&mut buf).is_ok() {
        return buf.iter().fold(String::with_capacity(32), |mut s, b| {
            use std::fmt::Write;
            let _ = write!(s, "{b:02x}");
            s
        });
    }

    // Fallback: timestamp + PID + counter (deterministic but unique)
    #[allow(clippy::cast_possible_truncation)]
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos() as u64;
    let count = MSG_ID_COUNTER.fetch_add(1, Ordering::Relaxed);
    let pid = u64::from(std::process::id());
    format!("{nanos:016x}{pid:08x}{count:08x}")
}

/// Reads crypto-random bytes from `/dev/urandom`.
fn read_urandom(buf: &mut [u8]) -> std::io::Result<()> {
    use std::io::Read;
    let mut f = std::fs::File::open("/dev/urandom")?;
    f.read_exact(buf)
}

// ---------------------------------------------------------------------------
// Header and MIME part writing
// ---------------------------------------------------------------------------

/// Maximum line length before folding (RFC 5322 Section 2.1.1 SHOULD limit).
const MAX_LINE_LEN: usize = 78;

/// Hard maximum line length (RFC 5322 Section 2.1.1 MUST limit).
const HARD_LINE_LIMIT: usize = 998;

/// Writes a header, folding long lines per RFC 5322 Section 2.2.3.
///
/// Tries to keep lines under [`MAX_LINE_LEN`] (78) by inserting `\r\n `
/// (CRLF + space) at whitespace boundaries. Never exceeds
/// [`HARD_LINE_LIMIT`] (998).
fn write_header(output: &mut Vec<u8>, name: &str, value: &str) {
    let prefix = format!("{name}: ");
    let mut line_len = prefix.len();
    output.extend_from_slice(prefix.as_bytes());

    let mut first_word = true;
    for word in split_header_words(value) {
        // +1 for the space before the word (except the first word)
        let word_with_sep_len = if first_word {
            word.len()
        } else {
            1 + word.len()
        };

        if !first_word && line_len + word_with_sep_len > MAX_LINE_LEN && line_len > 0 {
            // Fold: insert CRLF + space (RFC 5322 Section 2.2.3)
            output.extend_from_slice(b"\r\n ");
            line_len = 1; // leading space counts
        } else if !first_word {
            output.push(b' ');
            line_len += 1;
        }

        // If a single word exceeds the hard limit, force-fold it.
        // Snap to UTF-8 character boundaries to avoid splitting multi-byte
        // characters across fold points (RFC 6532 / RFC 5322 Section 2.2.3).
        if line_len + word.len() > HARD_LINE_LIMIT {
            let bytes = word.as_bytes();
            let mut pos = 0;
            while pos < bytes.len() {
                let remaining = HARD_LINE_LIMIT - line_len;
                let chunk_end = snap_utf8_chunk_end(bytes, pos, remaining);
                output.extend_from_slice(&bytes[pos..chunk_end]);
                line_len += chunk_end - pos;
                pos = chunk_end;
                if pos < bytes.len() {
                    output.extend_from_slice(b"\r\n ");
                    line_len = 1;
                }
            }
        } else {
            output.extend_from_slice(word.as_bytes());
            line_len += word.len();
        }

        first_word = false;
    }

    output.extend_from_slice(b"\r\n");
}

/// Splits a header value into words for folding purposes.
///
/// Preserves whitespace-delimited tokens, keeping quoted strings and
/// angle-bracketed message-ids as single units.
fn split_header_words(value: &str) -> Vec<&str> {
    let mut words = Vec::new();
    let mut start = 0;
    let mut in_quotes = false;
    let mut in_angles = false;
    let bytes = value.as_bytes();

    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            // Skip escaped character in quoted-string (RFC 5322 Section 3.2.4)
            b'\\' if in_quotes => {
                i += 2;
                continue;
            }
            b'"' => in_quotes = !in_quotes,
            b'<' if !in_quotes => in_angles = true,
            b'>' if !in_quotes => in_angles = false,
            b' ' | b'\t' if !in_quotes && !in_angles => {
                if i > start {
                    words.push(&value[start..i]);
                }
                start = i + 1;
            }
            _ => {}
        }
        i += 1;
    }
    if start < bytes.len() {
        words.push(&value[start..]);
    }
    words
}

/// Writes a MIME boundary line. If `closing` is true, appends `--` suffix.
fn write_boundary(output: &mut Vec<u8>, boundary: &str, closing: bool) {
    output.extend_from_slice(b"--");
    output.extend_from_slice(boundary.as_bytes());
    if closing {
        output.extend_from_slice(b"--");
    }
    output.extend_from_slice(b"\r\n");
}

/// Returns `true` if the text (already CRLF-normalized) contains any line
/// exceeding the 998-character hard limit from RFC 5322 Section 2.1.1.
///
/// When this returns `true`, the body must be encoded with `quoted-printable`
/// (RFC 2045 Section 6.7) rather than `8bit`, because `8bit` requires all
/// lines to be at most 998 octets (RFC 2045 Section 2.8).
///
/// # References
/// - RFC 5322 Section 2.1.1 (998-character line length limit)
/// - RFC 2045 Section 2.8 (8bit line length constraint)
fn needs_quoted_printable(text: &str) -> bool {
    text.split("\r\n").any(|line| line.len() > HARD_LINE_LIMIT)
}

/// Encodes data using the quoted-printable encoding defined in RFC 2045
/// Section 6.7.
///
/// Encoding rules:
/// - Printable ASCII characters (33..=126 except `=`) pass through unchanged.
/// - TAB (0x09) and space (0x20) pass through unless they appear at the end
///   of a line (Rule #3 — trailing whitespace must be encoded).
/// - CRLF sequences pass through as hard line breaks (Rule #4).
/// - All other bytes are encoded as `=XX` with uppercase hex digits (Rule #1).
/// - Lines are wrapped at 76 characters using `=\r\n` soft line breaks (Rule #5).
///
/// # References
/// - RFC 2045 Section 6.7 (quoted-printable encoding)
fn encode_quoted_printable(data: &[u8]) -> Vec<u8> {
    /// Maximum encoded line length before a soft break (RFC 2045 Section 6.7 Rule #5).
    /// The `=` soft break marker uses 1 char, so usable content is 75 chars.
    const QP_LINE_LIMIT: usize = 76;

    let mut result = Vec::with_capacity(data.len() * 2);
    let mut line_len: usize = 0;
    let mut i = 0;

    while i < data.len() {
        // Hard line break: CRLF passes through unchanged (Rule #4)
        if data[i] == b'\r' && i + 1 < data.len() && data[i + 1] == b'\n' {
            result.extend_from_slice(b"\r\n");
            line_len = 0;
            i += 2;
            continue;
        }

        let byte = data[i];

        // Determine if this byte needs encoding (Rule #1, #2, #3)
        let needs_encoding = if byte == b'\t' || byte == b' ' {
            // Trailing whitespace on a line must be encoded (Rule #3).
            // Check if next non-whitespace before next CRLF/end is absent.
            is_trailing_whitespace(data, i)
        } else if byte == b'=' {
            // The `=` character must always be encoded (Rule #1)
            true
        } else if (33..=126).contains(&byte) {
            // Printable ASCII (except `=` handled above) — pass through
            false
        } else {
            // Non-printable / non-ASCII — encode (Rule #1)
            true
        };

        if needs_encoding {
            // Encoded form is 3 chars: =XX
            // Need at least 3 chars on current line, plus 1 for potential soft break marker
            if line_len + 3 > QP_LINE_LIMIT - 1 {
                // Insert soft line break before encoding
                result.extend_from_slice(b"=\r\n");
                line_len = 0;
            }
            result.push(b'=');
            // Uppercase hex digits per RFC 2045 Section 6.7 Rule #1
            let hi = HEX_UPPER[(byte >> 4) as usize];
            let lo = HEX_UPPER[(byte & 0x0F) as usize];
            result.push(hi);
            result.push(lo);
            line_len += 3;
        } else {
            // Literal byte — 1 char
            if line_len + 1 > QP_LINE_LIMIT - 1 {
                // Insert soft line break
                result.extend_from_slice(b"=\r\n");
                line_len = 0;
            }
            result.push(byte);
            line_len += 1;
        }

        i += 1;
    }

    result
}

/// Uppercase hex digit lookup table for quoted-printable encoding.
const HEX_UPPER: [u8; 16] = *b"0123456789ABCDEF";

/// Returns `true` if the whitespace byte at position `pos` in `data` is
/// "trailing" — i.e., no non-whitespace byte follows before the next CRLF
/// or end of data.
///
/// RFC 2045 Section 6.7 Rule #3 requires trailing whitespace to be encoded.
fn is_trailing_whitespace(data: &[u8], pos: usize) -> bool {
    let mut j = pos + 1;
    while j < data.len() {
        match data[j] {
            b'\r' | b'\n' => return true,
            b' ' | b'\t' => j += 1,
            _ => return false,
        }
    }
    // Reached end of data — whitespace at end of data is trailing
    true
}

/// Writes a text MIME part (text/plain or text/html) with UTF-8 charset.
///
/// Normalizes line endings to CRLF per RFC 5322 Section 2.1. If any line
/// exceeds 998 characters after normalization, the part is encoded using
/// `quoted-printable` (RFC 2045 Section 6.7) to guarantee line length
/// compliance. Otherwise, `8bit` encoding is used.
///
/// # References
/// - RFC 5322 Section 2.1 (CRLF line endings)
/// - RFC 5322 Section 2.1.1 (998-character line length limit)
/// - RFC 2045 Section 2.8 (8bit requires conforming line lengths)
/// - RFC 2045 Section 6.7 (quoted-printable encoding)
fn write_text_part(output: &mut Vec<u8>, text: &str, mime_type: &str) {
    write_header(
        output,
        "Content-Type",
        &format!("{mime_type}; charset=utf-8"),
    );
    // Normalize bare LF/CR to CRLF (RFC 5322 Section 2.1)
    let normalized = normalize_line_endings(text);
    if needs_quoted_printable(&normalized) {
        // Lines exceed 998 chars — must use quoted-printable (RFC 2045 Section 2.8)
        write_header(output, "Content-Transfer-Encoding", "quoted-printable");
        output.extend_from_slice(b"\r\n");
        let encoded = encode_quoted_printable(normalized.as_bytes());
        output.extend_from_slice(&encoded);
        // Ensure trailing CRLF after body
        if !encoded.ends_with(b"\r\n") {
            output.extend_from_slice(b"\r\n");
        }
    } else {
        write_header(output, "Content-Transfer-Encoding", "8bit");
        output.extend_from_slice(b"\r\n");
        output.extend_from_slice(normalized.as_bytes());
        output.extend_from_slice(b"\r\n");
    }
}

/// Writes an attachment MIME part with base64 encoding.
///
/// Falls back to `application/octet-stream` for unparseable MIME types.
///
/// # References
/// - RFC 2183 Section 2 (Content-Disposition: attachment)
/// - RFC 2045 Section 6.8 (base64 line wrapping at 76 chars)
fn write_attachment_part(output: &mut Vec<u8>, attachment: &OutgoingAttachment) {
    let content_type = if is_valid_mime_type(&attachment.content_type) {
        &attachment.content_type
    } else {
        // Fallback for unparseable MIME type (requirements: "Invalid MIME type fallback")
        "application/octet-stream"
    };

    write_header(output, "Content-Type", content_type);

    // Sanitize filename: strip CR/LF to prevent header injection
    // (RFC 5322 Section 2.1 — headers are terminated by CRLF).
    let filename = sanitize_header_value(&attachment.filename);

    // Use RFC 2231 encoding for non-ASCII filenames (RFC 2231 Section 4),
    // plain quoted-string for ASCII-only filenames (RFC 2183 Section 2).
    if filename.bytes().any(|b| !b.is_ascii()) {
        // RFC 2231 Section 5: provide both `filename*` (for RFC 2231-aware
        // clients) and a legacy `filename` fallback (for older clients that
        // don't support RFC 2231). The `filename*` parameter takes precedence
        // per RFC 2231 Section 4.
        let encoded = percent_encode_filename(&filename);
        // Build a legacy ASCII-safe fallback filename: replace non-ASCII
        // characters with `_`, preserving the file extension.
        let legacy: String = filename
            .chars()
            .map(|c| if c.is_ascii() { c } else { '_' })
            .collect();
        let escaped_legacy = escape_quoted_string(&legacy);
        write_header(
            output,
            "Content-Disposition",
            &format!("attachment; filename=\"{escaped_legacy}\"; filename*=UTF-8''{encoded}"),
        );
    } else {
        // ASCII filename: use quoted-string with backslash escaping
        // (RFC 5322 Section 3.2.4).
        let escaped_filename = escape_quoted_string(&filename);
        write_header(
            output,
            "Content-Disposition",
            &format!("attachment; filename=\"{escaped_filename}\""),
        );
    }

    write_header(output, "Content-Transfer-Encoding", "base64");
    output.extend_from_slice(b"\r\n");

    // Base64 encode with line wrapping at 76 characters (RFC 2045 Section 6.8)
    let encoded = base64::engine::general_purpose::STANDARD.encode(&attachment.data);
    for chunk in encoded.as_bytes().chunks(76) {
        output.extend_from_slice(chunk);
        output.extend_from_slice(b"\r\n");
    }
}

/// Percent-encodes a filename for RFC 2231 parameter encoding.
///
/// Encodes all bytes that are not unreserved characters (letters, digits,
/// `-`, `.`, `_`, `~`) per RFC 3986 Section 2.3. This is the encoding
/// used in RFC 2231 `charset'language'encoded-value` parameter values.
///
/// # References
/// - RFC 2231 Section 4 (parameter value character set and language)
/// - RFC 3986 Section 2.1 (percent-encoding)
fn percent_encode_filename(filename: &str) -> String {
    let mut encoded = String::with_capacity(filename.len() * 3);
    for &b in filename.as_bytes() {
        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
            encoded.push(b as char);
        } else {
            use std::fmt::Write;
            let _ = write!(encoded, "%{b:02X}");
        }
    }
    encoded
}

/// MIME type validation: must contain `/` with valid type and subtype tokens.
///
/// Both type and subtype must be non-empty and consist of valid token characters
/// (RFC 2045 Section 5.1).
///
/// A token character is any ASCII character except SPACE, CTLs, and tspecials:
/// `( ) < > @ , ; : \ " / [ ] ? =`
fn is_valid_mime_type(ct: &str) -> bool {
    let ct = ct.trim();
    if let Some(slash) = ct.find('/') {
        let type_part = &ct[..slash];
        let subtype_part = &ct[slash + 1..];
        !type_part.is_empty()
            && !subtype_part.is_empty()
            && type_part.chars().all(is_mime_token_char)
            && subtype_part.chars().all(is_mime_token_char)
    } else {
        false
    }
}

/// Returns `true` if `c` is a valid MIME token character (RFC 2045 Section 5.1).
///
/// Token characters are any ASCII character except SPACE, CTLs, and tspecials:
/// `( ) < > @ , ; : \ " / [ ] ? =`
fn is_mime_token_char(c: char) -> bool {
    c.is_ascii()
        && !c.is_ascii_whitespace()
        && !c.is_ascii_control()
        && !matches!(
            c,
            '(' | ')'
                | '<'
                | '>'
                | '@'
                | ','
                | ';'
                | ':'
                | '\\'
                | '"'
                | '/'
                | '['
                | ']'
                | '?'
                | '='
        )
}

/// Returns `true` if the byte is a UTF-8 continuation byte (0x80..0xBF).
///
/// Finds the largest chunk end ≤ `pos + max_bytes` that lands on a UTF-8
/// character boundary within `bytes`. If even one character does not fit,
/// the chunk is expanded to include the complete character to avoid an
/// infinite loop.
///
/// Used by RFC 2047 encoding and header force-folding to avoid splitting
/// multi-byte UTF-8 characters (RFC 6532 / RFC 5322 Section 2.2.3).
fn snap_utf8_chunk_end(bytes: &[u8], pos: usize, max_bytes: usize) -> usize {
    let mut end = (pos + max_bytes).min(bytes.len());
    // Back up to a character boundary
    while end > pos && end < bytes.len() && is_utf8_continuation(bytes[end]) {
        end -= 1;
    }
    // If we couldn't fit even one character, advance past the complete character
    if end == pos && pos < bytes.len() {
        end = (pos + utf8_char_len(bytes[pos])).min(bytes.len());
    }
    end
}

/// Used to avoid splitting multi-byte UTF-8 characters during header
/// force-folding (RFC 6532 / RFC 5322 Section 2.2.3).
pub(crate) fn is_utf8_continuation(b: u8) -> bool {
    (b & 0xC0) == 0x80
}

/// Returns the expected byte length of a UTF-8 character from its lead byte.
///
/// Returns 1 for ASCII, 2-4 for multi-byte sequences.
pub(crate) fn utf8_char_len(lead: u8) -> usize {
    if lead < 0x80 {
        1
    } else if lead < 0xE0 {
        2
    } else if lead < 0xF0 {
        3
    } else {
        4
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    fn make_email() -> OutgoingEmail {
        OutgoingEmail {
            from: Address {
                name: Some("Sender".into()),
                email: "sender@example.com".into(),
            },
            to: vec![Address {
                name: None,
                email: "to@example.com".into(),
            }],
            cc: vec![],
            bcc: vec![],
            reply_to: None,
            subject: "Test Subject".into(),
            body_text: None,
            body_html: None,
            in_reply_to: None,
            references: None,
            attachments: vec![],
        }
    }

    /// Helper: convert raw bytes to string for assertion.
    fn raw_str(built: &BuiltMessage) -> String {
        String::from_utf8_lossy(&built.raw).into_owned()
    }

    #[test]
    fn build_text_only() {
        let mut email = make_email();
        email.body_text = Some("Hello, World!".into());

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(s.contains("Content-Type: text/plain; charset=utf-8"));
        assert!(s.contains("Hello, World!"));
        assert!(s.contains("From: Sender <sender@example.com>"));
        assert!(s.contains("To: to@example.com"));
        assert!(s.contains("Subject: Test Subject"));
        assert!(s.contains("MIME-Version: 1.0"));
        assert!(s.contains("Date: "));
        assert!(s.contains("Message-ID: <"));
    }

    #[test]
    fn build_html_only() {
        let mut email = make_email();
        email.body_html = Some("<h1>Hello</h1>".into());

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(s.contains("Content-Type: text/html; charset=utf-8"));
        assert!(s.contains("<h1>Hello</h1>"));
    }

    #[test]
    fn build_text_and_html() {
        let mut email = make_email();
        email.body_text = Some("Plain text".into());
        email.body_html = Some("<p>HTML</p>".into());

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(s.contains("multipart/alternative"));
        assert!(s.contains("text/plain; charset=utf-8"));
        assert!(s.contains("text/html; charset=utf-8"));
        assert!(s.contains("Plain text"));
        assert!(s.contains("<p>HTML</p>"));
        // text/plain should come before text/html (RFC 2046 Section 5.1.4)
        let plain_pos = s.find("text/plain").unwrap();
        let html_pos = s.find("text/html").unwrap();
        assert!(plain_pos < html_pos);
    }

    #[test]
    fn build_with_attachment() {
        let mut email = make_email();
        email.body_text = Some("See attached".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "test.pdf".into(),
            content_type: "application/pdf".into(),
            data: b"fake pdf data".to_vec(),
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(s.contains("multipart/mixed"));
        assert!(s.contains("Content-Type: application/pdf"));
        assert!(s.contains("Content-Disposition: attachment; filename=\"test.pdf\""));
        assert!(s.contains("Content-Transfer-Encoding: base64"));
    }

    #[test]
    fn build_text_html_attachments() {
        let mut email = make_email();
        email.body_text = Some("Text".into());
        email.body_html = Some("<b>HTML</b>".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "file.txt".into(),
            content_type: "text/plain".into(),
            data: b"data".to_vec(),
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Should have outer multipart/mixed and inner multipart/alternative
        assert!(s.contains("multipart/mixed"));
        assert!(s.contains("multipart/alternative"));
    }

    #[test]
    fn build_no_body() {
        let email = make_email();
        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Should still have a text/plain content type
        assert!(s.contains("Content-Type: text/plain; charset=utf-8"));
    }

    #[test]
    fn build_bcc_not_in_headers() {
        let mut email = make_email();
        email.bcc = vec![Address {
            name: None,
            email: "hidden@example.com".into(),
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // BCC must NOT appear in headers (RFC 5322 Section 3.6.3)
        assert!(!s.contains("Bcc:"));
        assert!(!s.contains("hidden@example.com"));
    }

    #[test]
    fn build_bcc_in_envelope() {
        let mut email = make_email();
        email.bcc = vec![Address {
            name: None,
            email: "hidden@example.com".into(),
        }];

        let built = build_message(&email).unwrap();

        // BCC must be in envelope recipients
        assert!(built
            .envelope_recipients
            .contains(&"hidden@example.com".to_string()));
        assert!(built
            .envelope_recipients
            .contains(&"to@example.com".to_string()));
    }

    #[test]
    fn build_message_id_format() {
        let email = make_email();
        let built = build_message(&email).unwrap();

        // Message-ID should be hex@domain
        assert!(built.message_id.contains('@'));
        assert!(built.message_id.ends_with("example.com"));

        // Should appear in headers with angle brackets
        let s = raw_str(&built);
        assert!(s.contains(&format!("Message-ID: <{}>", built.message_id)));
    }

    #[test]
    fn build_threading_headers() {
        let mut email = make_email();
        email.in_reply_to = Some("parent@host.com".into());
        email.references = Some("root@host.com parent@host.com".into());

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(s.contains("In-Reply-To: <parent@host.com>"));
        assert!(s.contains("References: <root@host.com> <parent@host.com>"));
    }

    /// If the caller accidentally passes already-bracketed message-IDs,
    /// the builder must strip them before wrapping — not produce `<<id>>` which
    /// violates RFC 5322 Section 3.6.4 (msg-id = "<" addr-spec ">").
    #[test]
    fn build_threading_headers_already_bracketed() {
        let mut email = make_email();
        email.in_reply_to = Some("<parent@host.com>".into());
        email.references = Some("<root@host.com> <parent@host.com>".into());

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Must NOT double-wrap
        assert!(
            !s.contains("<<"),
            "Double angle brackets found in headers: {s}"
        );
        assert!(s.contains("In-Reply-To: <parent@host.com>"));
        assert!(s.contains("References: <root@host.com> <parent@host.com>"));
    }

    #[test]
    fn build_invalid_address_error() {
        let mut email = make_email();
        email.from.email = "not-an-email".into();

        let result = build_message(&email);
        assert!(matches!(result, Err(Error::InvalidAddress(_))));
    }

    #[test]
    fn build_empty_address_error() {
        let mut email = make_email();
        email.from.email = String::new();

        let result = build_message(&email);
        assert!(matches!(result, Err(Error::InvalidAddress(_))));
    }

    #[test]
    fn build_invalid_mime_fallback() {
        let mut email = make_email();
        email.body_text = Some("Body".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "file.bin".into(),
            content_type: "not_a_valid_mime".into(),
            data: b"data".to_vec(),
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Should fall back to application/octet-stream
        assert!(s.contains("Content-Type: application/octet-stream"));
    }

    #[test]
    fn build_reply_to() {
        let mut email = make_email();
        email.reply_to = Some(Address {
            name: Some("Reply".into()),
            email: "reply@example.com".into(),
        });

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(s.contains("Reply-To: Reply <reply@example.com>"));
    }

    #[test]
    fn build_no_recipients_error() {
        let mut email = make_email();
        email.to.clear();

        let result = build_message(&email);
        assert!(matches!(result, Err(Error::Build(_))));
    }

    #[test]
    fn build_cc_in_headers_and_envelope() {
        let mut email = make_email();
        email.cc = vec![Address {
            name: None,
            email: "cc@example.com".into(),
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(s.contains("Cc: cc@example.com"));
        assert!(built
            .envelope_recipients
            .contains(&"cc@example.com".to_string()));
    }

    #[test]
    fn build_attachment_base64_line_wrapping() {
        let mut email = make_email();
        email.body_text = Some("Body".into());
        // Create data that produces base64 longer than 76 chars
        email.attachments = vec![OutgoingAttachment {
            filename: "big.bin".into(),
            content_type: "application/octet-stream".into(),
            data: vec![0xAB; 100],
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Find base64 lines after Content-Transfer-Encoding: base64
        let after_b64_header = s.find("Content-Transfer-Encoding: base64").unwrap();
        let body_section = &s[after_b64_header..];
        // Check that no line exceeds 78 chars (76 + \r\n)
        for line in body_section.split("\r\n") {
            if !line.is_empty() && !line.starts_with("--") && !line.contains(':') {
                assert!(
                    line.len() <= 76,
                    "Base64 line too long ({} chars): {line}",
                    line.len()
                );
            }
        }
    }

    #[test]
    fn message_id_domain_fallback() {
        let mut email = make_email();
        email.from.email = "local-only@".into();
        // Should fail validation due to empty domain
        assert!(build_message(&email).is_err());
    }

    #[test]
    fn round_trip_build_then_parse() {
        let mut email = make_email();
        email.body_text = Some("Round-trip test body".into());
        email.body_html = Some("<p>Round-trip HTML</p>".into());
        email.in_reply_to = Some("parent@host.com".into());
        email.references = Some("root@host.com parent@host.com".into());
        email.cc = vec![Address {
            name: Some("CC User".into()),
            email: "cc@example.com".into(),
        }];

        let built = build_message(&email).unwrap();

        // Parse the built message
        let parsed = crate::parse_email(&built.raw).unwrap();

        assert_eq!(parsed.from.email, "sender@example.com");
        assert_eq!(parsed.from.name.as_deref(), Some("Sender"));
        assert_eq!(parsed.to.len(), 1);
        assert_eq!(parsed.to[0].email, "to@example.com");
        assert_eq!(parsed.cc.len(), 1);
        assert_eq!(parsed.cc[0].email, "cc@example.com");
        assert_eq!(parsed.subject.as_deref(), Some("Test Subject"));
        assert_eq!(
            parsed.message_id.as_deref(),
            Some(built.message_id.as_str())
        );
        assert_eq!(parsed.in_reply_to.as_deref(), Some("parent@host.com"));
        assert_eq!(
            parsed.references.as_deref(),
            Some("root@host.com parent@host.com")
        );
        assert_eq!(parsed.body_text.as_deref(), Some("Round-trip test body"));
        assert_eq!(parsed.body_html.as_deref(), Some("<p>Round-trip HTML</p>"));
        assert!(parsed.date.is_some());
    }

    #[test]
    fn message_id_is_crypto_random() {
        // Generate two Message-IDs and verify they're different (crypto-random)
        let email = make_email();
        let built1 = build_message(&email).unwrap();
        let built2 = build_message(&email).unwrap();
        assert_ne!(built1.message_id, built2.message_id);

        // Verify hex format: should be 32 hex chars + @ + domain
        let at_pos = built1.message_id.find('@').unwrap();
        let hex_part = &built1.message_id[..at_pos];
        assert_eq!(hex_part.len(), 32);
        assert!(hex_part.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn build_bcc_only_recipients() {
        // BCC-only: no To/Cc — should succeed with bcc in envelope only
        let mut email = make_email();
        email.to.clear();
        email.bcc = vec![Address {
            name: None,
            email: "hidden@example.com".into(),
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // No To header
        assert!(!s.contains("\r\nTo:"));
        // BCC must NOT appear in headers
        assert!(!s.contains("Bcc:"));
        assert!(!s.contains("hidden@example.com"));
        // But must be in envelope
        assert_eq!(built.envelope_recipients, vec!["hidden@example.com"]);
    }

    #[test]
    fn build_round_trip_with_attachments() {
        let mut email = make_email();
        email.body_text = Some("Text body".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "test.txt".into(),
            content_type: "text/plain".into(),
            data: b"attachment data".to_vec(),
        }];

        let built = build_message(&email).unwrap();
        let parsed = crate::parse_email(&built.raw).unwrap();

        assert_eq!(parsed.body_text.as_deref(), Some("Text body"));
        assert_eq!(parsed.attachments.len(), 1);
        assert_eq!(parsed.attachments[0].filename.as_deref(), Some("test.txt"));
    }

    #[test]
    fn build_html_only_with_attachments() {
        let mut email = make_email();
        email.body_html = Some("<p>Hello</p>".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "data.bin".into(),
            content_type: "application/octet-stream".into(),
            data: vec![1, 2, 3],
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Should have outer multipart/mixed
        assert!(s.contains("multipart/mixed"));
        assert!(s.contains("text/html; charset=utf-8"));
        assert!(s.contains("<p>Hello</p>"));
        assert!(s.contains("Content-Disposition: attachment; filename=\"data.bin\""));
    }

    #[test]
    fn build_whitespace_in_address_rejected() {
        let mut email = make_email();
        email.to = vec![Address {
            name: None,
            email: "bad user@example.com".into(),
        }];

        let result = build_message(&email);
        assert!(matches!(result, Err(Error::InvalidAddress(_))));
    }

    #[test]
    fn build_control_char_in_address_rejected() {
        let mut email = make_email();
        email.to = vec![Address {
            name: None,
            email: "user\x00@example.com".into(),
        }];

        let result = build_message(&email);
        assert!(matches!(result, Err(Error::InvalidAddress(_))));
    }

    #[test]
    fn build_envelope_contains_all_recipients() {
        let mut email = make_email();
        email.to = vec![Address {
            name: None,
            email: "to@x.com".into(),
        }];
        email.cc = vec![Address {
            name: None,
            email: "cc@x.com".into(),
        }];
        email.bcc = vec![Address {
            name: None,
            email: "bcc@x.com".into(),
        }];

        let built = build_message(&email).unwrap();
        assert_eq!(built.envelope_recipients.len(), 3);
        assert!(built.envelope_recipients.contains(&"to@x.com".to_string()));
        assert!(built.envelope_recipients.contains(&"cc@x.com".to_string()));
        assert!(built.envelope_recipients.contains(&"bcc@x.com".to_string()));
    }

    #[test]
    fn build_message_has_crlf_line_endings() {
        let mut email = make_email();
        email.body_text = Some("Hello".into());

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // All header lines should end with \r\n
        for line in s.split("\r\n") {
            assert!(
                !line.contains('\n') || line.is_empty(),
                "bare LF found in line: {line:?}"
            );
        }
    }

    /// Body text containing bare LF (`\n`) must be normalized
    /// to CRLF (`\r\n`) per RFC 5322 Section 2.1.
    #[test]
    fn build_body_bare_lf_normalized_to_crlf() {
        let mut email = make_email();
        email.body_text = Some("Line 1\nLine 2\nLine 3".into());

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // The body must not contain bare LF — all newlines should be CRLF
        for line in s.split("\r\n") {
            assert!(
                !line.contains('\n') || line.is_empty(),
                "bare LF found in output: {line:?}"
            );
        }
        // Verify the content is preserved
        assert!(s.contains("Line 1\r\nLine 2\r\nLine 3"));
    }

    /// HTML body with bare LF must also be normalized to CRLF.
    #[test]
    fn build_html_body_bare_lf_normalized_to_crlf() {
        let mut email = make_email();
        email.body_html = Some("<p>Line 1</p>\n<p>Line 2</p>".into());

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        for line in s.split("\r\n") {
            assert!(
                !line.contains('\n') || line.is_empty(),
                "bare LF found in HTML output: {line:?}"
            );
        }
    }

    /// Body with mixed line endings (\r\n and \n) must normalize all.
    #[test]
    fn build_body_mixed_line_endings_normalized() {
        let mut email = make_email();
        email.body_text = Some("CRLF line\r\nLF line\nAnother LF\n".into());

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        for line in s.split("\r\n") {
            assert!(
                !line.contains('\n') || line.is_empty(),
                "bare LF in mixed-endings output: {line:?}"
            );
        }
    }

    #[test]
    fn build_empty_attachment_data() {
        let mut email = make_email();
        email.body_text = Some("Body".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "empty.bin".into(),
            content_type: "application/octet-stream".into(),
            data: vec![],
        }];

        // Should succeed even with empty attachment data
        let built = build_message(&email).unwrap();
        let s = raw_str(&built);
        assert!(s.contains("Content-Disposition: attachment; filename=\"empty.bin\""));
    }

    #[test]
    fn build_multiple_attachments() {
        let mut email = make_email();
        email.body_text = Some("Body".into());
        email.attachments = vec![
            OutgoingAttachment {
                filename: "a.pdf".into(),
                content_type: "application/pdf".into(),
                data: b"pdf data".to_vec(),
            },
            OutgoingAttachment {
                filename: "b.png".into(),
                content_type: "image/png".into(),
                data: b"png data".to_vec(),
            },
        ];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(s.contains("filename=\"a.pdf\""));
        assert!(s.contains("filename=\"b.png\""));
        assert!(s.contains("Content-Type: application/pdf"));
        assert!(s.contains("Content-Type: image/png"));
    }

    #[test]
    fn build_date_header_rfc5322_format() {
        let email = make_email();
        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Find the Date header and verify format
        let date_line = s
            .lines()
            .find(|l| l.starts_with("Date: "))
            .expect("Date header missing");
        // Should contain day-of-week abbreviation
        let dow_names = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
        assert!(
            dow_names.iter().any(|d| date_line.contains(d)),
            "Date header missing day-of-week: {date_line}"
        );
        // Should end with timezone offset
        assert!(
            date_line.contains("+0000"),
            "Date header missing timezone: {date_line}"
        );
    }

    // -----------------------------------------------------------------------
    // Additional edge case tests
    // -----------------------------------------------------------------------

    #[test]
    fn build_unicode_subject() {
        let mut email = make_email();
        email.subject = "Héllo Wörld 你好 🌍".into();

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Subject must be RFC 2047 encoded, not raw UTF-8 (RFC 5322 Section 2.2)
        let header_section = s.split("\r\n\r\n").next().unwrap();
        assert!(
            header_section.is_ascii(),
            "Headers must be pure ASCII per RFC 5322 Section 2.2"
        );
        assert!(s.contains("=?UTF-8?B?"));

        // Must round-trip through parse
        let parsed = crate::parse_email(&built.raw).unwrap();
        assert_eq!(parsed.subject.as_deref(), Some("Héllo Wörld 你好 🌍"));
    }

    #[test]
    /// Non-ASCII display names must be RFC 2047 encoded in the raw
    /// message headers (RFC 5322 Section 2.2, RFC 2047 Section 5). The parser
    /// must decode them back to the original name.
    fn build_unicode_display_name() {
        let mut email = make_email();
        email.from = Address {
            name: Some("José García".into()),
            email: "jose@example.com".into(),
        };

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Raw headers must be pure ASCII (RFC 5322 Section 2.2)
        let header_section = s.split("\r\n\r\n").next().unwrap();
        assert!(
            header_section.is_ascii(),
            "Headers must be pure ASCII per RFC 5322 Section 2.2, \
             but found non-ASCII in: {header_section}"
        );

        // Round-trip: parser must decode the display name back
        let parsed = crate::parse_email(&built.raw).unwrap();
        assert_eq!(parsed.from.name.as_deref(), Some("José García"));
        assert_eq!(parsed.from.email, "jose@example.com");
    }

    #[test]
    fn build_empty_subject() {
        let mut email = make_email();
        email.subject = String::new();

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(s.contains("Subject: \r\n"));
    }

    #[test]
    fn build_special_chars_in_filename() {
        let mut email = make_email();
        email.body_text = Some("Body".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "my file (1).pdf".into(),
            content_type: "application/pdf".into(),
            data: b"data".to_vec(),
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(s.contains("filename=\"my file (1).pdf\""));
    }

    /// Non-ASCII filenames must be encoded using RFC 2231
    /// parameter encoding (`filename*=UTF-8''percent-encoded`), not raw
    /// UTF-8 bytes in a quoted-string. The parser must round-trip the
    /// encoded filename back to the original.
    #[test]
    fn build_non_ascii_filename_rfc2231_encoded() {
        let mut email = make_email();
        email.body_text = Some("Body".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "résumé.pdf".into(),
            content_type: "application/pdf".into(),
            data: b"data".to_vec(),
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Must use RFC 2231 encoding for non-ASCII filename
        assert!(
            s.contains("filename*=UTF-8''"),
            "Non-ASCII filename must use RFC 2231 encoding, got: {s}"
        );

        // Round-trip: parser should decode the RFC 2231 filename back
        let parsed = crate::parse_email(&built.raw).unwrap();
        assert_eq!(parsed.attachments.len(), 1);
        assert_eq!(
            parsed.attachments[0].filename.as_deref(),
            Some("résumé.pdf")
        );
    }

    /// Non-ASCII filenames must include a legacy `filename`
    /// parameter alongside `filename*` for backward compatibility with older
    /// email clients that don't support RFC 2231 (RFC 2231 Section 5).
    #[test]
    fn build_non_ascii_filename_includes_legacy_fallback() {
        let mut email = make_email();
        email.body_text = Some("Body".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "résumé.pdf".into(),
            content_type: "application/pdf".into(),
            data: b"data".to_vec(),
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Must have RFC 2231 encoded filename*
        assert!(
            s.contains("filename*=UTF-8''"),
            "Missing RFC 2231 filename*: {s}"
        );

        // Must ALSO have legacy filename= fallback for older clients
        // (RFC 2231 Section 5 — dual parameter approach)
        assert!(
            s.contains("filename=\""),
            "Missing legacy filename fallback for non-ASCII attachment: {s}"
        );
    }

    #[test]
    fn build_multiple_bcc_all_excluded() {
        let mut email = make_email();
        email.bcc = vec![
            Address {
                name: None,
                email: "bcc1@example.com".into(),
            },
            Address {
                name: None,
                email: "bcc2@example.com".into(),
            },
            Address {
                name: Some("BCC Three".into()),
                email: "bcc3@example.com".into(),
            },
        ];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // None of the BCC addresses should appear in headers (RFC 5322 Section 3.6.3)
        assert!(!s.contains("bcc1@example.com"));
        assert!(!s.contains("bcc2@example.com"));
        assert!(!s.contains("bcc3@example.com"));
        assert!(!s.contains("BCC Three"));
        assert!(!s.contains("Bcc:"));

        // But all should be in envelope
        assert_eq!(built.envelope_recipients.len(), 4); // 1 To + 3 BCC
        assert!(built
            .envelope_recipients
            .contains(&"bcc1@example.com".to_string()));
        assert!(built
            .envelope_recipients
            .contains(&"bcc2@example.com".to_string()));
        assert!(built
            .envelope_recipients
            .contains(&"bcc3@example.com".to_string()));
    }

    #[test]
    fn build_from_without_display_name() {
        let mut email = make_email();
        email.from = Address {
            name: None,
            email: "plain@example.com".into(),
        };

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Should be bare email without angle brackets
        assert!(s.contains("From: plain@example.com\r\n"));
    }

    #[test]
    fn build_all_recipient_types_together() {
        let mut email = make_email();
        email.to = vec![
            Address {
                name: Some("To One".into()),
                email: "to1@x.com".into(),
            },
            Address {
                name: None,
                email: "to2@x.com".into(),
            },
        ];
        email.cc = vec![Address {
            name: Some("CC One".into()),
            email: "cc1@x.com".into(),
        }];
        email.bcc = vec![Address {
            name: None,
            email: "bcc1@x.com".into(),
        }];
        email.reply_to = Some(Address {
            name: None,
            email: "reply@x.com".into(),
        });

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(s.contains("To: To One <to1@x.com>, to2@x.com"));
        assert!(s.contains("Cc: CC One <cc1@x.com>"));
        assert!(s.contains("Reply-To: reply@x.com"));
        assert!(!s.contains("Bcc:"));
        assert_eq!(built.envelope_recipients.len(), 4);
    }

    #[test]
    fn build_large_attachment_base64() {
        let mut email = make_email();
        email.body_text = Some("Body".into());
        // 1000 bytes of data → base64 should be properly line-wrapped
        email.attachments = vec![OutgoingAttachment {
            filename: "large.bin".into(),
            content_type: "application/octet-stream".into(),
            data: vec![0x42; 1000],
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Find base64 content and check all lines are ≤76 chars
        let b64_header = "Content-Transfer-Encoding: base64\r\n\r\n";
        let b64_start = s.find(b64_header).unwrap() + b64_header.len();
        let b64_end = s[b64_start..].find("\r\n--").unwrap_or(s.len() - b64_start);
        let b64_block = &s[b64_start..b64_start + b64_end];

        for line in b64_block.split("\r\n") {
            if !line.is_empty() {
                assert!(
                    line.len() <= 76,
                    "Base64 line exceeds 76 chars ({} chars): {}",
                    line.len(),
                    line
                );
            }
        }
    }

    #[test]
    fn build_round_trip_text_html_attachments() {
        // Full round-trip: build a complex message and verify it parses back
        let mut email = make_email();
        email.subject = "Complex message".into();
        email.body_text = Some("Plain text part".into());
        email.body_html = Some("<h1>HTML part</h1>".into());
        email.in_reply_to = Some("parent-id@example.com".into());
        email.references = Some("root@example.com parent-id@example.com".into());
        email.cc = vec![Address {
            name: Some("CC User".into()),
            email: "cc@example.com".into(),
        }];
        email.attachments = vec![
            OutgoingAttachment {
                filename: "doc.pdf".into(),
                content_type: "application/pdf".into(),
                data: b"pdf content".to_vec(),
            },
            OutgoingAttachment {
                filename: "img.png".into(),
                content_type: "image/png".into(),
                data: b"png content".to_vec(),
            },
        ];

        let built = build_message(&email).unwrap();
        let parsed = crate::parse_email(&built.raw).unwrap();

        assert_eq!(parsed.subject.as_deref(), Some("Complex message"));
        assert_eq!(parsed.from.email, "sender@example.com");
        assert_eq!(parsed.to.len(), 1);
        assert_eq!(parsed.cc.len(), 1);
        assert_eq!(
            parsed.message_id.as_deref(),
            Some(built.message_id.as_str())
        );
        assert_eq!(parsed.in_reply_to.as_deref(), Some("parent-id@example.com"));
        assert_eq!(
            parsed.references.as_deref(),
            Some("root@example.com parent-id@example.com")
        );
        assert_eq!(parsed.body_text.as_deref(), Some("Plain text part"));
        assert_eq!(parsed.body_html.as_deref(), Some("<h1>HTML part</h1>"));
        assert_eq!(parsed.attachments.len(), 2);
        assert_eq!(parsed.attachments[0].filename.as_deref(), Some("doc.pdf"));
        assert_eq!(parsed.attachments[1].filename.as_deref(), Some("img.png"));
    }

    #[test]
    fn build_message_id_fallback_domain() {
        // Test that domain extraction works correctly
        assert_eq!(extract_domain("user@example.com"), Some("example.com"));
        assert_eq!(
            extract_domain("user@sub.domain.org"),
            Some("sub.domain.org")
        );
        assert_eq!(extract_domain("user@"), None);
        assert_eq!(extract_domain("no-at-sign"), None);
    }

    #[test]
    fn build_no_body_with_attachments() {
        // No body text/html but has attachments — should get empty text/plain + attachment
        let mut email = make_email();
        email.attachments = vec![OutgoingAttachment {
            filename: "data.bin".into(),
            content_type: "application/octet-stream".into(),
            data: vec![1, 2, 3],
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(s.contains("multipart/mixed"));
        assert!(s.contains("text/plain; charset=utf-8"));
        assert!(s.contains("Content-Disposition: attachment; filename=\"data.bin\""));
    }

    #[test]
    fn build_multiple_mime_type_fallbacks() {
        let mut email = make_email();
        email.body_text = Some("Body".into());
        email.attachments = vec![
            OutgoingAttachment {
                filename: "a.bin".into(),
                content_type: String::new(), // empty
                data: b"data".to_vec(),
            },
            OutgoingAttachment {
                filename: "b.bin".into(),
                content_type: "no-slash".into(), // no slash
                data: b"data".to_vec(),
            },
            OutgoingAttachment {
                filename: "c.bin".into(),
                content_type: "/subtype".into(), // empty type
                data: b"data".to_vec(),
            },
        ];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // All should fall back to application/octet-stream
        let count = s.matches("Content-Type: application/octet-stream").count();
        assert_eq!(count, 3, "Expected 3 fallback MIME types, got {count}");
    }

    #[test]
    fn build_address_at_boundary_rejected() {
        // Address with @ at start or end
        let mut email = make_email();
        email.to = vec![Address {
            name: None,
            email: "@domain.com".into(),
        }];

        let result = build_message(&email);
        assert!(matches!(result, Err(Error::InvalidAddress(_))));

        let mut email2 = make_email();
        email2.to = vec![Address {
            name: None,
            email: "user@".into(),
        }];

        let result2 = build_message(&email2);
        assert!(matches!(result2, Err(Error::InvalidAddress(_))));
    }

    #[test]
    fn mime_type_validation_subtype_chars() {
        // Valid MIME types
        assert!(is_valid_mime_type("application/pdf"));
        assert!(is_valid_mime_type("image/svg+xml"));
        assert!(is_valid_mime_type("application/vnd.ms-excel"));

        // RFC 2045 Section 5.1: token allows any ASCII char except SPACE, CTLs,
        // and tspecials. Underscore, bang, hash, etc. are valid token chars.
        assert!(
            is_valid_mime_type("application/x-my_type"),
            "underscore is a valid token char per RFC 2045 Section 5.1"
        );
        assert!(
            is_valid_mime_type("application/x-custom!type"),
            "bang is a valid token char per RFC 2045 Section 5.1"
        );

        // Invalid: tspecials in subtype (RFC 2045 Section 5.1)
        assert!(!is_valid_mime_type("text/plain; charset=utf-8"));
        assert!(!is_valid_mime_type("text/html@bad"));
        assert!(!is_valid_mime_type("text/html(bad)"));
    }

    #[test]
    fn build_invalid_subtype_mime_fallback() {
        let mut email = make_email();
        email.body_text = Some("Body".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "file.bin".into(),
            content_type: "application/pdf; extra=bad".into(),
            data: b"data".to_vec(),
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Subtype contains ';' and spaces — should fall back to application/octet-stream
        assert!(s.contains("Content-Type: application/octet-stream"));
    }

    #[test]
    fn build_display_name_with_comma_is_quoted() {
        // Display names with commas must be quoted (RFC 5322 Section 3.4)
        let mut email = make_email();
        email.from = Address {
            name: Some("Doe, John".into()),
            email: "john@example.com".into(),
        };

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(
            s.contains("From: \"Doe, John\" <john@example.com>"),
            "From header should quote display name with comma: {s}"
        );
    }

    #[test]
    fn build_display_name_with_special_chars_is_quoted() {
        // Display names with RFC 5322 specials are quoted
        let mut email = make_email();
        email.from = Address {
            name: Some("O'Brien (test)".into()),
            email: "ob@example.com".into(),
        };

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(
            s.contains("\"O'Brien (test)\" <ob@example.com>"),
            "From header should quote display name with parens: {s}"
        );
    }

    #[test]
    fn build_display_name_with_quotes_escaped() {
        // Double-quotes in display names must be backslash-escaped (RFC 5322 Section 3.2.4)
        let mut email = make_email();
        email.from = Address {
            name: Some("John \"Doc\" Doe".into()),
            email: "john@example.com".into(),
        };

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(
            s.contains("\"John \\\"Doc\\\" Doe\" <john@example.com>"),
            "From header should escape quotes in display name: {s}"
        );
    }

    #[test]
    fn build_display_name_plain_not_quoted() {
        // Simple display names without specials should NOT be quoted
        let email = make_email();
        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // "Sender" has no specials — should not be quoted
        assert!(
            s.contains("From: Sender <sender@example.com>"),
            "Simple display name should not be quoted: {s}"
        );
    }

    #[test]
    fn build_round_trip_display_name_with_comma() {
        // Round-trip: build with comma in display name, parse it back
        let mut email = make_email();
        email.from = Address {
            name: Some("Doe, John".into()),
            email: "john@example.com".into(),
        };
        email.body_text = Some("Body".into());

        let built = build_message(&email).unwrap();
        let parsed = crate::parse_email(&built.raw).unwrap();

        assert_eq!(parsed.from.name.as_deref(), Some("Doe, John"));
        assert_eq!(parsed.from.email, "john@example.com");
    }

    #[test]
    fn build_round_trip_display_name_with_escaped_quotes() {
        // Round-trip: build with quotes in display name, parse it back
        let mut email = make_email();
        email.from = Address {
            name: Some("John \"Doc\" Doe".into()),
            email: "john@example.com".into(),
        };
        email.body_text = Some("Body".into());

        let built = build_message(&email).unwrap();
        let parsed = crate::parse_email(&built.raw).unwrap();

        assert_eq!(parsed.from.name.as_deref(), Some("John \"Doc\" Doe"));
        assert_eq!(parsed.from.email, "john@example.com");
    }

    #[test]
    fn build_attachment_filename_with_quotes_escaped() {
        // RFC 2183 Section 2 / RFC 5322 Section 3.2.4: quotes and backslashes
        // in filenames must be escaped within the quoted-string.
        let mut email = make_email();
        email.body_text = Some("Body".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "file\"name.pdf".into(),
            content_type: "application/pdf".into(),
            data: b"data".to_vec(),
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // The quote inside the filename must be backslash-escaped
        assert!(
            s.contains(r#"filename="file\"name.pdf""#),
            "Filename with quote not properly escaped: {s}"
        );
    }

    #[test]
    fn build_attachment_filename_with_backslash_escaped() {
        // RFC 5322 Section 3.2.4: backslash in quoted-string must be escaped
        let mut email = make_email();
        email.body_text = Some("Body".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "path\\file.pdf".into(),
            content_type: "application/pdf".into(),
            data: b"data".to_vec(),
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(
            s.contains(r#"filename="path\\file.pdf""#),
            "Filename with backslash not properly escaped: {s}"
        );
    }

    #[test]
    fn build_long_subject_is_folded() {
        // RFC 5322 Section 2.1.1: lines MUST be no more than 998 chars,
        // SHOULD be no more than 78 chars.
        let mut email = make_email();
        email.subject = "A".repeat(1000);

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // No single line (excluding CRLF) should exceed 998 characters
        for line in s.split("\r\n") {
            assert!(
                line.len() <= 998,
                "Line exceeds 998 chars ({} chars): {}...",
                line.len(),
                &line[..80.min(line.len())]
            );
        }
    }

    #[test]
    fn build_long_references_header_is_folded() {
        // Long References header with many message-ids
        let mut email = make_email();
        let ids: Vec<String> = (0..30)
            .map(|i| format!("id{i:04}@very-long-domain-name-for-testing.example.com"))
            .collect();
        email.references = Some(ids.join(" "));

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        for line in s.split("\r\n") {
            assert!(
                line.len() <= 998,
                "Line exceeds 998 chars ({} chars)",
                line.len()
            );
        }

        // The References header should still be parseable after folding
        let parsed = crate::parse_email(&built.raw).unwrap();
        assert!(parsed.references.is_some());
        let parsed_refs = parsed.references.unwrap();
        assert_eq!(parsed_refs.split_whitespace().count(), 30);
    }

    // -----------------------------------------------------------------------
    // UTF-8-aware force-fold (RFC 5322 Section 2.2.3)
    // -----------------------------------------------------------------------

    #[test]
    fn build_force_fold_preserves_utf8_boundaries() {
        // When a single word exceeds the 998-char hard limit and must be
        // force-folded, the fold must not split in the middle of a multi-byte
        // UTF-8 character. Each resulting line must be valid UTF-8.
        //
        // Use a subject consisting entirely of 4-byte emoji characters to
        // maximize the chance of hitting a multi-byte boundary.
        let mut email = make_email();
        // 300 emoji * 4 bytes = 1200 bytes — exceeds the 998-char hard limit
        // when combined with "Subject: " prefix (10 bytes).
        email.subject = "🌍".repeat(300);

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Every line must be valid UTF-8 on its own
        for (i, line) in s.split("\r\n").enumerate() {
            // Verify it's valid UTF-8 (raw_str already converted, but check
            // that no replacement characters were introduced by mid-char splits)
            assert!(
                !line.contains('\u{FFFD}'),
                "Line {i} contains UTF-8 replacement character from mid-char split: {line:?}"
            );
        }

        // The subject must round-trip without data corruption.
        // Folding inserts whitespace per RFC 5322 Section 2.2.3, so the
        // parsed subject may contain fold-point spaces — but no data loss.
        let parsed = crate::parse_email(&built.raw).unwrap();
        let parsed_subject = parsed.subject.unwrap();
        let original_no_ws: String = email
            .subject
            .chars()
            .filter(|c| !c.is_whitespace())
            .collect();
        let parsed_no_ws: String = parsed_subject
            .chars()
            .filter(|c| !c.is_whitespace())
            .collect();
        assert_eq!(
            parsed_no_ws, original_no_ws,
            "Force-folded UTF-8 subject must round-trip without data corruption"
        );
    }

    #[test]
    fn split_header_words_handles_escaped_quotes() {
        // RFC 5322 Section 3.2.4: a backslash-escaped quote `\"` inside a
        // quoted-string must NOT toggle the in_quotes state. Without this
        // fix, `"A\" B" <a@b.com>` is split into `["\"A\\\"", "B\"",
        // "<a@b.com>"]` — breaking the quoted-string across words.
        let value = r#""A\" B" <a@b.com>"#;
        let words = split_header_words(value);
        // The entire display-name + angle-addr should produce exactly two
        // tokens: the quoted-string name and the angle-bracketed email.
        assert_eq!(
            words,
            vec![r#""A\" B""#, "<a@b.com>"],
            "split_header_words must skip escaped quotes inside quoted-strings \
             per RFC 5322 Section 3.2.4"
        );
    }

    #[test]
    fn build_crlf_in_display_name_stripped() {
        // CRLF in a display name must not inject headers
        // (RFC 5322 Section 2.1/2.2 — header injection prevention).
        let mut email = make_email();
        email.from = Address {
            name: Some("evil\r\nBcc: injected@evil.com".into()),
            email: "sender@example.com".into(),
        };

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // The CRLF must be stripped — no injected header line starting with "Bcc:"
        assert!(
            !s.contains("\r\nBcc:"),
            "CRLF in display name must not inject headers: {s}"
        );
        // The injected address must not appear in envelope recipients
        assert!(
            !built
                .envelope_recipients
                .contains(&"injected@evil.com".to_string()),
            "Injected address must not appear in envelope"
        );
    }

    #[test]
    fn build_crlf_in_subject_stripped() {
        // CRLF in subject must not inject headers.
        let mut email = make_email();
        email.subject = "Test\r\nBcc: injected@evil.com".into();

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // The CRLF must be stripped — no injected header line
        assert!(
            !s.contains("\r\nBcc:"),
            "CRLF in subject must not inject headers: {s}"
        );
    }

    #[test]
    fn build_bare_lf_in_display_name_stripped() {
        // bare LF in a display name must not inject headers
        // (some servers treat bare LF as line ending).
        let mut email = make_email();
        email.from = Address {
            name: Some("evil\nBcc: injected@evil.com".into()),
            email: "sender@example.com".into(),
        };

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // No bare-LF-injected header line
        assert!(
            !s.contains("\nBcc:"),
            "Bare LF in display name must not inject headers: {s}"
        );
    }

    #[test]
    fn build_crlf_in_references_stripped() {
        // CRLF in references must not inject headers.
        let mut email = make_email();
        email.references = Some("root@host.com\r\nBcc: injected@evil.com".into());

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // No CRLF-injected header line
        assert!(
            !s.contains("\r\nBcc:"),
            "CRLF in references must not inject headers: {s}"
        );
    }

    #[test]
    fn build_round_trip_escaped_quote_name_long_header() {
        // Build a message with an escaped-quote display name long enough to
        // trigger header folding, then parse it back. The fold must not
        // split inside the quoted-string.
        let mut email = make_email();
        email.from = Address {
            name: Some("A\" B".into()),
            email: "user@very-long-domain-name-that-pushes-header-over-78-chars.example.com".into(),
        };
        email.body_text = Some("Body".into());

        let built = build_message(&email).unwrap();
        let parsed = crate::parse_email(&built.raw).unwrap();

        assert_eq!(
            parsed.from.name.as_deref(),
            Some("A\" B"),
            "Display name with escaped quote must survive folding round-trip"
        );
    }

    /// `normalize_line_endings` was processing bytes individually
    /// with `bytes[i] as char`, which treats each byte of a multi-byte UTF-8
    /// sequence as a separate Latin-1 character. This corrupts any non-ASCII
    /// text in the email body (e.g., "é" → "é").
    ///
    /// RFC 5322 Section 2.1 requires CRLF line endings, but the normalization
    /// must preserve UTF-8 character integrity (RFC 6532).
    #[test]
    fn build_non_ascii_body_preserved() {
        let mut email = make_email();
        email.body_text = Some("Héllo, José! Ñoño. 日本語テスト".into());

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(
            s.contains("Héllo, José! Ñoño. 日本語テスト"),
            "Non-ASCII UTF-8 body text must be preserved, got: {s}"
        );
    }

    /// non-ASCII characters in HTML bodies must also survive
    /// `normalize_line_endings` without corruption.
    #[test]
    fn build_non_ascii_html_body_preserved() {
        let mut email = make_email();
        email.body_html = Some("<p>Ünïcödé résumé</p>".into());

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(
            s.contains("<p>Ünïcödé résumé</p>"),
            "Non-ASCII UTF-8 HTML body must be preserved, got: {s}"
        );
    }

    /// non-ASCII in multipart text parts (text+html+attachments)
    /// must survive normalization.
    #[test]
    fn build_non_ascii_multipart_body_preserved() {
        let mut email = make_email();
        email.body_text = Some("Café".into());
        email.body_html = Some("<b>Café</b>".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "test.txt".into(),
            content_type: "text/plain".into(),
            data: b"data".to_vec(),
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(
            s.contains("Café"),
            "Non-ASCII in multipart text must be preserved, got: {s}"
        );
        assert!(
            s.contains("<b>Café</b>"),
            "Non-ASCII in multipart HTML must be preserved, got: {s}"
        );
    }

    /// Non-ASCII Subject must be RFC 2047 encoded in the raw
    /// message headers (RFC 5322 Section 2.2 — field bodies must be US-ASCII;
    /// RFC 2047 provides the encoding mechanism for non-ASCII text).
    /// The parser must decode it back to the original text.
    #[test]
    fn build_non_ascii_subject_rfc2047_round_trip() {
        let mut email = make_email();
        email.subject = "Héllo Wörld".into();

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Raw headers must NOT contain raw non-ASCII bytes — they must be
        // RFC 2047 encoded (RFC 5322 Section 2.2).
        let header_section = s.split("\r\n\r\n").next().unwrap();
        assert!(
            header_section.is_ascii(),
            "Headers must be pure ASCII per RFC 5322 Section 2.2, \
             but found non-ASCII in: {header_section}"
        );

        // The Subject header must contain RFC 2047 encoded word(s)
        assert!(
            s.contains("=?UTF-8?B?"),
            "Subject must be RFC 2047 B-encoded, got: {s}"
        );

        // Round-trip: parser must decode it back
        let parsed = crate::parse_email(&built.raw).unwrap();
        assert_eq!(
            parsed.subject.as_deref(),
            Some("Héllo Wörld"),
            "Subject must round-trip through RFC 2047 encoding"
        );
    }

    /// body text with lines exceeding 998 characters must use
    /// `Content-Transfer-Encoding: quoted-printable` instead of `8bit` to
    /// comply with RFC 2045 Section 2.8 and RFC 5322 Section 2.1.1.
    #[test]
    fn build_long_body_line_uses_quoted_printable() {
        let mut email = make_email();
        // Single line > 998 characters — violates RFC 5322 Section 2.1.1
        let long_line = "A".repeat(1200);
        email.body_text = Some(long_line.clone());

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Must use quoted-printable, not 8bit
        assert!(
            s.contains("Content-Transfer-Encoding: quoted-printable"),
            "Long body lines must trigger quoted-printable encoding \
             (RFC 2045 Section 2.8), but got:\n{s}"
        );
        assert!(
            !s.contains("Content-Transfer-Encoding: 8bit"),
            "8bit encoding must not be used when body has lines > 998 chars"
        );

        // No line in the output should exceed 998 characters
        for (i, line) in s.split("\r\n").enumerate() {
            assert!(
                line.len() <= 998,
                "Line {i} exceeds 998 chars ({} chars): {}...",
                line.len(),
                &line[..80.min(line.len())]
            );
        }

        // Round-trip: parse the built message and verify body text matches
        let parsed = crate::parse_email(&built.raw).unwrap();
        assert_eq!(
            parsed.body_text.as_deref(),
            Some(long_line.as_str()),
            "Body text must round-trip through quoted-printable encoding"
        );
    }

    /// Verify that short body lines still use `8bit` encoding (no unnecessary
    /// overhead from quoted-printable).
    #[test]
    fn build_normal_body_line_uses_8bit() {
        let mut email = make_email();
        email.body_text = Some("Short line, well under 998 chars.".into());

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(
            s.contains("Content-Transfer-Encoding: 8bit"),
            "Short body lines should use 8bit encoding, got:\n{s}"
        );
        assert!(
            !s.contains("Content-Transfer-Encoding: quoted-printable"),
            "Short body lines should not use quoted-printable"
        );
    }

    /// `generate_boundary_not_in` must return a boundary that does
    /// not appear in the supplied content. RFC 2046 Section 5.1.1 says:
    /// "The boundary delimiter MUST NOT appear within the encapsulated material."
    #[test]
    fn generate_boundary_not_in_avoids_collision() {
        // Generate a boundary and embed it in "content"
        let first = generate_boundary();
        let content = format!("Some text before\r\n--{first}\r\nSome text after");

        // generate_boundary_not_in must return a boundary different from `first`
        let second = generate_boundary_not_in(content.as_bytes());
        assert_ne!(
            first, second,
            "generate_boundary_not_in must produce a boundary that \
             differs from one already present in the content"
        );
        // The returned boundary must NOT appear anywhere in the content
        assert!(
            !content.contains(&second),
            "Returned boundary must not appear in the content, but \
             found '{second}' in '{content}'"
        );
    }

    /// the builder must generate boundaries that do not collide
    /// with body text. Verifies that a multipart message whose body text
    /// contains the boundary prefix `----=_Part_` round-trips correctly.
    ///
    /// RFC 2046 Section 5.1.1
    #[test]
    fn build_boundary_not_in_body() {
        let mut email = make_email();
        // Body text intentionally contains the boundary prefix used by
        // generate_boundary(). The full boundary (with 32 random hex chars)
        // must not collide.
        email.body_text =
            Some("Line 1\r\n----=_Part_00000000000000000000000000000000\r\nLine 2".into());
        email.body_html = Some("<p>HTML body</p>".into());

        let built = build_message(&email).unwrap();

        // Parse the built message back
        let parsed = crate::parse_email(&built.raw).unwrap();

        // The body text must round-trip exactly
        assert_eq!(
            parsed.body_text.as_deref(),
            Some("Line 1\r\n----=_Part_00000000000000000000000000000000\r\nLine 2"),
            "Body text containing boundary prefix must round-trip correctly"
        );
        assert_eq!(
            parsed.body_html.as_deref(),
            Some("<p>HTML body</p>"),
            "HTML body must round-trip correctly"
        );
    }

    /// RFC 2046 Section 5.1.1: boundary parameter values for nested multipart
    /// levels within the same message MUST be distinct. When building a
    /// text+html+attachments message, the outer multipart/mixed and inner
    /// multipart/alternative boundaries must differ.
    #[test]
    fn build_nested_multipart_boundaries_are_distinct() {
        let mut email = make_email();
        email.body_text = Some("Plain text".into());
        email.body_html = Some("<p>HTML</p>".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "data.bin".into(),
            content_type: "application/octet-stream".into(),
            data: vec![1, 2, 3],
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Extract all boundary values — search the raw string for boundary=
        // patterns since Content-Type headers may be folded across lines.
        let mut boundaries: Vec<String> = Vec::new();
        let lower = s.to_lowercase();
        let mut search_from = 0;
        while let Some(pos) = lower[search_from..].find("boundary=\"") {
            let abs = search_from + pos;
            let rest = &s[abs + 10..]; // skip 'boundary="'
            let end = rest.find('"').unwrap_or(rest.len());
            boundaries.push(rest[..end].to_string());
            search_from = abs + 10 + end;
        }

        assert_eq!(
            boundaries.len(),
            2,
            "Expected 2 boundary values (mixed + alternative), got {boundaries:?}"
        );
        assert_ne!(
            boundaries[0], boundaries[1],
            "Nested multipart boundaries must be distinct per RFC 2046 Section 5.1.1"
        );
    }

    /// attachment filenames containing CRLF must not inject
    /// arbitrary headers into the built message. RFC 5322 Section 2.1
    /// defines header fields as terminated by CRLF, so bare CRLF in
    /// user-provided values is a header injection vector.
    #[test]
    fn build_attachment_filename_crlf_sanitized() {
        let mut email = make_email();
        email.body_text = Some("Body".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "evil\r\nBcc: attacker@evil.com\r\nX-Injected: yes".into(),
            content_type: "application/pdf".into(),
            data: b"data".to_vec(),
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // The injected Bcc header must NOT appear as a real header
        assert!(
            !s.contains("\r\nBcc: attacker@evil.com"),
            "CRLF in filename must be stripped to prevent header injection \
             (RFC 5322 Section 2.1)"
        );
        assert!(
            !s.contains("\r\nX-Injected:"),
            "CRLF in filename must be stripped to prevent header injection"
        );
        // The filename should still be present (minus the CRLF)
        assert!(
            s.contains("Content-Disposition: attachment"),
            "Content-Disposition header must still be present"
        );
    }

    /// non-ASCII attachment filenames with CRLF must also be
    /// sanitized. The RFC 2231 encoding path percent-encodes CRLF in the
    /// `filename*` parameter, but the legacy `filename` fallback must
    /// also be safe.
    #[test]
    fn build_non_ascii_attachment_filename_crlf_sanitized() {
        let mut email = make_email();
        email.body_text = Some("Body".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "résumé\r\nBcc: attacker@evil.com".into(),
            content_type: "application/pdf".into(),
            data: b"data".to_vec(),
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // The injected Bcc header must NOT appear as a real header
        assert!(
            !s.contains("\r\nBcc: attacker@evil.com"),
            "CRLF in non-ASCII filename must be stripped to prevent header injection"
        );
    }

    #[test]
    fn build_attachment_filename_with_backslash_and_quote_escaped() {
        // Both backslash and double-quote in the same filename must be escaped
        // independently. Order matters: backslash first, then quote
        // (RFC 5322 Section 3.2.4).
        let mut email = make_email();
        email.body_text = Some("Body".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "path\\file\"name.pdf".into(),
            content_type: "application/pdf".into(),
            data: b"data".to_vec(),
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(
            s.contains(r#"filename="path\\file\"name.pdf""#),
            "Filename with both backslash and quote not properly escaped: {s}"
        );
    }

    #[test]
    fn build_display_name_with_backslash_escaped() {
        // Backslash in a display name must be escaped in the quoted-string
        // (RFC 5322 Section 3.2.4).
        let mut email = make_email();
        email.from = Address {
            name: Some("Back\\Slash".into()),
            email: "bs@example.com".into(),
        };

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(
            s.contains(r#""Back\\Slash" <bs@example.com>"#),
            "Display name with backslash not properly escaped: {s}"
        );
    }

    #[test]
    fn build_then_parse_filename_with_backslash_and_quote_round_trip() {
        // Round-trip: filename with both backslash and double-quote must survive
        // build → parse without corruption (RFC 5322 Section 3.2.4).
        let mut email = make_email();
        email.body_text = Some("Body".into());
        email.attachments = vec![OutgoingAttachment {
            filename: "path\\file\"name.pdf".into(),
            content_type: "application/pdf".into(),
            data: b"data".to_vec(),
        }];

        let built = build_message(&email).unwrap();
        let parsed = crate::parse_email(&built.raw).unwrap();

        assert_eq!(parsed.attachments.len(), 1);
        assert_eq!(
            parsed.attachments[0].filename.as_deref(),
            Some("path\\file\"name.pdf"),
            "Round-trip filename with backslash and quote must be preserved"
        );
    }

    // -----------------------------------------------------------------------
    // Coverage: generate_boundary_not_in fallback path (L529, L534-535, L538)
    // -----------------------------------------------------------------------

    /// `generate_boundary_not_in` falls back to a counter-based boundary
    /// when all random attempts collide with content. This is astronomically
    /// unlikely in production (32 hex chars of randomness), but the fallback
    /// path must work correctly.
    ///
    /// We cannot easily force the random generator to collide, so we test
    /// the fallback indirectly by verifying that the function always returns
    /// a boundary not present in the content, even when the content contains
    /// the boundary prefix.
    ///
    /// RFC 2046 Section 5.1.1
    #[test]
    fn generate_boundary_not_in_with_prefix_in_content() {
        // Content that contains many boundary-like strings. The function
        // should still return a boundary that does NOT collide.
        let mut content = String::new();
        for i in 0..20 {
            use std::fmt::Write;
            let _ = write!(content, "----=_Part_{i:032x}\r\n");
        }
        let boundary = generate_boundary_not_in(content.as_bytes());
        assert!(
            !content.contains(&boundary),
            "Returned boundary must not appear in content containing \
             many boundary-like strings (RFC 2046 Section 5.1.1)"
        );
    }

    // -----------------------------------------------------------------------
    // Coverage: generate_message_id (L573, L577-583)
    // -----------------------------------------------------------------------

    /// `generate_message_id` produces a string in `{hex}@{domain}` format
    /// per RFC 5322 Section 3.6.4. Verify format and uniqueness.
    #[test]
    fn generate_message_id_format_and_uniqueness() {
        let id1 = generate_message_id("example.com");
        let id2 = generate_message_id("example.com");

        // Each ID must contain exactly one '@'
        assert_eq!(
            id1.matches('@').count(),
            1,
            "Message-ID must contain exactly one '@' (RFC 5322 Section 3.6.4)"
        );
        // Domain must match
        assert!(
            id1.ends_with("@example.com"),
            "Message-ID must end with @domain: {id1}"
        );
        // Two consecutive IDs must differ (crypto-random)
        assert_ne!(
            id1, id2,
            "Message-IDs must be unique (RFC 5322 Section 3.6.4)"
        );
        // The local part (before @) must be 32 hex chars
        let local = id1.split('@').next().unwrap();
        assert_eq!(local.len(), 32, "Local part must be 32 hex chars: {local}");
        assert!(
            local.chars().all(|c| c.is_ascii_hexdigit()),
            "Local part must be hex digits: {local}"
        );
    }

    // -----------------------------------------------------------------------
    // Coverage: quoted-printable encoding (L746-784)
    // -----------------------------------------------------------------------

    /// CRLF passthrough in quoted-printable encoding (Rule #4):
    /// CRLF sequences must pass through unchanged as hard line breaks.
    ///
    /// RFC 2045 Section 6.7 Rule #4
    #[test]
    fn qp_crlf_passthrough() {
        let input = b"Line one\r\nLine two\r\n";
        let encoded = encode_quoted_printable(input);
        assert_eq!(
            encoded, b"Line one\r\nLine two\r\n",
            "CRLF must pass through unchanged in QP encoding \
             (RFC 2045 Section 6.7 Rule #4)"
        );
    }

    /// Trailing whitespace before CRLF must be encoded in QP (Rule #3).
    /// Space and TAB at end of a line must become =20 and =09.
    ///
    /// RFC 2045 Section 6.7 Rule #3
    #[test]
    fn qp_trailing_whitespace_encoded() {
        // Space before CRLF
        let input = b"trailing space \r\nnext line";
        let encoded = encode_quoted_printable(input);
        let encoded_str = String::from_utf8_lossy(&encoded);
        assert!(
            encoded_str.contains("trailing space=20\r\n"),
            "Trailing space before CRLF must be encoded as =20 \
             (RFC 2045 Section 6.7 Rule #3), got: {encoded_str}"
        );

        // TAB before CRLF
        let input_tab = b"trailing tab\t\r\nnext line";
        let encoded_tab = encode_quoted_printable(input_tab);
        let encoded_tab_str = String::from_utf8_lossy(&encoded_tab);
        assert!(
            encoded_tab_str.contains("trailing tab=09\r\n"),
            "Trailing TAB before CRLF must be encoded as =09 \
             (RFC 2045 Section 6.7 Rule #3), got: {encoded_tab_str}"
        );
    }

    /// Trailing whitespace at end of data (no CRLF following) must also
    /// be encoded (RFC 2045 Section 6.7 Rule #3).
    #[test]
    fn qp_trailing_whitespace_at_eof_encoded() {
        let input = b"end with space ";
        let encoded = encode_quoted_printable(input);
        let encoded_str = String::from_utf8_lossy(&encoded);
        assert!(
            encoded_str.ends_with("=20"),
            "Trailing space at EOF must be encoded as =20 \
             (RFC 2045 Section 6.7 Rule #3), got: {encoded_str}"
        );
    }

    /// Non-trailing whitespace (space/TAB followed by non-whitespace before
    /// next CRLF) should pass through unchanged (RFC 2045 Section 6.7 Rule #2).
    #[test]
    fn qp_non_trailing_whitespace_passthrough() {
        let input = b"hello world";
        let encoded = encode_quoted_printable(input);
        assert_eq!(
            encoded, b"hello world",
            "Non-trailing space must pass through unchanged \
             (RFC 2045 Section 6.7 Rule #2)"
        );
    }

    /// The `=` character must always be encoded as `=3D` in QP
    /// (RFC 2045 Section 6.7 Rule #1).
    #[test]
    fn qp_equals_sign_encoded() {
        let input = b"a=b";
        let encoded = encode_quoted_printable(input);
        assert_eq!(
            encoded, b"a=3Db",
            "`=` must be encoded as =3D (RFC 2045 Section 6.7 Rule #1)"
        );
    }

    /// Non-printable bytes must be encoded as `=XX` with uppercase hex
    /// (RFC 2045 Section 6.7 Rule #1).
    #[test]
    fn qp_non_printable_bytes_encoded() {
        // NUL byte
        let input = &[0x00u8];
        let encoded = encode_quoted_printable(input);
        assert_eq!(
            encoded, b"=00",
            "NUL byte must be encoded as =00 (RFC 2045 Section 6.7 Rule #1)"
        );

        // High byte (0xFF)
        let input_hi = &[0xFFu8];
        let encoded_hi = encode_quoted_printable(input_hi);
        assert_eq!(
            encoded_hi, b"=FF",
            "0xFF must be encoded as =FF (RFC 2045 Section 6.7 Rule #1)"
        );

        // DEL (0x7F)
        let input_del = &[0x7Fu8];
        let encoded_del = encode_quoted_printable(input_del);
        assert_eq!(
            encoded_del, b"=7F",
            "DEL must be encoded as =7F (RFC 2045 Section 6.7 Rule #1)"
        );
    }

    /// Lines in QP encoding must not exceed 76 characters. When encoding
    /// bytes that push past the limit, a soft line break (`=\r\n`) must
    /// be inserted (RFC 2045 Section 6.7 Rule #5).
    #[test]
    fn qp_soft_line_break_on_long_encoded_data() {
        // 100 bytes of 0xFF → each becomes =FF (3 chars). 100 * 3 = 300 chars.
        // Should be split across multiple lines of ≤76 chars each.
        let input: Vec<u8> = vec![0xFF; 100];
        let encoded = encode_quoted_printable(&input);
        let encoded_str = String::from_utf8_lossy(&encoded);
        for line in encoded_str.split("\r\n") {
            assert!(
                line.len() <= 76,
                "QP line exceeds 76-char limit ({} chars): {line} \
                 (RFC 2045 Section 6.7 Rule #5)",
                line.len()
            );
        }
        // Verify content round-trips: count the =FF occurrences
        let ff_count = encoded_str.matches("=FF").count();
        assert_eq!(
            ff_count, 100,
            "All 100 bytes must be encoded as =FF, got {ff_count}"
        );
    }

    /// Soft line breaks for literal (non-encoded) characters that would
    /// push past the 76-char line limit (RFC 2045 Section 6.7 Rule #5).
    #[test]
    fn qp_soft_line_break_on_long_literal_data() {
        // 200 'A' characters on one line — all printable, pass through as-is,
        // but must be wrapped with soft breaks at 76-char boundaries.
        let input: Vec<u8> = vec![b'A'; 200];
        let encoded = encode_quoted_printable(&input);
        let encoded_str = String::from_utf8_lossy(&encoded);
        for line in encoded_str.split("\r\n") {
            assert!(
                line.len() <= 76,
                "QP line exceeds 76-char limit ({} chars): {line}",
                line.len()
            );
        }
        // Verify all 'A' characters are preserved (soft breaks stripped)
        let reassembled: String = encoded_str.replace("=\r\n", "");
        let a_count = reassembled.chars().filter(|&c| c == 'A').count();
        assert_eq!(a_count, 200, "All 200 'A' chars must be preserved");
    }

    /// Mixed content: printable ASCII, CRLF, trailing whitespace, and
    /// non-printable bytes in a single QP encoding pass.
    #[test]
    fn qp_mixed_content_round_trip() {
        let mut email = make_email();
        // Body with a very long line (>998 chars) that includes special chars
        let mut long_line = String::new();
        long_line.push_str("Start ");
        for _ in 0..200 {
            long_line.push_str("abcde");
        }
        long_line.push_str(" \t end"); // trailing whitespace
        long_line.push_str("\r\n");
        long_line.push_str("Line with = sign and \x01 control char\r\n");
        email.body_text = Some(long_line.clone());

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Must use quoted-printable due to the long line
        assert!(
            s.contains("Content-Transfer-Encoding: quoted-printable"),
            "Long body line must trigger QP encoding (RFC 2045 Section 2.8)"
        );

        // No line in the output should exceed 998 characters
        for (i, line) in s.split("\r\n").enumerate() {
            assert!(
                line.len() <= 998,
                "Line {i} exceeds 998 chars ({} chars)",
                line.len()
            );
        }
    }

    // -----------------------------------------------------------------------
    // Coverage: is_trailing_whitespace helper (L810-821)
    // -----------------------------------------------------------------------

    /// `is_trailing_whitespace` returns `true` when whitespace is followed
    /// only by more whitespace before CRLF.
    ///
    /// RFC 2045 Section 6.7 Rule #3
    #[test]
    fn is_trailing_whitespace_before_crlf() {
        // Space followed by CRLF
        let data = b"abc \r\n";
        assert!(
            is_trailing_whitespace(data, 3),
            "Space directly before CRLF is trailing"
        );

        // Space followed by more spaces then CRLF
        let data2 = b"abc   \r\n";
        assert!(
            is_trailing_whitespace(data2, 3),
            "Space followed by spaces before CRLF is trailing"
        );

        // TAB followed by CRLF
        let data3 = b"abc\t\r\n";
        assert!(
            is_trailing_whitespace(data3, 3),
            "TAB directly before CRLF is trailing"
        );
    }

    /// `is_trailing_whitespace` returns `true` when whitespace is at
    /// end of data (no CRLF following).
    ///
    /// RFC 2045 Section 6.7 Rule #3
    #[test]
    fn is_trailing_whitespace_at_eof() {
        let data = b"abc ";
        assert!(
            is_trailing_whitespace(data, 3),
            "Space at end of data is trailing"
        );

        let data2 = b"abc\t";
        assert!(
            is_trailing_whitespace(data2, 3),
            "TAB at end of data is trailing"
        );
    }

    /// `is_trailing_whitespace` returns `false` when whitespace is
    /// followed by non-whitespace before the next CRLF.
    ///
    /// RFC 2045 Section 6.7 Rule #3
    #[test]
    fn is_trailing_whitespace_not_trailing() {
        let data = b"abc def";
        assert!(
            !is_trailing_whitespace(data, 3),
            "Space followed by non-whitespace is NOT trailing"
        );

        // TAB followed by text
        let data2 = b"abc\tdef";
        assert!(
            !is_trailing_whitespace(data2, 3),
            "TAB followed by non-whitespace is NOT trailing"
        );
    }

    // -----------------------------------------------------------------------
    // Coverage: utf8_char_len (L1025-1035)
    // -----------------------------------------------------------------------

    /// `utf8_char_len` returns the expected byte length for each class
    /// of UTF-8 lead byte.
    #[test]
    fn utf8_char_len_all_classes() {
        // ASCII (0x00..0x7F) → 1 byte
        assert_eq!(utf8_char_len(b'A'), 1, "ASCII 'A' is 1 byte");
        assert_eq!(utf8_char_len(0x00), 1, "NUL is 1 byte");
        assert_eq!(utf8_char_len(0x7F), 1, "DEL is 1 byte");

        // 2-byte lead (0x80..0xDF) → 2 bytes
        // 'é' = 0xC3 0xA9
        assert_eq!(utf8_char_len(0xC3), 2, "0xC3 (é lead) is 2-byte char");
        assert_eq!(utf8_char_len(0xC0), 2, "0xC0 is 2-byte lead");
        assert_eq!(utf8_char_len(0xDF), 2, "0xDF is 2-byte lead");

        // 3-byte lead (0xE0..0xEF) → 3 bytes
        // '你' = 0xE4 0xBD 0xA0
        assert_eq!(utf8_char_len(0xE4), 3, "0xE4 (CJK lead) is 3-byte char");
        assert_eq!(utf8_char_len(0xE0), 3, "0xE0 is 3-byte lead");
        assert_eq!(utf8_char_len(0xEF), 3, "0xEF is 3-byte lead");

        // 4-byte lead (0xF0..0xFF) → 4 bytes
        // '🌍' = 0xF0 0x9F 0x8C 0x8D
        assert_eq!(utf8_char_len(0xF0), 4, "0xF0 (emoji lead) is 4-byte char");
        assert_eq!(utf8_char_len(0xF4), 4, "0xF4 is 4-byte lead");
        assert_eq!(utf8_char_len(0xFF), 4, "0xFF is 4-byte lead");
    }

    // -----------------------------------------------------------------------
    // Coverage: snap_utf8_chunk_end for multi-byte characters (L1010-1011)
    // -----------------------------------------------------------------------

    /// `snap_utf8_chunk_end` must not split multi-byte UTF-8 characters.
    /// When the budget is too small for even one complete character, it
    /// must advance past the full character to avoid an infinite loop.
    #[test]
    fn snap_utf8_chunk_end_undersized_budget() {
        // '🌍' is 4 bytes (0xF0 0x9F 0x8C 0x8D). If max_bytes is 1-3,
        // the function cannot fit any character, so it must advance past
        // the entire 4-byte sequence to avoid an infinite loop.
        let emoji = "🌍".as_bytes();
        assert_eq!(emoji.len(), 4);

        // Budget of 1 byte — can't fit the 4-byte char, must advance past it
        let end = snap_utf8_chunk_end(emoji, 0, 1);
        assert_eq!(end, 4, "Budget too small for one char must advance past it");

        // Budget of 2 bytes — still can't fit
        let end = snap_utf8_chunk_end(emoji, 0, 2);
        assert_eq!(end, 4);

        // Budget of 3 bytes — still can't fit
        let end = snap_utf8_chunk_end(emoji, 0, 3);
        assert_eq!(end, 4);

        // Budget of 4 bytes — exactly fits
        let end = snap_utf8_chunk_end(emoji, 0, 4);
        assert_eq!(end, 4);

        // 3-byte char '你' (0xE4 0xBD 0xA0) with budget of 2
        let cjk = "".as_bytes();
        assert_eq!(cjk.len(), 3);
        let end = snap_utf8_chunk_end(cjk, 0, 2);
        assert_eq!(
            end, 3,
            "Budget of 2 can't fit 3-byte char, must advance past it"
        );

        // 2-byte char 'é' (0xC3 0xA9) with budget of 1
        let accent = "é".as_bytes();
        assert_eq!(accent.len(), 2);
        let end = snap_utf8_chunk_end(accent, 0, 1);
        assert_eq!(
            end, 2,
            "Budget of 1 can't fit 2-byte char, must advance past it"
        );
    }

    /// `snap_utf8_chunk_end` correctly snaps back to character boundaries
    /// when the budget lands in the middle of a multi-byte sequence.
    #[test]
    fn snap_utf8_chunk_end_snaps_to_boundary() {
        // "Aé" = [0x41, 0xC3, 0xA9] — 'A' (1 byte) + 'é' (2 bytes)
        let data = "".as_bytes();
        assert_eq!(data.len(), 3);

        // Budget of 2: lands at byte 2 (0xA9, continuation byte of 'é').
        // Must snap back to byte 1 (start of 'é'), so chunk is just 'A'.
        let end = snap_utf8_chunk_end(data, 0, 2);
        assert_eq!(
            end, 1,
            "Must snap back to char boundary, excluding incomplete 'é'"
        );

        // Budget of 3: exactly fits both characters
        let end = snap_utf8_chunk_end(data, 0, 3);
        assert_eq!(end, 3, "Budget of 3 fits both 'A' and 'é'");
    }

    // -----------------------------------------------------------------------
    // Coverage: header folding with long subject (L634 force-fold path)
    // -----------------------------------------------------------------------

    /// A subject consisting of a single very long word (no spaces) must
    /// be force-folded at UTF-8 character boundaries to stay within the
    /// 998-char hard limit per RFC 5322 Section 2.1.1.
    #[test]
    fn build_very_long_single_word_subject_force_folded() {
        let mut email = make_email();
        // 1100 ASCII chars with no spaces — exceeds 998-char hard limit.
        // Must be force-folded since there are no word boundaries.
        email.subject = "X".repeat(1100);

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        for (i, line) in s.split("\r\n").enumerate() {
            assert!(
                line.len() <= 998,
                "Line {i} exceeds 998 chars ({} chars) after force-fold: {}...",
                line.len(),
                &line[..80.min(line.len())]
            );
        }
    }

    /// A very long address list should be folded at word boundaries
    /// per RFC 5322 Section 2.2.3. Lines should stay under 78 chars
    /// where possible (SHOULD limit) and never exceed 998 (MUST limit).
    #[test]
    fn build_very_long_address_list_folded() {
        let mut email = make_email();
        // 20 recipients with long addresses — the To header will be very long
        email.to = (0..20)
            .map(|i| Address {
                name: Some(format!("User Number {i:03}")),
                email: format!("user{i:03}@very-long-domain-name.example.com"),
            })
            .collect();

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        for (i, line) in s.split("\r\n").enumerate() {
            assert!(
                line.len() <= 998,
                "Line {i} exceeds 998-char hard limit ({} chars) in long address list",
                line.len()
            );
        }

        // Verify all recipients made it into the envelope
        assert_eq!(built.envelope_recipients.len(), 20);
    }

    /// An encoded-word subject (RFC 2047) that is very long should be
    /// folded correctly. Each `=?UTF-8?B?...?=` word is separated by
    /// a space, and `write_header` should fold at those spaces.
    ///
    /// RFC 2047 Section 2, RFC 5322 Section 2.2.3
    #[test]
    fn build_long_rfc2047_subject_folded() {
        let mut email = make_email();
        // Long non-ASCII subject — will be split into multiple encoded words,
        // and the header should be folded at encoded-word boundaries.
        email.subject = "日本語テスト ".repeat(50);

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        for (i, line) in s.split("\r\n").enumerate() {
            assert!(
                line.len() <= 998,
                "Line {i} exceeds 998-char limit for RFC 2047 subject ({} chars)",
                line.len()
            );
        }

        // Verify the subject round-trips
        let parsed = crate::parse_email(&built.raw).unwrap();
        let original = email.subject.trim();
        let parsed_subject = parsed.subject.unwrap();
        assert_eq!(
            parsed_subject.trim(),
            original,
            "Long RFC 2047 subject must round-trip"
        );
    }

    // -----------------------------------------------------------------------
    // Coverage: encode_rfc2047_if_needed with multi-byte characters
    // -----------------------------------------------------------------------

    /// `encode_rfc2047_if_needed` must handle 2-byte, 3-byte, and 4-byte
    /// UTF-8 characters correctly, splitting at character boundaries when
    /// the encoded-word exceeds 75 chars (RFC 2047 Section 2).
    #[test]
    fn encode_rfc2047_multibyte_chars() {
        // 2-byte characters: 'é' (U+00E9)
        let two_byte = "é".repeat(100);
        let encoded = encode_rfc2047_if_needed(&two_byte);
        assert!(
            encoded.contains("=?UTF-8?B?"),
            "Non-ASCII text must be RFC 2047 encoded"
        );
        // Each encoded word must be ≤75 chars (RFC 2047 Section 2)
        for word in encoded.split(' ') {
            if word.starts_with("=?") {
                assert!(
                    word.len() <= 75,
                    "Encoded word exceeds 75 chars ({} chars): {word}",
                    word.len()
                );
            }
        }

        // 3-byte characters: '日' (U+65E5)
        let three_byte = "".repeat(100);
        let encoded = encode_rfc2047_if_needed(&three_byte);
        for word in encoded.split(' ') {
            if word.starts_with("=?") {
                assert!(
                    word.len() <= 75,
                    "3-byte char encoded word exceeds 75 chars ({} chars): {word}",
                    word.len()
                );
            }
        }

        // 4-byte characters: '🌍' (U+1F30D)
        let four_byte = "🌍".repeat(100);
        let encoded = encode_rfc2047_if_needed(&four_byte);
        for word in encoded.split(' ') {
            if word.starts_with("=?") {
                assert!(
                    word.len() <= 75,
                    "4-byte char encoded word exceeds 75 chars ({} chars): {word}",
                    word.len()
                );
            }
        }

        // Pure ASCII should pass through unchanged
        let ascii = "Hello World";
        assert_eq!(
            encode_rfc2047_if_needed(ascii),
            "Hello World",
            "Pure ASCII must not be encoded (RFC 2047 Section 5)"
        );
    }

    // -----------------------------------------------------------------------
    // Coverage: body with QP encoding and CRLF, trailing whitespace
    // integrated through build_message
    // -----------------------------------------------------------------------

    /// Full integration test: body text with lines >998 chars that also
    /// contains CRLF sequences, trailing whitespace, and special chars.
    /// Exercises the QP encoder's CRLF passthrough (L746-749), trailing
    /// whitespace detection (L758), and hex encoding paths (L773-784).
    ///
    /// RFC 2045 Section 6.7
    #[test]
    fn build_qp_body_with_crlf_and_trailing_whitespace() {
        let mut email = make_email();
        // Build a body that triggers QP encoding (>998 chars on one line)
        // and includes CRLF, trailing whitespace, and special chars.
        let mut body = String::new();
        // Very long first line to trigger QP
        body.push_str(&"B".repeat(1100));
        body.push_str("\r\n");
        // Line with trailing space before CRLF
        body.push_str("trailing space \r\n");
        // Line with trailing tab before CRLF
        body.push_str("trailing tab\t\r\n");
        // Line with = sign
        body.push_str("equals = sign\r\n");
        // Line with non-ASCII
        body.push_str("café résumé\r\n");
        email.body_text = Some(body);

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(
            s.contains("Content-Transfer-Encoding: quoted-printable"),
            "Must use QP encoding for body with >998-char lines"
        );

        // No line should exceed 998 chars
        for (i, line) in s.split("\r\n").enumerate() {
            assert!(
                line.len() <= 998,
                "Line {i} exceeds 998-char limit ({} chars)",
                line.len()
            );
        }
    }

    /// HTML body with lines >998 chars must also use quoted-printable.
    ///
    /// RFC 2045 Section 2.8
    #[test]
    fn build_long_html_body_uses_quoted_printable() {
        let mut email = make_email();
        // Single long HTML line
        let long_html = format!("<p>{}</p>", "x".repeat(1100));
        email.body_html = Some(long_html);

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        assert!(
            s.contains("Content-Transfer-Encoding: quoted-printable"),
            "Long HTML body lines must trigger QP encoding"
        );

        for (i, line) in s.split("\r\n").enumerate() {
            assert!(
                line.len() <= 998,
                "HTML QP line {i} exceeds 998-char limit ({} chars)",
                line.len()
            );
        }
    }

    /// Multipart message (text + html + attachments) where both text parts
    /// have long lines must use quoted-printable for both.
    ///
    /// RFC 2045 Section 2.8, RFC 2046 Section 5.1.4
    #[test]
    fn build_multipart_with_long_lines_uses_qp() {
        let mut email = make_email();
        email.body_text = Some("T".repeat(1100));
        email.body_html = Some("H".repeat(1100));
        email.attachments = vec![OutgoingAttachment {
            filename: "file.bin".into(),
            content_type: "application/octet-stream".into(),
            data: vec![1, 2, 3],
        }];

        let built = build_message(&email).unwrap();
        let s = raw_str(&built);

        // Count QP headers — should have 2 (one for text, one for html)
        let qp_count = s
            .matches("Content-Transfer-Encoding: quoted-printable")
            .count();
        assert_eq!(
            qp_count, 2,
            "Both text and HTML parts with long lines must use QP, got {qp_count}"
        );

        for (i, line) in s.split("\r\n").enumerate() {
            assert!(
                line.len() <= 998,
                "Multipart QP line {i} exceeds 998-char limit ({} chars)",
                line.len()
            );
        }
    }
}