daaki-smtp 0.1.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
//! SMTP command encoder.
//!
//! Serializes SMTP commands into bytes for transmission.
//! All commands are terminated with CRLF per RFC 5321.

use bytes::BytesMut;

use crate::types::{BodyType, DeliverByMode, DsnNotify, DsnRet, MailFromParams, RcptToParams};

/// Encode a greeting command (`<cmd> <domain>\r\n`).
///
/// Shared by EHLO (RFC 5321 Section 4.1.1.1), LHLO (RFC 2033 Section 4.2),
/// and HELO (RFC 5321 Section 4.1.1.1).
fn encode_greeting(buf: &mut BytesMut, cmd: &[u8], domain: &str) {
    buf.extend_from_slice(cmd);
    buf.extend_from_slice(domain.as_bytes());
    buf.extend_from_slice(b"\r\n");
}

/// Encode an EHLO command (RFC 5321 Section 4.1.1.1).
pub(crate) fn encode_ehlo(buf: &mut BytesMut, domain: &str) {
    encode_greeting(buf, b"EHLO ", domain);
}

/// Encode an AUTH PLAIN command with credentials (RFC 4954, RFC 4616).
///
/// Format: `AUTH PLAIN <base64(\0user\0pass)>`
///
/// Used in tests to verify line-length thresholds for the SASL-IR
/// one-step vs two-step decision (RFC 4954 Section 4).
#[cfg(test)]
pub(crate) fn encode_auth_plain(buf: &mut BytesMut, user: &str, pass: &str) {
    use base64::Engine;

    let mut credentials = Vec::with_capacity(1 + user.len() + 1 + pass.len());
    credentials.push(0);
    credentials.extend_from_slice(user.as_bytes());
    credentials.push(0);
    credentials.extend_from_slice(pass.as_bytes());

    let encoded = base64::engine::general_purpose::STANDARD.encode(&credentials);

    buf.extend_from_slice(b"AUTH PLAIN ");
    buf.extend_from_slice(encoded.as_bytes());
    buf.extend_from_slice(b"\r\n");
}

/// Encode an AUTH XOAUTH2 command (Google XOAUTH2 extension).
///
/// Format: `AUTH XOAUTH2 <base64(user=<user>\x01auth=Bearer <token>\x01\x01)>`
///
/// Used in tests to verify line-length thresholds for the SASL-IR
/// one-step vs two-step decision (RFC 4954 Section 4).
#[cfg(test)]
pub(crate) fn encode_auth_xoauth2(buf: &mut BytesMut, user: &str, token: &str) {
    use base64::Engine;

    let sasl_string = format!("user={user}\x01auth=Bearer {token}\x01\x01");
    let encoded = base64::engine::general_purpose::STANDARD.encode(sasl_string.as_bytes());

    buf.extend_from_slice(b"AUTH XOAUTH2 ");
    buf.extend_from_slice(encoded.as_bytes());
    buf.extend_from_slice(b"\r\n");
}

/// Encode an AUTH OAUTHBEARER command (RFC 7628 Section 3.1).
///
/// Format: `AUTH OAUTHBEARER <base64(sasl_payload)>\r\n`
/// SASL payload: `n,,\x01auth=Bearer <token>\x01\x01`
///
/// Used in tests to verify the SASL payload encoding.
#[cfg(test)]
pub(crate) fn encode_auth_oauthbearer(buf: &mut BytesMut, token: &str) {
    use base64::Engine;

    // RFC 7628 Section 3.1: gs2-header is "n,," (no channel binding, no authzid)
    // followed by key-value pairs separated by SOH (\x01).
    let sasl_string = format!("n,,\x01auth=Bearer {token}\x01\x01");
    let encoded = base64::engine::general_purpose::STANDARD.encode(sasl_string.as_bytes());

    buf.extend_from_slice(b"AUTH OAUTHBEARER ");
    buf.extend_from_slice(encoded.as_bytes());
    buf.extend_from_slice(b"\r\n");
}

/// Encode the initial AUTH LOGIN command (draft-murchison-sasl-login).
///
/// Format: `AUTH LOGIN\r\n`
///
/// AUTH LOGIN is a multi-step challenge-response mechanism. The initial
/// command contains no credentials; the server responds with 334 challenges
/// for username and password. The connection layer handles the full SASL
/// exchange following the pattern in RFC 4954 Section 4.
///
/// Used in tests to verify the initial command encoding.
#[cfg(test)]
pub(crate) fn encode_auth_login_initial(buf: &mut BytesMut) {
    buf.extend_from_slice(b"AUTH LOGIN\r\n");
}

/// Encode MAIL FROM command (RFC 5321 Section 4.1.1.2).
///
/// If `size` is `Some`, includes the SIZE parameter (RFC 1870).
/// Delegates to [`encode_mail_from_full`] with default parameters.
pub(crate) fn encode_mail_from(buf: &mut BytesMut, from: &str, size: Option<u64>) {
    let params = MailFromParams {
        size,
        ..MailFromParams::default()
    };
    encode_mail_from_full(buf, from, &params);
}

/// Encode RCPT TO command (RFC 5321 Section 4.1.1.3).
pub(crate) fn encode_rcpt_to(buf: &mut BytesMut, to: &str) {
    buf.extend_from_slice(b"RCPT TO:<");
    buf.extend_from_slice(to.as_bytes());
    buf.extend_from_slice(b">\r\n");
}

