daaki-smtp 0.2.0

An async SMTP client library
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
//! Integration tests for the SMTP client.
//!
//! These tests run against real SMTP servers in Docker.
//!
//! # Setup
//!
//! ```sh
//! docker compose up -d           # start Mailpit + GreenMail
//! cargo test -p daaki-smtp -- --ignored
//! docker compose down
//! ```
//!
//! # Servers under test
//!
//! - **Mailpit** (Go, test-oriented) — port 11025, HTTP API on 18025
//! - **`GreenMail`** (Java, test-oriented) — port 13025
//!
//! Both servers capture all mail without delivering, making them safe for testing.

#![allow(clippy::unwrap_used, clippy::expect_used)]

use std::sync::Arc;
use std::time::Duration;

use daaki_smtp::{
    AuthMechanism, BodyType, Error, ForwardPath, MailFromParams, Protocol, ReversePath,
    SmtpConnection, TlsMode,
};

const TIMEOUT: Duration = Duration::from_secs(10);

/// Minimal RFC 5322 message for send tests.
fn test_message(id: &str) -> Vec<u8> {
    format!(
        "From: sender@example.com\r\n\
         To: recipient@example.com\r\n\
         Subject: SMTP integration test {id}\r\n\
         Date: Sun, 15 Mar 2026 00:00:00 +0000\r\n\
         Message-ID: <{id}@daaki>\r\n\
         MIME-Version: 1.0\r\n\
         Content-Type: text/plain; charset=utf-8\r\n\
         \r\n\
         Hello from daaki SMTP integration tests.\r\n"
    )
    .into_bytes()
}

// ---------------------------------------------------------------------------
// Server configurations
// ---------------------------------------------------------------------------

mod mailpit {
    pub const HOST: &str = "127.0.0.1";
    pub const SMTP_PORT: u16 = 11025;
    pub const _HTTP_PORT: u16 = 18025;
    pub const USER: &str = "testuser";
    pub const PASS: &str = "testpass";
}

mod greenmail {
    pub const HOST: &str = "127.0.0.1";
    pub const SMTP_PORT: u16 = 13025;
    pub const SMTPS_PORT: u16 = 13465;
    // GreenMail SMTP AUTH requires the bare username (no @domain),
    // unlike IMAP LOGIN which uses the full "user@domain" form.
    pub const USER: &str = "testuser";
    pub const PASS: &str = "testpass";
}

// ==========================================================================
// Connection & Authentication (RFC 5321 Section 3.1, RFC 4954)
// ==========================================================================

// --- Mailpit ---

/// Connect to Mailpit and authenticate with PLAIN.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_connect_and_auth() {
    let conn = SmtpConnection::connect(mailpit::HOST, mailpit::SMTP_PORT, TlsMode::None, TIMEOUT)
        .await
        .unwrap();

    conn.auth_plain(mailpit::USER, mailpit::PASS, TIMEOUT)
        .await
        .unwrap();
    conn.quit(TIMEOUT).await.unwrap();
}

// --- GreenMail ---

/// Connect to `GreenMail` over plaintext and authenticate.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_connect_and_auth() {
    let conn = SmtpConnection::connect(
        greenmail::HOST,
        greenmail::SMTP_PORT,
        TlsMode::None,
        TIMEOUT,
    )
    .await
    .unwrap();

    conn.auth_plain(greenmail::USER, greenmail::PASS, TIMEOUT)
        .await
        .unwrap();
    conn.quit(TIMEOUT).await.unwrap();
}

/// Connect to `GreenMail` over implicit TLS (SMTPS, port 13465).
///
/// `GreenMail` uses self-signed certificates, so we need a danger TLS config.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_connect_implicit_tls() {
    let tls_config = build_danger_tls_config();
    let conn = SmtpConnection::connect_with_tls_config(
        greenmail::HOST,
        greenmail::SMTPS_PORT,
        TlsMode::Implicit,
        TIMEOUT,
        tls_config,
    )
    .await
    .unwrap();

    conn.auth_plain(greenmail::USER, greenmail::PASS, TIMEOUT)
        .await
        .unwrap();
    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Sending messages (RFC 5321 Section 3.3 — MAIL/RCPT/DATA sequence)
// ==========================================================================

/// Send a simple message through Mailpit.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_send_simple() {
    let conn = connect_mailpit().await;

    let msg = test_message("mailpit-simple");
    conn.send(
        &ReversePath::new("sender@example.com").unwrap(),
        &[ForwardPath::new("recipient@example.com").unwrap()],
        &msg,
        TIMEOUT,
    )
    .await
    .unwrap();

    conn.quit(TIMEOUT).await.unwrap();
}

/// Send a message to multiple recipients.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_send_multiple_recipients() {
    let conn = connect_mailpit().await;

    let msg = test_message("mailpit-multi");
    conn.send(
        &ReversePath::new("sender@example.com").unwrap(),
        &[
            ForwardPath::new("alice@example.com").unwrap(),
            ForwardPath::new("bob@example.com").unwrap(),
            ForwardPath::new("carol@example.com").unwrap(),
        ],
        &msg,
        TIMEOUT,
    )
    .await
    .unwrap();

    conn.quit(TIMEOUT).await.unwrap();
}

/// Send a simple message through `GreenMail`.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_send_simple() {
    let conn = connect_greenmail().await;

    let msg = test_message("greenmail-simple");
    conn.send(
        &ReversePath::new("sender@example.com").unwrap(),
        &[ForwardPath::new("recipient@example.com").unwrap()],
        &msg,
        TIMEOUT,
    )
    .await
    .unwrap();

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// 8-bit content (RFC 1652 8BITMIME)
// ==========================================================================

/// Send a message containing non-ASCII UTF-8 body content.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_send_8bit_content() {
    let conn = connect_mailpit().await;

    let msg = "From: sender@example.com\r\n\
               To: recipient@example.com\r\n\
               Subject: 8-bit test\r\n\
               Date: Sun, 15 Mar 2026 00:00:00 +0000\r\n\
               Message-ID: <8bit@daaki>\r\n\
               MIME-Version: 1.0\r\n\
               Content-Type: text/plain; charset=utf-8\r\n\
               Content-Transfer-Encoding: 8bit\r\n\
               \r\n\
               Héllo wörld! 你好世界 🌍\r\n";

    conn.send(
        &ReversePath::new("sender@example.com").unwrap(),
        &[ForwardPath::new("recipient@example.com").unwrap()],
        msg.as_bytes(),
        TIMEOUT,
    )
    .await
    .unwrap();

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Session management (RFC 5321 Section 4.1.1.5 RSET)
// ==========================================================================