/// Encode an extended RCPT TO command with optional ESMTP parameters
/// (RFC 5321 Section 4.1.1.3).
///
/// When `params` is empty, this produces the same output as [`encode_rcpt_to`].
/// Extension-specific parameters (e.g., DSN NOTIFY/ORCPT per RFC 3461
/// Section 4.2) are appended after the address.
pub(crate) fn encode_rcpt_to_full(buf: &mut BytesMut, to: &str, params: &RcptToParams) {
    buf.extend_from_slice(b"RCPT TO:<");
    buf.extend_from_slice(to.as_bytes());
    buf.extend_from_slice(b">");

    // NOTIFY parameter per RFC 3461 Section 4.1
    if let Some(notify) = &params.notify {
        buf.extend_from_slice(b" NOTIFY=");
        // RFC 3461 Section 4.1: NEVER MUST NOT be combined with other values.
        // If NEVER is present anywhere in the list, emit only NEVER and
        // discard the rest — be conservative in what you send (Postel's law).
        if notify.iter().any(|n| matches!(n, DsnNotify::Never)) {
            buf.extend_from_slice(b"NEVER");
        } else {
            let mut first = true;
            for n in notify {
                if !first {
                    buf.extend_from_slice(b",");
                }
                first = false;
                match n {
                    DsnNotify::Success => buf.extend_from_slice(b"SUCCESS"),
                    DsnNotify::Failure => buf.extend_from_slice(b"FAILURE"),
                    DsnNotify::Delay => buf.extend_from_slice(b"DELAY"),
                    DsnNotify::Never => unreachable!(),
                }
            }
        }
    }

    // ORCPT parameter per RFC 3461 Section 4.2
    // Format: ORCPT=rfc822;<addr> where <addr> is xtext-encoded.
    if let Some(orcpt) = &params.orcpt {
        buf.extend_from_slice(b" ORCPT=rfc822;");
        encode_xtext(buf, orcpt);
    }

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

/// Encode DATA command (RFC 5321 Section 4.1.1.4).
pub(crate) fn encode_data(buf: &mut BytesMut) {
    buf.extend_from_slice(b"DATA\r\n");
}

/// Encode the end-of-data terminator (RFC 5321 Section 4.1.1.4).
///
/// The end-of-data sequence is `<CRLF>.<CRLF>` where the first `<CRLF>` is
/// "actually the terminator of the previous line." If `preceding_data` already
/// ends with `\r\n`, only `.\r\n` is emitted; otherwise `\r\n.\r\n` is emitted
/// to ensure the dot appears on a line by itself.
pub(crate) fn encode_data_end(buf: &mut BytesMut, preceding_data: &[u8]) {
    // RFC 5321 Section 4.1.1.4: the first CRLF in <CRLF>.<CRLF> terminates
    // the previous line. Only add it when the data doesn't already end with CRLF.
    if !preceding_data.ends_with(b"\r\n") {
        buf.extend_from_slice(b"\r\n");
    }
    buf.extend_from_slice(b".\r\n");
}

/// Encode STARTTLS command (RFC 3207 Section 4).
pub(crate) fn encode_starttls(buf: &mut BytesMut) {
    buf.extend_from_slice(b"STARTTLS\r\n");
}

/// Encode QUIT command (RFC 5321 Section 4.1.1.10).
pub(crate) fn encode_quit(buf: &mut BytesMut) {
    buf.extend_from_slice(b"QUIT\r\n");
}

/// Encode RSET command (RFC 5321 Section 4.1.1.5).
pub(crate) fn encode_rset(buf: &mut BytesMut) {
    buf.extend_from_slice(b"RSET\r\n");
}

/// Encode NOOP command (RFC 5321 Section 4.1.1.9).
pub(crate) fn encode_noop(buf: &mut BytesMut) {
    buf.extend_from_slice(b"NOOP\r\n");
}

/// Encode a BDAT command (RFC 3030 Section 3).
///
/// Format: `BDAT <size>\r\n` or `BDAT <size> LAST\r\n`.
/// The LAST keyword indicates the final chunk of the message.
pub(crate) fn encode_bdat(buf: &mut BytesMut, size: usize, last: bool) {
    buf.extend_from_slice(b"BDAT ");
    buf.extend_from_slice(size.to_string().as_bytes());
    if last {
        // LAST keyword per RFC 3030 Section 3
        buf.extend_from_slice(b" LAST");
    }
    buf.extend_from_slice(b"\r\n");
}

/// Encode an LHLO command (RFC 2033 Section 4.2).
///
/// LHLO is the LMTP equivalent of EHLO, used to initiate an LMTP session.
pub(crate) fn encode_lhlo(buf: &mut BytesMut, domain: &str) {
    encode_greeting(buf, b"LHLO ", domain);
}

/// Encode a HELO command (RFC 5321 Section 4.1.1.1).
///
/// HELO is the legacy greeting command, used as a fallback when EHLO is rejected
/// by the server.
pub(crate) fn encode_helo(buf: &mut BytesMut, domain: &str) {
    encode_greeting(buf, b"HELO ", domain);
}

/// Encode an extended MAIL FROM command with optional ESMTP parameters
/// (RFC 5321 Section 4.1.1.2).
///
/// Supports optional parameters:
/// - `SIZE=<n>` (RFC 1870 Section 3)
/// - `BODY=<type>` (RFC 1652 Section 3, RFC 3030 Section 2)
/// - `SMTPUTF8` (RFC 6531 Section 3.4)
/// - `REQUIRETLS` (RFC 8689 Section 3)
/// - `RET=FULL|HDRS` (RFC 3461 Section 4.3)
/// - `ENVID=<xtext>` (RFC 3461 Section 4.4)
pub(crate) fn encode_mail_from_full(buf: &mut BytesMut, from: &str, params: &MailFromParams) {
    buf.extend_from_slice(b"MAIL FROM:<");
    buf.extend_from_slice(from.as_bytes());
    buf.extend_from_slice(b">");

    // SIZE parameter per RFC 1870 Section 3
    if let Some(size) = params.size {
        buf.extend_from_slice(b" SIZE=");
        buf.extend_from_slice(size.to_string().as_bytes());
    }

    // BODY parameter per RFC 1652 Section 3 / RFC 3030 Section 2
    if let Some(body) = &params.body {
        match body {
            BodyType::SevenBit => buf.extend_from_slice(b" BODY=7BIT"),
            BodyType::EightBitMime => buf.extend_from_slice(b" BODY=8BITMIME"),
            BodyType::BinaryMime => buf.extend_from_slice(b" BODY=BINARYMIME"),
        }
    }

    // SMTPUTF8 parameter per RFC 6531 Section 3.4
    if params.smtputf8 {
        buf.extend_from_slice(b" SMTPUTF8");
    }

    // REQUIRETLS parameter per RFC 8689 Section 3
    if params.requiretls {
        buf.extend_from_slice(b" REQUIRETLS");
    }

    // RET parameter per RFC 3461 Section 4.3
    if let Some(ret) = &params.ret {
        match ret {
            DsnRet::Full => buf.extend_from_slice(b" RET=FULL"),
            DsnRet::Hdrs => buf.extend_from_slice(b" RET=HDRS"),
        }
    }

    // ENVID parameter per RFC 3461 Section 4.4
    // The value is an xtext-encoded string (RFC 3461 Section 4).
    if let Some(envid) = &params.envid {
        buf.extend_from_slice(b" ENVID=");
        encode_xtext(buf, envid);
    }

    // HOLDFOR parameter per RFC 4865 Section 5
    if let Some(hold_for) = params.hold_for {
        buf.extend_from_slice(b" HOLDFOR=");
        buf.extend_from_slice(hold_for.to_string().as_bytes());
    }

    // HOLDUNTIL parameter per RFC 4865 Section 5
    if let Some(hold_until) = &params.hold_until {
        buf.extend_from_slice(b" HOLDUNTIL=");
        buf.extend_from_slice(hold_until.as_bytes());
    }

    // BY parameter per RFC 2852 Section 4
    if let Some(deliver_by) = &params.deliver_by {
        buf.extend_from_slice(b" BY=");
        buf.extend_from_slice(deliver_by.seconds.to_string().as_bytes());
        match deliver_by.mode {
            DeliverByMode::Notify => buf.extend_from_slice(b";N"),
            DeliverByMode::Return => buf.extend_from_slice(b";R"),
        }
    }

    // MT-PRIORITY parameter per RFC 6758 Section 4
    if let Some(mt_priority) = params.mt_priority {
        buf.extend_from_slice(b" MT-PRIORITY=");
        buf.extend_from_slice(mt_priority.to_string().as_bytes());
    }

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

/// Encode a string as xtext per RFC 3461 Section 4.
///
/// xtext encoding replaces `+` and characters outside the range
/// `!`–`~` (printable ASCII excluding SP and `+`) with `+XX` hex
/// encoding (RFC 3461 Section 4: "xchar = %x21-2A / %x2C-7E /
/// hexchar", where hexchar = `+` 2HEXDIG).
fn encode_xtext(buf: &mut BytesMut, s: &str) {
    for &b in s.as_bytes() {
        // RFC 3461 Section 4: xchar = %x21-2A / %x2C-7E
        // Characters outside this range (including '+' = 0x2B and SP = 0x20)
        // must be hex-encoded as +XX.
        if b == b'+' || b <= 0x20 || b > 0x7E {
            buf.extend_from_slice(b"+");
            // RFC 3461 Section 4: hexchar = "+" 2HEXDIG (uppercase per convention)
            buf.extend_from_slice(format!("{b:02X}").as_bytes());
        } else {
            buf.extend_from_slice(&[b]);
        }
    }
}

/// Encode a command of the form `CMD SP arg CRLF`.
///
/// Shared by VRFY (RFC 5321 Section 4.1.1.6) and EXPN (RFC 5321 Section 4.1.1.7).
fn encode_cmd_with_arg(buf: &mut BytesMut, cmd: &[u8], arg: &str) {
    buf.extend_from_slice(cmd);
    buf.extend_from_slice(arg.as_bytes());
    buf.extend_from_slice(b"\r\n");
}

/// Encode a VRFY command (RFC 5321 Section 4.1.1.6).
///
/// Format: `VRFY SP String CRLF`
/// Asks the server to verify whether the argument identifies a user
/// or mailbox. Many servers disable VRFY for security reasons (RFC 5321
/// Section 3.5.3), returning 252 or 502.
pub(crate) fn encode_vrfy(buf: &mut BytesMut, address: &str) {
    encode_cmd_with_arg(buf, b"VRFY ", address);
}

/// Encode an EXPN command (RFC 5321 Section 4.1.1.7).
///
/// Format: `EXPN SP String CRLF`
/// Asks the server to expand a mailing list name. Many servers disable
/// EXPN for security reasons (RFC 5321 Section 3.5.3), returning 252
/// or 502.
pub(crate) fn encode_expn(buf: &mut BytesMut, list_name: &str) {
    encode_cmd_with_arg(buf, b"EXPN ", list_name);
}

/// Perform dot-stuffing on message data for DATA command.
///
/// Per RFC 5321 Section 4.5.2: any line beginning with `.` must have an
/// additional `.` prepended. Lines are delimited by CRLF (RFC 5321
/// Section 2.3.8), so only a `\n` preceded by `\r` counts as a line
/// boundary.
pub(crate) fn dot_stuff(data: &[u8]) -> Vec<u8> {
    let mut result = Vec::with_capacity(data.len() + data.len() / 50);
    let mut at_line_start = true;
    let mut prev_cr = false;

    for &byte in data {
        if at_line_start && byte == b'.' {
            result.push(b'.');
        }
        result.push(byte);
        // RFC 5321 Section 2.3.8: lines are terminated by CRLF, not bare LF.
        at_line_start = byte == b'\n' && prev_cr;
        prev_cr = byte == b'\r';
    }

    result
}

/// Calculate the size of dot-stuffed message data without allocating.
///
/// Returns the number of bytes that [`dot_stuff`] would produce for
/// `data`. Useful for pre-allocating buffers for dot-stuffed output.
///
/// Per RFC 5321 Section 4.5.2: any line beginning with `.` has an
/// additional `.` prepended. Lines are delimited by CRLF (RFC 5321
/// Section 2.3.8).
#[cfg(test)]
pub(crate) fn dot_stuff_size(data: &[u8]) -> usize {
    let mut size = data.len();
    let mut at_line_start = true;
    let mut prev_cr = false;

    for &byte in data {
        if at_line_start && byte == b'.' {
            size += 1;
        }
        at_line_start = byte == b'\n' && prev_cr;
        prev_cr = byte == b'\r';
    }

    size
}

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

    #[test]
    fn encode_ehlo_command() {
        let mut buf = BytesMut::new();
        encode_ehlo(&mut buf, "client.example.com");
        assert_eq!(&buf[..], b"EHLO client.example.com\r\n");
    }

    #[test]
    fn encode_mail_from_without_size() {
        let mut buf = BytesMut::new();
        encode_mail_from(&mut buf, "sender@example.com", None);
        assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com>\r\n");
    }

    #[test]
    fn encode_mail_from_with_size() {
        let mut buf = BytesMut::new();
        encode_mail_from(&mut buf, "sender@example.com", Some(1024));
        assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> SIZE=1024\r\n");
    }

    #[test]
    fn encode_rcpt_to_command() {
        let mut buf = BytesMut::new();
        encode_rcpt_to(&mut buf, "recipient@example.com");
        assert_eq!(&buf[..], b"RCPT TO:<recipient@example.com>\r\n");
    }

    #[test]
    fn dot_stuffing_no_dots() {
        assert_eq!(dot_stuff(b"hello\r\nworld\r\n"), b"hello\r\nworld\r\n");
    }

    #[test]
    fn dot_stuffing_leading_dot() {
        assert_eq!(
            dot_stuff(b".hidden\r\n.also\r\n"),
            b"..hidden\r\n..also\r\n"
        );
    }

    #[test]
    fn dot_stuffing_dot_in_middle() {
        // Dot not at line start should not be stuffed.
        assert_eq!(dot_stuff(b"no.dot\r\n"), b"no.dot\r\n");
    }

    #[test]
    fn dot_stuffing_at_start_of_data() {
        assert_eq!(dot_stuff(b".start"), b"..start");
    }

    #[test]
    fn dot_stuffing_bare_lf_not_treated_as_line_start() {
        // RFC 5321 Section 2.3.8: lines are terminated by CRLF, not bare LF.
        // RFC 5321 Section 4.5.2: dot-stuffing applies to dots at the start
        // of CRLF-delimited lines only. A dot after bare LF is NOT at a line
        // start and MUST NOT be stuffed, otherwise the receiver (which uses
        // CRLF boundaries) will not remove the extra dot, corrupting the message.
        assert_eq!(
            dot_stuff(b"test\n.notastart\r\n"),
            b"test\n.notastart\r\n",
            "dot after bare LF must not be stuffed (RFC 5321 Section 4.5.2)"
        );
    }

    #[test]
    fn dot_stuffing_crlf_dot_is_stuffed() {
        // Dot after proper CRLF line ending MUST be stuffed.
        assert_eq!(
            dot_stuff(b"test\r\n.start\r\n"),
            b"test\r\n..start\r\n",
            "dot after CRLF must be stuffed (RFC 5321 Section 4.5.2)"
        );
    }

    // ── dot_stuff_size — RFC 5321 §4.5.2 / RFC 1870 §3 ──────────────

    #[test]
    fn dot_stuff_size_matches_dot_stuff_len() {
        // dot_stuff_size must return the same value as dot_stuff().len()
        // for all inputs.
        let cases: &[&[u8]] = &[
            b"hello\r\nworld\r\n",
            b".hidden\r\n.also\r\n",
            b"no.dot\r\n",
            b".start",
            b"test\n.notastart\r\n",
            b"test\r\n.start\r\n",
            b"",
            b"Subject: Test\r\n\r\n.line1\r\n.line2\r\n",
        ];
        for data in cases {
            assert_eq!(
                dot_stuff_size(data),
                dot_stuff(data).len(),
                "dot_stuff_size mismatch for {:?}",
                String::from_utf8_lossy(data)
            );
        }
    }

    #[test]
    fn auth_plain_encoding() {
        use base64::Engine;

        let mut buf = BytesMut::new();
        encode_auth_plain(&mut buf, "user", "pass");
        // \0user\0pass -> base64
        let line = std::str::from_utf8(&buf).unwrap();
        assert!(line.starts_with("AUTH PLAIN "));
        assert!(line.ends_with("\r\n"));

        // Verify the base64 decodes correctly.
        let b64 = &line["AUTH PLAIN ".len()..line.len() - 2];
        let decoded = base64::engine::general_purpose::STANDARD
            .decode(b64)
            .unwrap();
        assert_eq!(decoded, b"\0user\0pass");
    }

    #[test]
    fn auth_xoauth2_encoding() {
        use base64::Engine;

        let mut buf = BytesMut::new();
        encode_auth_xoauth2(&mut buf, "user@example.com", "ya29.token");
        let line = std::str::from_utf8(&buf).unwrap();
        assert!(line.starts_with("AUTH XOAUTH2 "));

        let b64 = &line["AUTH XOAUTH2 ".len()..line.len() - 2];
        let decoded = base64::engine::general_purpose::STANDARD
            .decode(b64)
            .unwrap();
        let expected = "user=user@example.com\x01auth=Bearer ya29.token\x01\x01";
        assert_eq!(decoded, expected.as_bytes());
    }

    /// Verify that `encode_auth_plain` produces exact base64 matching
    /// the RFC 4616 credential format. This locks down the output
    /// before refactoring to eliminate duplicate credential computation
    /// in `connection.rs` `auth_plain()`.
    #[test]
    fn auth_plain_exact_base64_matches_manual_computation() {
        use base64::Engine;

        let user = "testuser";
        let pass = "testpass";

        // Manual RFC 4616 Section 2 computation: [authzid] NUL authcid NUL passwd
        let mut credentials = Vec::with_capacity(1 + user.len() + 1 + pass.len());
        credentials.push(0);
        credentials.extend_from_slice(user.as_bytes());
        credentials.push(0);
        credentials.extend_from_slice(pass.as_bytes());
        let expected_b64 = base64::engine::general_purpose::STANDARD.encode(&credentials);

        // Extract base64 from encode_auth_plain output
        let mut buf = BytesMut::new();
        encode_auth_plain(&mut buf, user, pass);
        let line = std::str::from_utf8(&buf).unwrap();
        let actual_b64 = &line["AUTH PLAIN ".len()..line.len() - 2];

        assert_eq!(
            actual_b64, expected_b64,
            "encode_auth_plain base64 must match manual RFC 4616 computation"
        );
    }

    /// Verify that `encode_auth_xoauth2` produces exact base64 matching
    /// the Google XOAUTH2 SASL format. This locks down the output
    /// before refactoring to eliminate duplicate credential computation
    /// in `connection.rs` `auth_xoauth2()`.
    #[test]
    fn auth_xoauth2_exact_base64_matches_manual_computation() {
        use base64::Engine;

        let user = "user@example.com";
        let token = "ya29.a0token";

        // Manual XOAUTH2 SASL string: user=<user>\x01auth=Bearer <token>\x01\x01
        let sasl_string = format!("user={user}\x01auth=Bearer {token}\x01\x01");
        let expected_b64 = base64::engine::general_purpose::STANDARD.encode(sasl_string.as_bytes());

        // Extract base64 from encode_auth_xoauth2 output
        let mut buf = BytesMut::new();
        encode_auth_xoauth2(&mut buf, user, token);
        let line = std::str::from_utf8(&buf).unwrap();
        let actual_b64 = &line["AUTH XOAUTH2 ".len()..line.len() - 2];

        assert_eq!(
            actual_b64, expected_b64,
            "encode_auth_xoauth2 base64 must match manual XOAUTH2 SASL computation"
        );
    }

    #[test]
    fn encode_bdat_without_last() {
        let mut buf = BytesMut::new();
        encode_bdat(&mut buf, 1024, false);
        assert_eq!(&buf[..], b"BDAT 1024\r\n");
    }

    #[test]
    fn encode_bdat_with_last() {
        let mut buf = BytesMut::new();
        encode_bdat(&mut buf, 512, true);
        assert_eq!(&buf[..], b"BDAT 512 LAST\r\n");
    }

    #[test]
    fn encode_lhlo_command() {
        let mut buf = BytesMut::new();
        encode_lhlo(&mut buf, "client.example.com");
        assert_eq!(&buf[..], b"LHLO client.example.com\r\n");
    }

    #[test]
    fn encode_helo_command() {
        let mut buf = BytesMut::new();
        encode_helo(&mut buf, "client.example.com");
        assert_eq!(&buf[..], b"HELO client.example.com\r\n");
    }

    #[test]
    fn encode_mail_from_full_no_params() {
        let mut buf = BytesMut::new();
        encode_mail_from_full(&mut buf, "sender@example.com", &MailFromParams::default());
        assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com>\r\n");
    }

    #[test]
    fn encode_mail_from_full_with_size() {
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            size: Some(2048),
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> SIZE=2048\r\n");
    }

    #[test]
    fn encode_mail_from_full_with_body_8bitmime() {
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            body: Some(BodyType::EightBitMime),
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(
            &buf[..],
            b"MAIL FROM:<sender@example.com> BODY=8BITMIME\r\n"
        );
    }

    #[test]
    fn encode_mail_from_full_with_body_binarymime() {
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            body: Some(BodyType::BinaryMime),
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(
            &buf[..],
            b"MAIL FROM:<sender@example.com> BODY=BINARYMIME\r\n"
        );
    }

    #[test]
    fn encode_mail_from_full_with_body_7bit() {
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            body: Some(BodyType::SevenBit),
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> BODY=7BIT\r\n");
    }

    #[test]
    fn encode_mail_from_full_with_smtputf8() {
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            smtputf8: true,
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> SMTPUTF8\r\n");
    }

    #[test]
    fn encode_mail_from_full_all_params() {
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            size: Some(4096),
            body: Some(BodyType::EightBitMime),
            smtputf8: true,
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(
            &buf[..],
            b"MAIL FROM:<sender@example.com> SIZE=4096 BODY=8BITMIME SMTPUTF8\r\n"
        );
    }

    // ── RFC 5321 §4.1.1.4 — end-of-data terminator ──

    #[test]
    fn data_end_no_extra_blank_line_when_data_ends_with_crlf() {
        // RFC 5321 Section 4.1.1.4: end-of-data is "<CRLF>.<CRLF>" where
        // the first CRLF is "actually the terminator of the previous line."
        // When message data already ends with CRLF, only ".\r\n" should be
        // appended — not "\r\n.\r\n" which injects a spurious blank line.
        let data = b"Subject: Test\r\n\r\nHello\r\n";
        let stuffed = dot_stuff(data);
        let mut terminator = BytesMut::new();
        encode_data_end(&mut terminator, &stuffed);

        // Assemble what goes on the wire: stuffed data + terminator.
        let mut wire = Vec::new();
        wire.extend_from_slice(&stuffed);
        wire.extend_from_slice(&terminator);

        // Must end with "Hello\r\n.\r\n" — NOT "Hello\r\n\r\n.\r\n".
        assert!(
            wire.ends_with(b"Hello\r\n.\r\n"),
            "expected wire to end with 'Hello\\r\\n.\\r\\n', got trailing bytes: {:?}",
            String::from_utf8_lossy(&wire[wire.len().saturating_sub(20)..])
        );
    }

    #[test]
    fn data_end_adds_crlf_when_data_does_not_end_with_crlf() {
        // If the data does NOT end with CRLF, the terminator must prepend
        // CRLF so the dot is on its own line (RFC 5321 Section 4.1.1.4).
        let data = b"incomplete line";
        let mut buf = BytesMut::new();
        encode_data_end(&mut buf, data);
        assert_eq!(&buf[..], b"\r\n.\r\n");
    }

    #[test]
    fn data_end_with_empty_data() {
        // Empty data (e.g. aborting DATA phase) — must still produce
        // a valid terminator with leading CRLF.
        let mut buf = BytesMut::new();
        encode_data_end(&mut buf, b"");
        assert_eq!(&buf[..], b"\r\n.\r\n");
    }

    #[test]
    fn encode_quit_command() {
        // RFC 5321 Section 4.1.1.10: "QUIT" CRLF
        let mut buf = BytesMut::new();
        encode_quit(&mut buf);
        assert_eq!(&buf[..], b"QUIT\r\n");
    }

    #[test]
    fn encode_vrfy_command() {
        // RFC 5321 Section 4.1.1.6: VRFY SP String CRLF
        let mut buf = BytesMut::new();
        encode_vrfy(&mut buf, "user@example.com");
        assert_eq!(&buf[..], b"VRFY user@example.com\r\n");
    }

    #[test]
    fn encode_expn_command() {
        // RFC 5321 Section 4.1.1.7: EXPN SP String CRLF
        let mut buf = BytesMut::new();
        encode_expn(&mut buf, "staff");
        assert_eq!(&buf[..], b"EXPN staff\r\n");
    }

    // ── equivalence tests: lock down before refactoring ──

    /// `encode_mail_from(from, None)` must produce the same output as
    /// `encode_mail_from_full(from, &MailFromParams::default())`.
    #[test]
    fn encode_mail_from_equiv_no_params() {
        let mut a = BytesMut::new();
        let mut b = BytesMut::new();
        encode_mail_from(&mut a, "test@example.com", None);
        encode_mail_from_full(&mut b, "test@example.com", &MailFromParams::default());
        assert_eq!(&a[..], &b[..]);
    }

    /// `encode_mail_from(from, Some(size))` must produce the same output as
    /// `encode_mail_from_full(from, &MailFromParams { size: Some(size), .. })`.
    #[test]
    fn encode_mail_from_equiv_with_size() {
        let mut a = BytesMut::new();
        let mut b = BytesMut::new();
        encode_mail_from(&mut a, "test@example.com", Some(5000));
        let params = MailFromParams {
            size: Some(5000),
            ..Default::default()
        };
        encode_mail_from_full(&mut b, "test@example.com", &params);
        assert_eq!(&a[..], &b[..]);
    }

    // ── AUTH LOGIN encoder — draft-murchison-sasl-login ──────────────

    #[test]
    fn auth_login_initial_encoding() {
        // AUTH LOGIN initial command: "AUTH LOGIN\r\n" with no credentials.
        // The server responds with 334 challenges for username and password.
        let mut buf = BytesMut::new();
        encode_auth_login_initial(&mut buf);
        assert_eq!(&buf[..], b"AUTH LOGIN\r\n");
    }

    // ── RCPT TO with params — RFC 5321 §4.1.1.3 ────────────────────────

    #[test]
    fn encode_rcpt_to_full_empty_params() {
        // RFC 5321 Section 4.1.1.3: with no params, output matches
        // encode_rcpt_to exactly.
        let mut a = BytesMut::new();
        let mut b = BytesMut::new();
        encode_rcpt_to(&mut a, "user@example.com");
        encode_rcpt_to_full(&mut b, "user@example.com", &RcptToParams::default());
        assert_eq!(&a[..], &b[..]);
    }

    // ── DSN — RFC 3461 ──────────────────────────────────────────────────

    #[test]
    fn encode_mail_from_full_with_ret_full() {
        // RFC 3461 Section 4.3: RET=FULL
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            ret: Some(DsnRet::Full),
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> RET=FULL\r\n");
    }

    #[test]
    fn encode_mail_from_full_with_ret_hdrs() {
        // RFC 3461 Section 4.3: RET=HDRS
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            ret: Some(DsnRet::Hdrs),
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> RET=HDRS\r\n");
    }

    #[test]
    fn encode_mail_from_full_with_envid() {
        // RFC 3461 Section 4.4: ENVID=<xtext>
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            envid: Some("msg-12345".into()),
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(
            &buf[..],
            b"MAIL FROM:<sender@example.com> ENVID=msg-12345\r\n"
        );
    }

    #[test]
    fn encode_mail_from_full_envid_xtext_encoding() {
        // RFC 3461 Section 4: characters outside xchar range must be
        // hex-encoded as +XX.
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            envid: Some("id with+plus".into()),
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        // SP (0x20) -> +20, '+' (0x2B) -> +2B
        assert_eq!(
            &buf[..],
            b"MAIL FROM:<sender@example.com> ENVID=id+20with+2Bplus\r\n"
        );
    }

    #[test]
    fn encode_mail_from_full_with_ret_and_envid() {
        // RFC 3461: both RET and ENVID on the same MAIL FROM.
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            ret: Some(DsnRet::Hdrs),
            envid: Some("envelope-42".into()),
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(
            &buf[..],
            b"MAIL FROM:<sender@example.com> RET=HDRS ENVID=envelope-42\r\n"
        );
    }

    #[test]
    fn encode_rcpt_to_full_with_notify_success() {
        // RFC 3461 Section 4.1: NOTIFY=SUCCESS
        let mut buf = BytesMut::new();
        let params = RcptToParams {
            notify: Some(vec![DsnNotify::Success]),
            ..Default::default()
        };
        encode_rcpt_to_full(&mut buf, "user@example.com", &params);
        assert_eq!(&buf[..], b"RCPT TO:<user@example.com> NOTIFY=SUCCESS\r\n");
    }

    #[test]
    fn encode_rcpt_to_full_with_notify_multiple() {
        // RFC 3461 Section 4.1: NOTIFY=SUCCESS,FAILURE,DELAY
        let mut buf = BytesMut::new();
        let params = RcptToParams {
            notify: Some(vec![
                DsnNotify::Success,
                DsnNotify::Failure,
                DsnNotify::Delay,
            ]),
            ..Default::default()
        };
        encode_rcpt_to_full(&mut buf, "user@example.com", &params);
        assert_eq!(
            &buf[..],
            b"RCPT TO:<user@example.com> NOTIFY=SUCCESS,FAILURE,DELAY\r\n"
        );
    }

    #[test]
    fn encode_rcpt_to_full_with_notify_never() {
        // RFC 3461 Section 4.1: NOTIFY=NEVER (must not combine with others)
        let mut buf = BytesMut::new();
        let params = RcptToParams {
            notify: Some(vec![DsnNotify::Never]),
            ..Default::default()
        };
        encode_rcpt_to_full(&mut buf, "user@example.com", &params);
        assert_eq!(&buf[..], b"RCPT TO:<user@example.com> NOTIFY=NEVER\r\n");
    }

    #[test]
    fn encode_rcpt_to_full_with_orcpt() {
        // RFC 3461 Section 4.2: ORCPT=rfc822;<xtext-addr>
        let mut buf = BytesMut::new();
        let params = RcptToParams {
            orcpt: Some("user@example.com".into()),
            ..Default::default()
        };
        encode_rcpt_to_full(&mut buf, "user@example.com", &params);
        assert_eq!(
            &buf[..],
            b"RCPT TO:<user@example.com> ORCPT=rfc822;user@example.com\r\n"
        );
    }

    #[test]
    fn encode_rcpt_to_full_with_notify_and_orcpt() {
        // RFC 3461: both NOTIFY and ORCPT on the same RCPT TO.
        let mut buf = BytesMut::new();
        let params = RcptToParams {
            notify: Some(vec![DsnNotify::Success, DsnNotify::Failure]),
            orcpt: Some("original@example.com".into()),
        };
        encode_rcpt_to_full(&mut buf, "user@example.com", &params);
        assert_eq!(
            &buf[..],
            b"RCPT TO:<user@example.com> NOTIFY=SUCCESS,FAILURE ORCPT=rfc822;original@example.com\r\n"
        );
    }

    #[test]
    fn rcpt_to_params_is_empty() {
        // RcptToParams::is_empty must be true when no DSN fields are set.
        assert!(RcptToParams::default().is_empty());
        assert!(!RcptToParams {
            notify: Some(vec![DsnNotify::Success]),
            ..Default::default()
        }
        .is_empty());
        assert!(!RcptToParams {
            orcpt: Some("user@example.com".into()),
            ..Default::default()
        }
        .is_empty());
    }

    #[test]
    fn xtext_encoding_printable_ascii_passthrough() {
        // RFC 3461 Section 4: printable ASCII (except SP and +) passes through.
        let mut buf = BytesMut::new();
        encode_xtext(&mut buf, "user@example.com");
        assert_eq!(&buf[..], b"user@example.com");
    }

    #[test]
    fn xtext_encoding_plus_is_encoded() {
        // RFC 3461 Section 4: '+' (0x2B) must be encoded as +2B.
        let mut buf = BytesMut::new();
        encode_xtext(&mut buf, "a+b");
        assert_eq!(&buf[..], b"a+2Bb");
    }

    #[test]
    fn xtext_encoding_space_is_encoded() {
        // RFC 3461 Section 4: SP (0x20) is outside xchar range.
        let mut buf = BytesMut::new();
        encode_xtext(&mut buf, "a b");
        assert_eq!(&buf[..], b"a+20b");
    }

    // ── REQUIRETLS — RFC 8689 ───────────────────────────────────────────

    #[test]
    fn encode_mail_from_full_with_requiretls() {
        // RFC 8689 Section 3: REQUIRETLS parameter on MAIL FROM.
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            requiretls: true,
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> REQUIRETLS\r\n");
    }

    #[test]
    fn encode_mail_from_full_requiretls_false_omitted() {
        // When requiretls is false, no REQUIRETLS param should appear.
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            requiretls: false,
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com>\r\n");
    }

    // ── AUTH OAUTHBEARER — RFC 7628 ─────────────────────────────────────

    #[test]
    fn auth_oauthbearer_encoding() {
        use base64::Engine;

        let mut buf = BytesMut::new();
        encode_auth_oauthbearer(&mut buf, "ya29.token");
        let line = std::str::from_utf8(&buf).unwrap();
        assert!(line.starts_with("AUTH OAUTHBEARER "));
        assert!(line.ends_with("\r\n"));

        // Verify the SASL payload decodes correctly.
        let b64 = &line["AUTH OAUTHBEARER ".len()..line.len() - 2];
        let decoded = base64::engine::general_purpose::STANDARD
            .decode(b64)
            .unwrap();
        let expected = "n,,\x01auth=Bearer ya29.token\x01\x01";
        assert_eq!(decoded, expected.as_bytes());
    }

    // ── FUTURERELEASE — RFC 4865 ────────────────────────────────────────

    #[test]
    fn encode_mail_from_full_with_holdfor() {
        // RFC 4865 Section 5: HOLDFOR=<seconds>
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            hold_for: Some(86400),
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(
            &buf[..],
            b"MAIL FROM:<sender@example.com> HOLDFOR=86400\r\n"
        );
    }

    #[test]
    fn encode_mail_from_full_with_holduntil() {
        // RFC 4865 Section 5: HOLDUNTIL=<datetime>
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            hold_until: Some("2024-12-25T00:00:00Z".into()),
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(
            &buf[..],
            b"MAIL FROM:<sender@example.com> HOLDUNTIL=2024-12-25T00:00:00Z\r\n"
        );
    }

    // ── DELIVERBY — RFC 2852 ────────────────────────────────────────────

    #[test]
    fn encode_mail_from_full_with_deliver_by_return() {
        use crate::types::{DeliverBy, DeliverByMode};
        // RFC 2852 Section 4: BY=<seconds>;R
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            deliver_by: Some(DeliverBy {
                seconds: 3600,
                mode: DeliverByMode::Return,
            }),
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> BY=3600;R\r\n");
    }

    #[test]
    fn encode_mail_from_full_with_deliver_by_notify() {
        use crate::types::{DeliverBy, DeliverByMode};
        // RFC 2852 Section 4: BY=<seconds>;N
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            deliver_by: Some(DeliverBy {
                seconds: -120,
                mode: DeliverByMode::Notify,
            }),
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> BY=-120;N\r\n");
    }

    // ── MT-PRIORITY — RFC 6758 ──────────────────────────────────────────

    #[test]
    fn encode_mail_from_full_with_mt_priority() {
        // RFC 6758 Section 4: MT-PRIORITY=<n>
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            mt_priority: Some(3),
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(
            &buf[..],
            b"MAIL FROM:<sender@example.com> MT-PRIORITY=3\r\n"
        );
    }

    #[test]
    fn encode_mail_from_full_with_mt_priority_negative() {
        // RFC 6758 Section 4: MT-PRIORITY supports -6 to +5.
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            mt_priority: Some(-4),
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, "sender@example.com", &params);
        assert_eq!(
            &buf[..],
            b"MAIL FROM:<sender@example.com> MT-PRIORITY=-4\r\n"
        );
    }

    /// RFC 3461 Section 4.1: "NEVER" MUST NOT be combined with other NOTIFY
    /// values. When NEVER is present, the encoder must emit `NOTIFY=NEVER`
    /// only, ignoring any other values that were erroneously included.
    #[test]
    fn encode_rcpt_to_full_notify_never_not_combined_with_others() {
        let mut buf = BytesMut::new();
        let params = RcptToParams {
            notify: Some(vec![DsnNotify::Never, DsnNotify::Success]),
            ..Default::default()
        };
        encode_rcpt_to_full(&mut buf, "user@example.com", &params);
        // RFC 3461 Section 4.1: NEVER must be the sole value.
        assert_eq!(
            &buf[..],
            b"RCPT TO:<user@example.com> NOTIFY=NEVER\r\n",
            "NEVER must not be combined with other NOTIFY values (RFC 3461 Section 4.1)"
        );
    }

    /// RFC 3461 Section 4.1: When only NEVER is present (no combination
    /// violation), output must be `NOTIFY=NEVER`.
    #[test]
    fn encode_rcpt_to_full_notify_never_alone_unchanged() {
        let mut buf = BytesMut::new();
        let params = RcptToParams {
            notify: Some(vec![DsnNotify::Never]),
            ..Default::default()
        };
        encode_rcpt_to_full(&mut buf, "user@example.com", &params);
        assert_eq!(&buf[..], b"RCPT TO:<user@example.com> NOTIFY=NEVER\r\n");
    }
}