/// RSET between sends — resets the mail transaction without disconnecting.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_rset_between_sends() {
    let conn = connect_mailpit().await;

    // First send.
    let msg1 = test_message("mailpit-rset-1");
    conn.send(
        &ReversePath::new("sender@example.com").unwrap(),
        &[ForwardPath::new("recipient@example.com").unwrap()],
        &msg1,
        TIMEOUT,
    )
    .await
    .unwrap();

    // Reset session state.
    conn.reset(TIMEOUT).await.unwrap();

    // Second send on same connection.
    let msg2 = test_message("mailpit-rset-2");
    conn.send(
        &ReversePath::new("sender@example.com").unwrap(),
        &[ForwardPath::new("other@example.com").unwrap()],
        &msg2,
        TIMEOUT,
    )
    .await
    .unwrap();

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Dot-stuffing edge case (RFC 5321 Section 4.5.2)
// ==========================================================================

/// Message body containing lines starting with "." — must be dot-stuffed.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_send_dot_stuffed() {
    let conn = connect_mailpit().await;

    let msg = "From: sender@example.com\r\n\
               To: recipient@example.com\r\n\
               Subject: dot-stuff test\r\n\
               Date: Sun, 15 Mar 2026 00:00:00 +0000\r\n\
               Message-ID: <dot-stuff@daaki>\r\n\
               MIME-Version: 1.0\r\n\
               Content-Type: text/plain\r\n\
               \r\n\
               Normal line.\r\n\
               .This line starts with a dot.\r\n\
               ..Two dots.\r\n\
               ...Three dots.\r\n\
               End.\r\n";

    conn.send(
        &ReversePath::new("sender@example.com").unwrap(),
        &[ForwardPath::new("recipient@example.com").unwrap()],
        msg.as_bytes(),
        TIMEOUT,
    )
    .await
    .unwrap();

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Empty / edge-case messages
// ==========================================================================

/// Minimal valid RFC 5322 message (headers only, empty body).
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_send_empty_body() {
    let conn = connect_mailpit().await;

    let msg = "From: sender@example.com\r\n\
               To: recipient@example.com\r\n\
               Subject: empty body\r\n\
               Date: Sun, 15 Mar 2026 00:00:00 +0000\r\n\
               Message-ID: <empty@daaki>\r\n\
               \r\n";

    conn.send(
        &ReversePath::new("sender@example.com").unwrap(),
        &[ForwardPath::new("recipient@example.com").unwrap()],
        msg.as_bytes(),
        TIMEOUT,
    )
    .await
    .unwrap();

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// QUIT without sending (RFC 5321 Section 4.1.1.10)
// ==========================================================================

/// Connect, authenticate, then immediately QUIT — no mail transaction.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_quit_immediately() {
    let conn = SmtpConnection::connect(mailpit::HOST, mailpit::SMTP_PORT, TlsMode::None, TIMEOUT)
        .await
        .unwrap();

    conn.auth_plain(mailpit::USER, mailpit::PASS, TIMEOUT)
        .await
        .unwrap();
    conn.quit(TIMEOUT).await.unwrap();
}

#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_quit_immediately() {
    let conn = SmtpConnection::connect(
        greenmail::HOST,
        greenmail::SMTP_PORT,
        TlsMode::None,
        TIMEOUT,
    )
    .await
    .unwrap();

    conn.auth_plain(greenmail::USER, greenmail::PASS, TIMEOUT)
        .await
        .unwrap();
    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// NOOP — keepalive probe (RFC 5321 Section 4.1.1.9)
// ==========================================================================

/// NOOP must return 250 OK and not affect session state.
///
/// RFC 5321 Section 4.1.1.9: "This command does not affect any
/// parameters or previously entered commands."
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_noop_keepalive() {
    let conn = connect_mailpit().await;

    // NOOP should succeed silently.
    conn.noop(TIMEOUT).await.unwrap();

    // Session must still be usable after NOOP.
    let msg = test_message("mailpit-noop");
    conn.send(
        &ReversePath::new("sender@example.com").unwrap(),
        &[ForwardPath::new("recipient@example.com").unwrap()],
        &msg,
        TIMEOUT,
    )
    .await
    .unwrap();

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Server capabilities (RFC 5321 Section 4.1.1.1)
// ==========================================================================

/// After connecting, the server's EHLO response must populate capabilities.
///
/// RFC 5321 Section 4.1.1.1: the server advertises extensions as EHLO
/// keyword lines following the greeting name.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_capabilities_advertised() {
    let conn = SmtpConnection::connect(mailpit::HOST, mailpit::SMTP_PORT, TlsMode::None, TIMEOUT)
        .await
        .unwrap();

    let caps = conn.capabilities().await;

    // The greeting name must be non-empty (RFC 5321 Section 4.1.1.1).
    assert!(
        !caps.greeting_name().is_empty(),
        "EHLO greeting name must not be empty"
    );

    // Mailpit is configured with MP_SMTP_AUTH, so AUTH must be advertised.
    assert!(
        caps.supports_auth_extension(),
        "server must advertise AUTH when authentication is configured"
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Protocol accessor
// ==========================================================================

/// `protocol()` must return `Protocol::Smtp` for an SMTP connection.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_protocol_is_smtp() {
    let conn = SmtpConnection::connect(mailpit::HOST, mailpit::SMTP_PORT, TlsMode::None, TIMEOUT)
        .await
        .unwrap();

    assert_eq!(conn.protocol(), Protocol::Smtp);

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Authentication state tracking (RFC 4954 Section 3)
// ==========================================================================

/// `is_authenticated()` must transition from `false` to `true` after
/// a successful AUTH command.
///
/// RFC 4954 Section 3: "After an AUTH command has been successfully
/// completed, no more AUTH commands may be issued in the same session."
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_is_authenticated_transitions() {
    let conn = SmtpConnection::connect(mailpit::HOST, mailpit::SMTP_PORT, TlsMode::None, TIMEOUT)
        .await
        .unwrap();

    assert!(
        !conn.is_authenticated().await,
        "must not be authenticated before AUTH"
    );

    conn.auth_plain(mailpit::USER, mailpit::PASS, TIMEOUT)
        .await
        .unwrap();

    assert!(
        conn.is_authenticated().await,
        "must be authenticated after successful AUTH PLAIN"
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// HELP command (RFC 5321 Section 4.1.1.8)
// ==========================================================================

/// HELP must return a valid SMTP response — either help text (211/214)
/// or "not implemented" (502).
///
/// RFC 5321 Section 4.1.1.8: "This command causes the server to send
/// helpful information to the client."
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_help_command() {
    let conn = connect_mailpit().await;

    let resp = conn.help(None, TIMEOUT).await.unwrap();

    // RFC 5321 Section 4.1.1.8: valid response codes are 211, 214, or 502.
    assert!(
        resp.code == 211 || resp.code == 214 || resp.code == 502,
        "HELP must return 211, 214, or 502; got {}",
        resp.code
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// VRFY command (RFC 5321 Section 4.1.1.6)
// ==========================================================================

/// VRFY must return a valid response — verified (250/251/252),
/// not implemented (502), or not found (550/553).
///
/// RFC 5321 Section 3.5.3 permits servers to disable VRFY with a 502
/// response, so both "verified" and "not implemented" are acceptable.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_vrfy_command() {
    let conn = connect_mailpit().await;

    let resp = conn.vrfy("testuser", TIMEOUT).await.unwrap();

    // RFC 5321 Section 4.1.1.6 / Section 3.5.3: valid responses.
    assert!(
        [250, 251, 252, 502, 550, 553].contains(&resp.code),
        "VRFY must return 250/251/252/502/550/553; got {}",
        resp.code
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// REHLO — capability refresh (RFC 5321 Section 4.1.1.1)
// ==========================================================================

/// `rehlo()` re-issues EHLO and refreshes the capability snapshot.
///
/// RFC 5321 Section 4.1.1.1: "An EHLO command MAY be issued by a
/// client later in the session."
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_rehlo_refreshes_capabilities() {
    let conn = connect_mailpit().await;

    let caps_before = conn.capabilities().await;

    // Re-issue EHLO.
    conn.rehlo(TIMEOUT).await.unwrap();

    // Capabilities must still be populated after REHLO.
    let caps_after = conn.capabilities().await;
    assert!(
        !caps_after.greeting_name().is_empty(),
        "greeting name must remain present after REHLO"
    );
    assert_eq!(
        caps_before.greeting_name(),
        caps_after.greeting_name(),
        "greeting name should be consistent across EHLO exchanges"
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// AUTH LOGIN (draft-murchison-sasl-login)
// ==========================================================================

/// AUTH LOGIN succeeds against `GreenMail`.
///
/// AUTH LOGIN uses a two-step challenge-response: the server challenges
/// for the username, then the password, each base64-encoded.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_auth_login() {
    let conn = SmtpConnection::connect(
        greenmail::HOST,
        greenmail::SMTP_PORT,
        TlsMode::None,
        TIMEOUT,
    )
    .await
    .unwrap();

    // GreenMail should advertise AUTH LOGIN.
    let caps = conn.capabilities().await;
    if !caps.supports_auth(&AuthMechanism::Login) {
        eprintln!("skipping: GreenMail does not advertise AUTH LOGIN");
        conn.quit(TIMEOUT).await.unwrap();
        return;
    }

    conn.auth_login(greenmail::USER, greenmail::PASS, TIMEOUT)
        .await
        .unwrap();

    assert!(
        conn.is_authenticated().await,
        "must be authenticated after AUTH LOGIN"
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Invalid credentials (RFC 4954 Section 4)
// ==========================================================================

/// AUTH PLAIN with wrong password must fail with `Error::Auth`.
///
/// RFC 4954 Section 4: "If the requested authentication identity is
/// unknown or the supplied credentials are invalid [...] a 535 reply
/// code SHOULD be used."
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_invalid_credentials_rejected() {
    let conn = SmtpConnection::connect(
        greenmail::HOST,
        greenmail::SMTP_PORT,
        TlsMode::None,
        TIMEOUT,
    )
    .await
    .unwrap();

    let result = conn
        .auth_plain(greenmail::USER, "wrong-password", TIMEOUT)
        .await;

    assert!(
        matches!(result, Err(Error::Auth { .. })),
        "bad credentials must produce Error::Auth, got {result:?}"
    );

    // Connection may still be usable after failed auth (RFC 4954 Section 6).
    let _ = conn.quit(TIMEOUT).await;
}

// ==========================================================================
// SendResult inspection (RFC 5321 Section 3.3)
// ==========================================================================

/// After a successful send to a valid recipient, `SendResult::all_accepted()`
/// must return `true` and `has_rejections()` must return `false`.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_send_result_all_accepted() {
    let conn = connect_mailpit().await;

    let msg = test_message("mailpit-sendresult");
    let result = conn
        .send(
            &ReversePath::new("sender@example.com").unwrap(),
            &[ForwardPath::new("recipient@example.com").unwrap()],
            &msg,
            TIMEOUT,
        )
        .await
        .unwrap();

    assert!(
        result.all_accepted(),
        "all recipients must be accepted; rejections: {:?}",
        result.rejected_recipients
    );
    assert!(
        !result.has_rejections(),
        "must have no rejections for a valid recipient"
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Null reverse path — bounce/DSN messages (RFC 5321 Section 4.1.1.2)
// ==========================================================================

/// Sending with a null reverse path (MAIL FROM:<>) is valid for bounce
/// messages and delivery status notifications.
///
/// RFC 5321 Section 4.1.1.2: "The special case of 'MAIL FROM:<>'
/// indicates the envelope sender is a null address."
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_send_null_reverse_path() {
    let conn = connect_mailpit().await;

    let null_sender = ReversePath::new("").unwrap();

    let msg = test_message("mailpit-null-sender");
    let result = conn
        .send(
            &null_sender,
            &[ForwardPath::new("recipient@example.com").unwrap()],
            &msg,
            TIMEOUT,
        )
        .await
        .unwrap();

    assert!(
        result.all_accepted(),
        "null reverse-path send must be accepted; rejections: {:?}",
        result.rejected_recipients
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Large message (RFC 5321 Section 4.5.3.1.8)
// ==========================================================================

/// Send a ~100 KB message to verify large-message handling.
///
/// RFC 5321 Section 4.5.3.1.8: "The minimum maximum message size that
/// a server must be able to receive is 64K octets."  Mailpit has no
/// realistic size limit, so a 100 KB message should succeed.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_send_large_message() {
    let conn = connect_mailpit().await;

    // Build a ~100 KB message.
    let body_line =
        "This is a line of text for the large message test. ABCDEFGHIJKLMNOPQRSTUVWXYZ\r\n";
    let body = body_line.repeat(1300); // ~100 KB
    let msg = format!(
        "From: sender@example.com\r\n\
         To: recipient@example.com\r\n\
         Subject: large message test\r\n\
         Date: Sun, 15 Mar 2026 00:00:00 +0000\r\n\
         Message-ID: <large@daaki>\r\n\
         MIME-Version: 1.0\r\n\
         Content-Type: text/plain; charset=utf-8\r\n\
         \r\n\
         {body}"
    );

    let result = conn
        .send(
            &ReversePath::new("sender@example.com").unwrap(),
            &[ForwardPath::new("recipient@example.com").unwrap()],
            msg.as_bytes(),
            TIMEOUT,
        )
        .await
        .unwrap();

    assert!(
        result.all_accepted(),
        "large message send must be accepted; rejections: {:?}",
        result.rejected_recipients
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Multiple sends without RSET (RFC 5321 Section 3.3)
// ==========================================================================

/// The server must accept multiple MAIL/RCPT/DATA sequences on the same
/// connection without an explicit RSET between them.
///
/// RFC 5321 Section 3.3: after a successful DATA, the server resets
/// the mail transaction state automatically.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_multiple_sends_same_connection() {
    let conn = connect_mailpit().await;

    for i in 1..=3 {
        let msg = test_message(&format!("mailpit-multi-send-{i}"));
        let result = conn
            .send(
                &ReversePath::new("sender@example.com").unwrap(),
                &[ForwardPath::new("recipient@example.com").unwrap()],
                &msg,
                TIMEOUT,
            )
            .await
            .unwrap();

        assert!(
            result.all_accepted(),
            "send {i}/3 must be accepted; rejections: {:?}",
            result.rejected_recipients
        );
    }

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// STARTTLS upgrade (RFC 3207)
// ==========================================================================

/// Connect to `GreenMail` in cleartext and attempt STARTTLS upgrade.
///
/// RFC 3207 Section 4: after a successful STARTTLS, the connection
/// is upgraded and a fresh EHLO exchange occurs. If the server does
/// not advertise STARTTLS, the connection fails with
/// `Error::StartTlsUnavailable` — this is the expected behavior per
/// RFC 3207 Section 3.1.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_starttls_upgrade() {
    let tls_config = build_danger_tls_config();
    let result = SmtpConnection::connect_with_tls_config(
        greenmail::HOST,
        greenmail::SMTP_PORT,
        TlsMode::StartTls,
        TIMEOUT,
        tls_config,
    )
    .await;

    match result {
        Ok(conn) => {
            // STARTTLS succeeded — verify capabilities and auth.
            let caps = conn.capabilities().await;
            assert!(
                !caps.greeting_name().is_empty(),
                "greeting name must be present after STARTTLS EHLO"
            );
            conn.auth_plain(greenmail::USER, greenmail::PASS, TIMEOUT)
                .await
                .unwrap();
            conn.quit(TIMEOUT).await.unwrap();
        }
        Err(Error::StartTlsUnavailable) => {
            // GreenMail does not advertise STARTTLS on its plaintext
            // port — this is expected. The library correctly refuses
            // to upgrade when the extension is absent.
            eprintln!("skipping: GreenMail plaintext port does not advertise STARTTLS");
        }
        Err(e) => panic!("unexpected error: {e:?}"),
    }
}

// ==========================================================================
// EXPN — mailing list expansion (RFC 5321 Section 4.1.1.7)
// ==========================================================================

/// EXPN must return a valid SMTP response — expanded list (250),
/// not implemented (502), or not found (550).
///
/// RFC 5321 Section 4.1.1.7 / Section 3.5.3: servers MAY disable
/// EXPN with a 502 response.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_expn_command() {
    let conn = connect_mailpit().await;

    let resp = conn.expn("testlist", TIMEOUT).await.unwrap();

    // RFC 5321 Section 4.1.1.7 / Section 3.5.3: valid responses.
    assert!(
        [250, 502, 550].contains(&resp.code),
        "EXPN must return 250/502/550; got {}",
        resp.code
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// HELP with topic (RFC 5321 Section 4.1.1.8)
// ==========================================================================

/// HELP with a specific topic argument must return a valid SMTP response.
///
/// RFC 5321 Section 4.1.1.8: "HELP" [ SP String ] CRLF — the optional
/// argument requests topic-specific help text.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_help_with_topic() {
    let conn = connect_mailpit().await;

    let resp = conn.help(Some("MAIL"), TIMEOUT).await.unwrap();

    // RFC 5321 Section 4.1.1.8: valid response codes are 211, 214, or 502.
    assert!(
        resp.code == 211 || resp.code == 214 || resp.code == 502,
        "HELP MAIL must return 211, 214, or 502; got {}",
        resp.code
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// EHLO domain configuration (RFC 5321 Section 4.1.1.1)
// ==========================================================================

/// `set_ehlo_domain` followed by `rehlo` must send the new domain to the
/// server and refresh capabilities.
///
/// RFC 5321 Section 4.1.1.1: "An EHLO command MAY be issued by a client
/// later in the session" — this tests the domain-change + refresh path.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_set_ehlo_domain_and_rehlo() {
    let conn = SmtpConnection::connect(mailpit::HOST, mailpit::SMTP_PORT, TlsMode::None, TIMEOUT)
        .await
        .unwrap();

    // Set a custom EHLO domain.
    conn.set_ehlo_domain("test.example.com").await.unwrap();

    // Re-issue EHLO with the new domain.
    conn.rehlo(TIMEOUT).await.unwrap();

    // Capabilities must still be populated after REHLO with new domain.
    let caps = conn.capabilities().await;
    assert!(
        !caps.greeting_name().is_empty(),
        "greeting name must be present after REHLO with new domain"
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// is_shutting_down accessor (RFC 5321 Section 3.8)
// ==========================================================================

/// `is_shutting_down()` must return `false` on a healthy connection that
/// has not received a 421 response.
///
/// RFC 5321 Section 3.8: the server sends 421 to signal channel shutdown.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_is_shutting_down_false() {
    let conn = connect_mailpit().await;

    assert!(
        !conn.is_shutting_down().await,
        "healthy connection must not report shutting down"
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Capability introspection — pipelining (RFC 1854)
// ==========================================================================

/// Verify detailed capability inspection after EHLO — pipelining, SIZE,
/// and 8BITMIME are commonly advertised.
///
/// RFC 5321 Section 4.1.1.1: the server advertises extensions as EHLO
/// keyword lines following the greeting name.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_capabilities_size_and_8bitmime() {
    let conn = SmtpConnection::connect(mailpit::HOST, mailpit::SMTP_PORT, TlsMode::None, TIMEOUT)
        .await
        .unwrap();

    let caps = conn.capabilities().await;

    // SIZE extension (RFC 1870) should be advertised.
    assert!(
        caps.supports_size(),
        "Mailpit must advertise the SIZE extension (RFC 1870)"
    );

    // 8BITMIME (RFC 6152) should be advertised.
    assert!(
        caps.supports_8bitmime(),
        "Mailpit must advertise 8BITMIME (RFC 6152)"
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Capability introspection — GreenMail extensions
// ==========================================================================

/// Inspect `GreenMail`'s capabilities on the plaintext port.
///
/// RFC 5321 Section 4.1.1.1: verify that AUTH and 8BITMIME are
/// advertised by `GreenMail`.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_capabilities_inspection() {
    let conn = SmtpConnection::connect(
        greenmail::HOST,
        greenmail::SMTP_PORT,
        TlsMode::None,
        TIMEOUT,
    )
    .await
    .unwrap();

    let caps = conn.capabilities().await;

    // GreenMail should advertise AUTH.
    assert!(
        caps.supports_auth_extension(),
        "GreenMail must advertise AUTH (RFC 4954)"
    );

    // GreenMail typically supports AUTH PLAIN.
    assert!(
        caps.supports_auth(&AuthMechanism::Plain),
        "GreenMail must advertise AUTH PLAIN"
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Send over implicit TLS (RFC 8314 Section 3)
// ==========================================================================

/// Send a message through `GreenMail` over implicit TLS (SMTPS).
///
/// RFC 8314 Section 3: implicit TLS wraps the connection from the start.
/// This verifies the full send path works over TLS, not just plaintext.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_send_over_implicit_tls() {
    let tls_config = build_danger_tls_config();
    let conn = SmtpConnection::connect_with_tls_config(
        greenmail::HOST,
        greenmail::SMTPS_PORT,
        TlsMode::Implicit,
        TIMEOUT,
        tls_config,
    )
    .await
    .unwrap();

    conn.auth_plain(greenmail::USER, greenmail::PASS, TIMEOUT)
        .await
        .unwrap();

    let msg = test_message("greenmail-implicit-tls");
    let result = conn
        .send(
            &ReversePath::new("sender@example.com").unwrap(),
            &[ForwardPath::new("recipient@example.com").unwrap()],
            &msg,
            TIMEOUT,
        )
        .await
        .unwrap();

    assert!(
        result.all_accepted(),
        "send over implicit TLS must accept all recipients; rejections: {:?}",
        result.rejected_recipients
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// BDAT chunking (RFC 3030 Section 3)
// ==========================================================================

/// Send a message via BDAT/CHUNKING if the server supports it.
///
/// RFC 3030 Section 3: BDAT replaces DATA, avoids dot-stuffing, and
/// supports binary content. The CHUNKING extension must be advertised.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_send_bdat_if_chunking_supported() {
    let conn = connect_greenmail().await;

    let caps = conn.capabilities().await;
    if !caps.supports_chunking() {
        eprintln!("skipping: GreenMail does not advertise CHUNKING");
        conn.quit(TIMEOUT).await.unwrap();
        return;
    }

    let msg = test_message("greenmail-bdat");
    let result = conn
        .send_bdat(
            &ReversePath::new("sender@example.com").unwrap(),
            &[ForwardPath::new("recipient@example.com").unwrap()],
            &msg,
            None,
            TIMEOUT,
        )
        .await
        .unwrap();

    assert!(
        result.all_accepted(),
        "BDAT send must accept all recipients; rejections: {:?}",
        result.rejected_recipients
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// send_with_params — BODY=8BITMIME (RFC 1652 Section 3)
// ==========================================================================

/// Send a message with explicit BODY=8BITMIME MAIL FROM parameter.
///
/// RFC 1652 Section 3: the client declares the body type via the
/// BODY parameter on MAIL FROM. When the server advertises 8BITMIME,
/// this should succeed.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_send_with_body_8bitmime_param() {
    let conn = connect_mailpit().await;

    let caps = conn.capabilities().await;
    if !caps.supports_8bitmime() {
        eprintln!("skipping: Mailpit does not advertise 8BITMIME");
        conn.quit(TIMEOUT).await.unwrap();
        return;
    }

    let mut params = MailFromParams::default();
    params.body = Some(BodyType::EightBitMime);

    let msg = "From: sender@example.com\r\n\
               To: recipient@example.com\r\n\
               Subject: 8BITMIME param test\r\n\
               Date: Sun, 15 Mar 2026 00:00:00 +0000\r\n\
               Message-ID: <body-param@daaki>\r\n\
               MIME-Version: 1.0\r\n\
               Content-Type: text/plain; charset=utf-8\r\n\
               Content-Transfer-Encoding: 8bit\r\n\
               \r\n\
               Héllo wörld — explicit BODY=8BITMIME.\r\n";

    let result = conn
        .send_with_params(
            &ReversePath::new("sender@example.com").unwrap(),
            &[ForwardPath::new("recipient@example.com").unwrap()],
            msg.as_bytes(),
            Some(&params),
            TIMEOUT,
        )
        .await
        .unwrap();

    assert!(
        result.all_accepted(),
        "send_with_params(BODY=8BITMIME) must accept; rejections: {:?}",
        result.rejected_recipients
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Error classification (RFC 5321 Section 4.2.1)
// ==========================================================================

/// `Error::is_permanent()` must be true for permanent auth failures (535).
///
/// RFC 4954 Section 4: "If the requested authentication identity is
/// unknown or the supplied credentials are invalid [...] a 535 reply
/// code SHOULD be used."
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_auth_error_is_permanent() {
    let conn = SmtpConnection::connect(
        greenmail::HOST,
        greenmail::SMTP_PORT,
        TlsMode::None,
        TIMEOUT,
    )
    .await
    .unwrap();

    let result = conn
        .auth_plain(greenmail::USER, "wrong-password", TIMEOUT)
        .await;

    match result {
        Err(ref e) => {
            assert!(
                e.is_permanent(),
                "bad-credentials error must be permanent (535); got {e:?}"
            );
            assert!(
                !e.is_transient(),
                "bad-credentials error must not be transient; got {e:?}"
            );
        }
        Ok(()) => panic!("auth with bad password should fail"),
    }

    let _ = conn.quit(TIMEOUT).await;
}

// ==========================================================================
// Multiple NOOPs (RFC 5321 Section 4.1.1.9)
// ==========================================================================

/// Multiple NOOP commands in sequence must all succeed without
/// affecting session state.
///
/// RFC 5321 Section 4.1.1.9: "This command does not affect any
/// parameters or previously entered commands."
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_multiple_noops() {
    let conn = connect_mailpit().await;

    for _ in 0..5 {
        conn.noop(TIMEOUT).await.unwrap();
    }

    // Session must still be usable after multiple NOOPs.
    let msg = test_message("mailpit-multi-noop");
    conn.send(
        &ReversePath::new("sender@example.com").unwrap(),
        &[ForwardPath::new("recipient@example.com").unwrap()],
        &msg,
        TIMEOUT,
    )
    .await
    .unwrap();

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// GreenMail multiple sends on same connection (RFC 5321 Section 3.3)
// ==========================================================================

/// Multiple MAIL/RCPT/DATA sequences on the same `GreenMail` connection must
/// succeed, verifying state reset after each DATA completion.
///
/// RFC 5321 Section 3.3: after a successful DATA, the server resets the
/// mail transaction state automatically.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_multiple_sends_same_connection() {
    let conn = connect_greenmail().await;

    for i in 1..=3 {
        let msg = test_message(&format!("greenmail-multi-send-{i}"));
        let result = conn
            .send(
                &ReversePath::new("sender@example.com").unwrap(),
                &[ForwardPath::new("recipient@example.com").unwrap()],
                &msg,
                TIMEOUT,
            )
            .await
            .unwrap();

        assert!(
            result.all_accepted(),
            "GreenMail send {i}/3 must be accepted; rejections: {:?}",
            result.rejected_recipients
        );
    }

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Connection usable after failed auth (RFC 4954 Section 6)
// ==========================================================================

/// After a failed AUTH attempt the session must remain usable — the client
/// can retry with correct credentials.
///
/// RFC 4954 Section 6: "The SMTP client may try another authentication
/// mechanism or provide corrected credentials by issuing another AUTH
/// command."
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_retry_auth_after_failure() {
    let conn = SmtpConnection::connect(
        greenmail::HOST,
        greenmail::SMTP_PORT,
        TlsMode::None,
        TIMEOUT,
    )
    .await
    .unwrap();

    // First attempt with wrong password.
    let bad_result = conn
        .auth_plain(greenmail::USER, "wrong-password", TIMEOUT)
        .await;
    assert!(bad_result.is_err(), "auth with wrong password must fail");
    assert!(
        !conn.is_authenticated().await,
        "must not be authenticated after failed auth"
    );

    // Retry with correct credentials on the same connection.
    conn.auth_plain(greenmail::USER, greenmail::PASS, TIMEOUT)
        .await
        .unwrap();
    assert!(
        conn.is_authenticated().await,
        "must be authenticated after successful retry"
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// send_with_all_params (RFC 5321 Section 3.3, RFC 3461)
// ==========================================================================

/// `send_with_all_params` rejects mismatched `rcpt_params` length.
///
/// RFC 3461 Sections 4.1-4.2: each recipient must have a corresponding
/// `RcptToParams` entry. Passing an empty slice when there are recipients
/// must return a protocol error.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_send_with_all_params_rejects_length_mismatch() {
    use daaki_smtp::RcptToParams;

    let conn = connect_greenmail().await;

    let from = ReversePath::new("sender@example.com").unwrap();
    let to = vec![ForwardPath::new("recipient@example.com").unwrap()];
    let msg = test_message("all-params-mismatch");

    // Empty rcpt_params with 1 recipient → protocol error.
    let result = conn
        .send_with_all_params(&from, &to, &msg, None, &[], TIMEOUT)
        .await;

    assert!(
        result.is_err(),
        "send_with_all_params must reject length mismatch (0 params, 1 recipient)"
    );

    // Matching length with default params should succeed.
    let rcpt_params = vec![RcptToParams::default()];
    let msg2 = test_message("all-params-default-rcpt");
    let result2 = conn
        .send_with_all_params(&from, &to, &msg2, None, &rcpt_params, TIMEOUT)
        .await
        .unwrap();

    assert!(
        result2.all_accepted(),
        "send with matching default RcptToParams should succeed"
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// auth_plain_with_authzid (RFC 4616 Section 2)
// ==========================================================================

/// Authenticate with an explicit authorization identity equal to the user.
///
/// RFC 4616 Section 2: the PLAIN SASL mechanism encodes
/// `[authzid] NUL authcid NUL passwd`. When authzid equals authcid the
/// server should treat it the same as omitting authzid.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_auth_plain_with_authzid_same_as_user() {
    let conn = SmtpConnection::connect(
        greenmail::HOST,
        greenmail::SMTP_PORT,
        TlsMode::None,
        TIMEOUT,
    )
    .await
    .unwrap();

    // authzid == authcid should be accepted.
    conn.auth_plain_with_authzid(greenmail::USER, greenmail::USER, greenmail::PASS, TIMEOUT)
        .await
        .unwrap();

    assert!(
        conn.is_authenticated().await,
        "auth_plain_with_authzid should authenticate successfully"
    );

    // Verify connection is usable post-auth.
    let from = ReversePath::new("sender@example.com").unwrap();
    let to = vec![ForwardPath::new("recipient@example.com").unwrap()];
    let msg = test_message("authzid-send");
    let result = conn.send(&from, &to, &msg, TIMEOUT).await.unwrap();
    assert!(result.all_accepted());

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// ForwardPath::Postmaster (RFC 5321 Section 4.1.1.3)
// ==========================================================================

/// Send to the POSTMASTER address.
///
/// RFC 5321 Section 4.1.1.3: "RCPT TO:<Postmaster>" (without a domain)
/// MUST be accepted by every SMTP server. However, test servers may not
/// deliver to it — we only verify the RCPT TO is accepted.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_send_to_postmaster() {
    let conn = connect_greenmail().await;

    let from = ReversePath::new("sender@example.com").unwrap();
    let to = vec![ForwardPath::Postmaster];
    let msg = test_message("postmaster-send");

    let result = conn.send(&from, &to, &msg, TIMEOUT).await;

    // RFC 5321 requires Postmaster to be accepted, but test servers
    // may reject it. We accept server-level rejections (5xx/4xx) but
    // NOT library-internal errors (Io, Parse, Protocol, Closed), which
    // would indicate a bug in ForwardPath::Postmaster serialization.
    match result {
        Ok(send_result) => {
            assert!(
                send_result.all_accepted(),
                "Postmaster should be accepted if the server handles it"
            );
        }
        Err(
            Error::Permanent { .. } | Error::Transient { .. } | Error::AllRecipientsFailed { .. },
        ) => {
            // Server-level rejection — acceptable for a test server.
        }
        Err(e) => {
            panic!("unexpected error sending to Postmaster (library bug?): {e:?}");
        }
    }

    let _ = conn.quit(TIMEOUT).await;
}

// ==========================================================================
// Send after QUIT (RFC 5321 Section 4.1.1.10)
// ==========================================================================

/// Sending after QUIT must fail.
///
/// RFC 5321 Section 4.1.1.10: after QUIT the server closes the connection.
/// Any subsequent MAIL FROM must fail with a connection-level error.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_send_after_quit_fails() {
    let conn = connect_greenmail().await;

    conn.quit(TIMEOUT).await.unwrap();

    let from = ReversePath::new("sender@example.com").unwrap();
    let to = vec![ForwardPath::new("recipient@example.com").unwrap()];
    let msg = test_message("after-quit");

    let result = conn.send(&from, &to, &msg, TIMEOUT).await;
    assert!(
        result.is_err(),
        "send after QUIT must fail — server closed the connection (RFC 5321 Section 4.1.1.10)"
    );
}

// ==========================================================================
// MailFromParams with SIZE (RFC 1870 Section 3)
// ==========================================================================

/// Send with the SIZE MAIL FROM parameter.
///
/// RFC 1870 Section 3: when the server advertises SIZE, the client MAY
/// include a SIZE parameter on MAIL FROM indicating the message size.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_send_with_size_param() {
    let conn = connect_greenmail().await;

    let caps = conn.capabilities().await;
    if !caps.supports_size() {
        eprintln!("skipping: GreenMail does not advertise SIZE");
        conn.quit(TIMEOUT).await.unwrap();
        return;
    }

    let from = ReversePath::new("sender@example.com").unwrap();
    let to = vec![ForwardPath::new("recipient@example.com").unwrap()];
    let msg = test_message("size-param");

    let mut params = MailFromParams::default();
    params.size = Some(msg.len() as u64);

    let result = conn
        .send_with_params(&from, &to, &msg, Some(&params), TIMEOUT)
        .await
        .unwrap();

    assert!(
        result.all_accepted(),
        "send with SIZE param should succeed when server advertises SIZE"
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Custom EHLO domain then send (RFC 5321 Section 4.1.1.1)
// ==========================================================================

/// Set a custom EHLO domain and verify the connection remains usable.
///
/// RFC 5321 Section 4.1.1.1: the client identifies itself with a domain
/// in the EHLO command. After `set_ehlo_domain` + `rehlo`, the session
/// state should be refreshed and sending should work.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_custom_ehlo_domain_and_send() {
    let conn = connect_greenmail().await;

    conn.set_ehlo_domain("custom-test.example.com")
        .await
        .unwrap();
    conn.rehlo(TIMEOUT).await.unwrap();

    // Verify EHLO succeeded: the server's greeting name (from the EHLO
    // response) must be non-empty after the capability refresh.
    let caps = conn.capabilities().await;
    assert!(
        !caps.greeting_name().is_empty(),
        "rehlo must succeed and produce a non-empty server greeting"
    );

    // Sending should work with the new EHLO domain.
    let from = ReversePath::new("sender@example.com").unwrap();
    let to = vec![ForwardPath::new("recipient@example.com").unwrap()];
    let msg = test_message("custom-ehlo-send");
    let result = conn.send(&from, &to, &msg, TIMEOUT).await.unwrap();
    assert!(result.all_accepted());

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// NOOP before authentication (RFC 5321 Section 4.1.1.9)
// ==========================================================================

/// NOOP works before authentication.
///
/// RFC 5321 Section 4.1.1.9: NOOP does not affect any state and is valid
/// at any point in the session.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_noop_before_auth() {
    let conn = SmtpConnection::connect(
        greenmail::HOST,
        greenmail::SMTP_PORT,
        TlsMode::None,
        TIMEOUT,
    )
    .await
    .unwrap();

    // NOOP before auth should succeed.
    conn.noop(TIMEOUT).await.unwrap();

    assert!(
        !conn.is_authenticated().await,
        "NOOP should not change authentication state"
    );

    // Connection should still be usable — authenticate and send.
    conn.auth_plain(greenmail::USER, greenmail::PASS, TIMEOUT)
        .await
        .unwrap();

    let from = ReversePath::new("sender@example.com").unwrap();
    let to = vec![ForwardPath::new("recipient@example.com").unwrap()];
    let msg = test_message("noop-before-auth");
    let result = conn.send(&from, &to, &msg, TIMEOUT).await.unwrap();
    assert!(result.all_accepted());

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Multiple send-reset cycles (RFC 5321 Section 4.1.1.5)
// ==========================================================================

/// Multiple explicit RSET cycles on the same connection.
///
/// RFC 5321 Section 4.1.1.5: RSET aborts the current mail transaction and
/// resets the session to post-EHLO state. The connection should handle
/// many RSET-send pairs without degradation.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_multiple_reset_send_cycles() {
    let conn = connect_greenmail().await;

    let from = ReversePath::new("sender@example.com").unwrap();
    let to = vec![ForwardPath::new("recipient@example.com").unwrap()];

    for i in 0..5 {
        // Explicit RSET between sends.
        conn.reset(TIMEOUT).await.unwrap();

        let msg = test_message(&format!("reset-cycle-{i}"));
        let result = conn.send(&from, &to, &msg, TIMEOUT).await.unwrap();
        assert!(
            result.all_accepted(),
            "send in cycle {i} should succeed after RSET"
        );
    }

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// BDAT with per-recipient params (RFC 3030 Section 3, RFC 3461)
// ==========================================================================

/// `send_bdat_with_all_params` sends via BDAT/CHUNKING with per-recipient
/// DSN parameters. When the server doesn't support CHUNKING, the method
/// should fall back to DATA or return an error — either way the code path
/// is exercised.
///
/// RFC 3030 Section 3: BDAT replaces the DATA command when CHUNKING is
/// advertised. RFC 3461: DSN RCPT parameters (NOTIFY, ORCPT).
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_send_bdat_with_all_params_default() {
    use daaki_smtp::RcptToParams;

    let conn = connect_greenmail().await;

    let caps = conn.capabilities().await;
    if !caps.supports_chunking() {
        // GreenMail may not support CHUNKING — skip gracefully.
        conn.quit(TIMEOUT).await.unwrap();
        return;
    }

    let from = ReversePath::new("sender@example.com").unwrap();
    let to = vec![ForwardPath::new("recipient@example.com").unwrap()];
    let rcpt_params = vec![RcptToParams::default()];
    let msg = test_message("bdat-all-params");

    let result = conn
        .send_bdat_with_all_params(&from, &to, &msg, None, &rcpt_params, TIMEOUT)
        .await
        .unwrap();

    assert!(
        result.all_accepted(),
        "BDAT with default RcptToParams should succeed"
    );
    assert!(
        !result.has_rejections(),
        "BDAT with default RcptToParams should have no rejections"
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// send_with_params — BODY=8BITMIME + SIZE (RFC 1652, RFC 1870)
// ==========================================================================

/// `send_with_params` with explicit BODY=8BITMIME and SIZE parameters
/// verifies that the client correctly encodes these MAIL FROM extensions.
///
/// RFC 1652 Section 3: BODY=8BITMIME indicates 8-bit content.
/// RFC 1870 Section 3: SIZE= declares the message size.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_send_with_params_body_and_size() {
    let conn = connect_mailpit().await;

    let msg = test_message("params-body-size");
    let mut params = MailFromParams::default();
    params.body = Some(BodyType::EightBitMime);
    params.size = Some(msg.len() as u64);

    let result = conn
        .send_with_params(
            &ReversePath::new("sender@example.com").unwrap(),
            &[ForwardPath::new("recipient@example.com").unwrap()],
            &msg,
            Some(&params),
            TIMEOUT,
        )
        .await
        .unwrap();

    assert!(
        result.all_accepted(),
        "send with BODY + SIZE params should succeed"
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// ServerCapabilities supports_*() methods (RFC 5321 Section 4.1.1.1)
// ==========================================================================

/// Verify that `ServerCapabilities` supports_*() methods correctly
/// reflect the server's EHLO response.
///
/// RFC 5321 Section 4.1.1.1: The EHLO response lists the extensions
/// the server supports. This test exercises the capability introspection
/// methods against Mailpit's known extension set.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn mailpit_capability_supports_methods() {
    let conn = connect_mailpit().await;
    let caps = conn.capabilities().await;

    // Mailpit should have a non-empty greeting name.
    assert!(
        !caps.greeting_name().is_empty(),
        "greeting name from EHLO should be non-empty"
    );

    // Mailpit's extension list should not be empty.
    assert!(
        !caps.extensions().is_empty(),
        "EHLO should advertise at least one extension"
    );

    // Verify boolean methods are consistent with extensions list.
    // PIPELINING is commonly supported.
    if caps.supports_pipelining() {
        assert!(
            caps.extensions()
                .iter()
                .any(|e| matches!(e, daaki_smtp::SmtpExtension::Pipelining)),
            "supports_pipelining() true but PIPELINING not in extensions list"
        );
    }

    // If SIZE is advertised, size_limit() should return Some or the server
    // advertises SIZE with no limit (0 means no declared limit).
    if caps.supports_size() {
        // size_limit() returns None only when SIZE is not advertised at all.
        // When SIZE is advertised with 0 or no parameter, it means "no limit"
        // but supports_size() is still true.
        assert!(
            caps.extensions()
                .iter()
                .any(|e| matches!(e, daaki_smtp::SmtpExtension::Size(_))),
            "supports_size() true but SIZE not in extensions list"
        );
    }

    // AUTH should be supported (we authenticated successfully).
    assert!(
        caps.supports_auth_extension(),
        "AUTH extension should be advertised (we authenticated)"
    );
    assert!(
        caps.supports_auth(&AuthMechanism::Plain),
        "AUTH PLAIN should be supported (we used it to authenticate)"
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// AUTH LOGIN followed by send (draft-murchison-sasl-login, RFC 5321)
// ==========================================================================

/// AUTH LOGIN followed by a complete MAIL/RCPT/DATA send cycle verifies
/// that the session is fully usable after LOGIN authentication.
///
/// The existing `greenmail_auth_login` test only verifies authentication
/// succeeds. This test verifies the full workflow: LOGIN → send → quit.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_auth_login_then_send() {
    let conn = SmtpConnection::connect(
        greenmail::HOST,
        greenmail::SMTP_PORT,
        TlsMode::None,
        TIMEOUT,
    )
    .await
    .unwrap();

    conn.auth_login(greenmail::USER, greenmail::PASS, TIMEOUT)
        .await
        .unwrap();

    assert!(
        conn.is_authenticated().await,
        "should be authenticated after AUTH LOGIN"
    );

    // Send a message to verify the session is fully usable.
    let msg = test_message("login-then-send");
    let result = conn
        .send(
            &ReversePath::new("sender@example.com").unwrap(),
            &[ForwardPath::new("recipient@example.com").unwrap()],
            &msg,
            TIMEOUT,
        )
        .await
        .unwrap();
    assert!(
        result.all_accepted(),
        "send after AUTH LOGIN should succeed"
    );

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// send_with_all_params — DSN parameters (RFC 3461 Section 4)
// ==========================================================================

/// `send_with_all_params` with actual DSN RCPT parameters (NOTIFY=SUCCESS).
///
/// RFC 3461 Section 4.1: NOTIFY specifies under which conditions a DSN
/// should be generated. The server may or may not support DSN — this test
/// exercises the parameter encoding path regardless.
#[tokio::test]
#[ignore = "requires Docker: docker compose up -d"]
async fn greenmail_send_with_dsn_notify_param() {
    use daaki_smtp::{DsnNotify, RcptToParams};

    let conn = connect_greenmail().await;

    let caps = conn.capabilities().await;

    let from = ReversePath::new("sender@example.com").unwrap();
    let to = vec![ForwardPath::new("recipient@example.com").unwrap()];
    let msg = test_message("dsn-notify");

    // Build RcptToParams with NOTIFY=SUCCESS,FAILURE.
    let mut rtp = RcptToParams::default();
    rtp.notify = Some(vec![DsnNotify::Success, DsnNotify::Failure]);
    let rcpt_params = vec![rtp];

    let result = conn
        .send_with_all_params(&from, &to, &msg, None, &rcpt_params, TIMEOUT)
        .await;

    if caps.supports_dsn() {
        // Server supports DSN — the send should succeed.
        let send_result =
            result.expect("send with DSN params should succeed when DSN is supported");
        assert!(
            send_result.all_accepted(),
            "send with DSN NOTIFY should succeed"
        );
    } else {
        // Server doesn't support DSN — the server may reject the NOTIFY
        // parameter or ignore it. Either way is valid per RFC 5321
        // Section 4.1.1.2 (unrecognized params).
        if let Ok(send_result) = result {
            assert!(
                send_result.all_accepted(),
                "server accepted DSN params despite not advertising DSN"
            );
        }
    }

    conn.quit(TIMEOUT).await.unwrap();
}

// ==========================================================================
// Helpers
// ==========================================================================

/// Connect and authenticate against Mailpit.
async fn connect_mailpit() -> SmtpConnection {
    let conn = SmtpConnection::connect(mailpit::HOST, mailpit::SMTP_PORT, TlsMode::None, TIMEOUT)
        .await
        .unwrap();
    conn.auth_plain(mailpit::USER, mailpit::PASS, TIMEOUT)
        .await
        .unwrap();
    conn
}

/// Connect and authenticate against `GreenMail`.
async fn connect_greenmail() -> SmtpConnection {
    let conn = SmtpConnection::connect(
        greenmail::HOST,
        greenmail::SMTP_PORT,
        TlsMode::None,
        TIMEOUT,
    )
    .await
    .unwrap();
    conn.auth_plain(greenmail::USER, greenmail::PASS, TIMEOUT)
        .await
        .unwrap();
    conn
}

/// Build a TLS config that accepts any certificate (for Docker self-signed certs).
fn build_danger_tls_config() -> Arc<rustls::ClientConfig> {
    mod danger {
        #[derive(Debug)]
        pub struct AcceptAll;

        impl rustls::client::danger::ServerCertVerifier for AcceptAll {
            fn verify_server_cert(
                &self,
                _end_entity: &rustls::pki_types::CertificateDer<'_>,
                _intermediates: &[rustls::pki_types::CertificateDer<'_>],
                _server_name: &rustls::pki_types::ServerName<'_>,
                _ocsp_response: &[u8],
                _now: rustls::pki_types::UnixTime,
            ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
                Ok(rustls::client::danger::ServerCertVerified::assertion())
            }

            fn verify_tls12_signature(
                &self,
                _message: &[u8],
                _cert: &rustls::pki_types::CertificateDer<'_>,
                _dss: &rustls::DigitallySignedStruct,
            ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error>
            {
                Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
            }

            fn verify_tls13_signature(
                &self,
                _message: &[u8],
                _cert: &rustls::pki_types::CertificateDer<'_>,
                _dss: &rustls::DigitallySignedStruct,
            ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error>
            {
                Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
            }

            fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
                rustls::crypto::ring::default_provider()
                    .signature_verification_algorithms
                    .supported_schemes()
            }
        }
    }

    let _ = rustls::crypto::ring::default_provider().install_default();

    let config = rustls::ClientConfig::builder()
        .dangerous()
        .with_custom_certificate_verifier(Arc::new(danger::AcceptAll))
        .with_no_client_auth();
    Arc::new(config)
}