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
//! SMTP protocol types.

/// Transport protocol for the connection.
///
/// Determines the greeting command and DATA response handling.
/// SMTP uses EHLO and returns one reply after DATA (RFC 5321 Section 3.1).
/// LMTP uses LHLO and returns one reply per recipient after DATA (RFC 2033 Section 4.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Protocol {
    /// Standard SMTP (RFC 5321). Uses EHLO; one reply after DATA.
    Smtp,
    /// Local Mail Transfer Protocol (RFC 2033). Uses LHLO; one reply per recipient after DATA.
    Lmtp,
}

/// Per-recipient delivery result for LMTP (RFC 2033 Section 4.2).
///
/// In LMTP, the server sends one response per RCPT TO after the final DATA dot,
/// rather than a single aggregate response as in SMTP.
#[derive(Debug, Clone)]
pub struct RecipientResult {
    /// The recipient address.
    pub recipient: String,
    /// The server's response for this recipient.
    pub response: SmtpResponse,
}

/// A parsed SMTP server response.
///
/// Multi-line responses are collected into a single `SmtpResponse` with the final
/// reply code.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SmtpResponse {
    /// Three-digit reply code (e.g. 250, 354, 550).
    pub code: u16,
    /// Enhanced status code (RFC 2034), if present.
    pub enhanced_code: Option<EnhancedStatusCode>,
    /// Response text lines (one per line in a multi-line response).
    pub lines: Vec<String>,
}

impl SmtpResponse {
    /// Returns `true` if this is a positive completion reply (2xx).
    pub fn is_success(&self) -> bool {
        (200..300).contains(&self.code)
    }

    /// Returns `true` if this is a positive intermediate reply (3xx).
    pub fn is_intermediate(&self) -> bool {
        (300..400).contains(&self.code)
    }

    /// Returns `true` if this is a transient negative reply (4xx).
    pub fn is_transient_error(&self) -> bool {
        (400..500).contains(&self.code)
    }

    /// Returns `true` if this is a permanent negative reply (5xx).
    pub fn is_permanent_error(&self) -> bool {
        (500..600).contains(&self.code)
    }

    /// Join all response lines into a single string, separated by newlines.
    pub fn text(&self) -> String {
        self.lines.join("\n")
    }
}

/// Enhanced status code per RFC 1893 / RFC 2034.
///
/// Format: `class.subject.detail` (e.g. `2.1.0` for "success, mailbox address").
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EnhancedStatusCode {
    /// Class: 2 (success), 4 (transient), 5 (permanent).
    pub class: u8,
    /// Subject component.
    pub subject: u16,
    /// Detail component.
    pub detail: u16,
}

/// SMTP server extension capabilities, parsed from EHLO response.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SmtpExtension {
    /// `8BITMIME` (RFC 1652).
    EightBitMime,
    /// `PIPELINING` (RFC 1854).
    Pipelining,
    /// `SIZE [limit]` (RFC 1870).
    Size(Option<u64>),
    /// `STARTTLS` (RFC 3207).
    StartTls,
    /// `AUTH mechanisms...` (RFC 4954).
    Auth(Vec<AuthMechanism>),
    /// `CHUNKING` (RFC 3030).
    Chunking,
    /// `BINARYMIME` (RFC 3030).
    BinaryMime,
    /// `SMTPUTF8` (RFC 6531).
    SmtpUtf8,
    /// `ENHANCEDSTATUSCODES` (RFC 2034).
    EnhancedStatusCodes,
    /// `SASL-IR` (RFC 4959). Indicates the server accepts an initial
    /// response on the AUTH command line (RFC 4954 Section 4).
    SaslIr,
    /// `DSN` (RFC 3461). Delivery Status Notification extension.
    Dsn,
    /// `REQUIRETLS` (RFC 8689). Per-message TLS enforcement.
    RequireTls,
    /// `FUTURERELEASE` (RFC 4865). Scheduled message delivery.
    ///
    /// The server may advertise a maximum hold interval (seconds) and/or
    /// a maximum hold-until datetime.
    FutureRelease {
        /// Maximum hold interval in seconds, if advertised (RFC 4865 Section 4).
        max_interval: Option<u64>,
        /// Maximum hold-until datetime string, if advertised (RFC 4865 Section 4).
        max_datetime: Option<String>,
    },
    /// `DELIVERBY` (RFC 2852). Time-bound delivery.
    ///
    /// Optional value is the server's maximum delivery time in seconds.
    DeliverBy(Option<u64>),
    /// `MT-PRIORITY` (RFC 6758). Message priority signaling.
    MtPriority,
    /// `VRFY` (RFC 5321 Section 4.1.1.6). Server supports VRFY command.
    Vrfy,
    /// `EXPN` (RFC 5321 Section 4.1.1.7). Server supports EXPN command.
    Expn,
    /// `NO-SOLICITING` (RFC 3865). Advertising policy extension.
    ///
    /// Optional value is a soliciting keyword.
    NoSoliciting(Option<String>),
    /// An unrecognized extension — keyword preserved verbatim.
    Other(String),
}

/// SMTP authentication mechanism.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AuthMechanism {
    /// `PLAIN` (RFC 4616).
    Plain,
    /// `LOGIN` (draft-murchison-sasl-login, de-facto standard).
    ///
    /// AUTH LOGIN is a two-step challenge-response mechanism widely
    /// deployed by corporate and legacy servers. The SASL exchange
    /// follows the pattern in RFC 4954 Section 4.
    Login,
    /// `OAUTHBEARER` (RFC 7628 Section 3.1).
    ///
    /// Modern OAuth 2.0 bearer token SASL mechanism, replacing XOAUTH2.
    OAuthBearer,
    /// `XOAUTH2` (Google extension).
    XOAuth2,
    /// Unrecognized mechanism.
    Other(String),
}

impl AuthMechanism {
    /// Case-insensitive mechanism name comparison.
    ///
    /// RFC 4954 Section 3 / RFC 4422 Section 3.1: SASL mechanism names
    /// are case-insensitive. Known variants (`Plain`, `XOAuth2`) match
    /// by identity. `Other` variants are compared using
    /// `eq_ignore_ascii_case`, and cross-variant comparisons (e.g.
    /// `Other("PLAIN")` vs `Plain`) are resolved by mapping `Other`
    /// to its canonical name before comparing.
    fn eq_mechanism(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Plain, Self::Plain)
            | (Self::Login, Self::Login)
            | (Self::OAuthBearer, Self::OAuthBearer)
            | (Self::XOAuth2, Self::XOAuth2) => true,
            (Self::Other(a), Self::Other(b)) => a.eq_ignore_ascii_case(b),
            // Cross-variant: Other("PLAIN") must match Plain, etc.
            // RFC 4954 Section 3: mechanism names are case-insensitive
            // regardless of how they are represented in the enum.
            (Self::Other(name), Self::Plain) | (Self::Plain, Self::Other(name)) => {
                name.eq_ignore_ascii_case("PLAIN")
            }
            (Self::Other(name), Self::Login) | (Self::Login, Self::Other(name)) => {
                name.eq_ignore_ascii_case("LOGIN")
            }
            (Self::Other(name), Self::OAuthBearer) | (Self::OAuthBearer, Self::Other(name)) => {
                name.eq_ignore_ascii_case("OAUTHBEARER")
            }
            (Self::Other(name), Self::XOAuth2) | (Self::XOAuth2, Self::Other(name)) => {
                name.eq_ignore_ascii_case("XOAUTH2")
            }
            _ => false,
        }
    }
}

/// Server capabilities parsed from EHLO response.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ServerCapabilities {
    /// Server greeting name from the EHLO response.
    pub greeting_name: String,
    /// Extensions advertised by the server.
    pub extensions: Vec<SmtpExtension>,
}

impl ServerCapabilities {
    /// Check if the server supports a given auth mechanism.
    ///
    /// RFC 4954 Section 3 / RFC 4422 Section 3.1: SASL mechanism names
    /// are case-insensitive, so this method performs case-insensitive
    /// matching for [`AuthMechanism::Other`] variants.
    pub fn supports_auth(&self, mechanism: &AuthMechanism) -> bool {
        self.extensions.iter().any(|ext| {
            if let SmtpExtension::Auth(mechs) = ext {
                mechs.iter().any(|m| m.eq_mechanism(mechanism))
            } else {
                false
            }
        })
    }

    /// Check if any extension matches the given predicate.
    fn has_extension(&self, predicate: fn(&SmtpExtension) -> bool) -> bool {
        self.extensions.iter().any(predicate)
    }

    /// Check if the server advertises STARTTLS.
    pub fn supports_starttls(&self) -> bool {
        self.has_extension(|ext| matches!(ext, SmtpExtension::StartTls))
    }

    /// Check if the server supports CHUNKING (BDAT).
    pub fn supports_chunking(&self) -> bool {
        self.has_extension(|ext| matches!(ext, SmtpExtension::Chunking))
    }

    /// Check if the server supports the SIZE extension (RFC 1870).
    ///
    /// Returns `true` when the server advertises SIZE, regardless of
    /// whether a numeric limit was included. Use [`size_limit`] to
    /// retrieve the limit value.
    pub fn supports_size(&self) -> bool {
        self.has_extension(|ext| matches!(ext, SmtpExtension::Size(_)))
    }

    /// Get the SIZE limit, if advertised.
    pub fn size_limit(&self) -> Option<u64> {
        self.extensions.iter().find_map(|ext| {
            if let SmtpExtension::Size(limit) = ext {
                *limit
            } else {
                None
            }
        })
    }

    /// Check if the server supports 8BITMIME (RFC 1652).
    pub fn supports_8bitmime(&self) -> bool {
        self.has_extension(|ext| matches!(ext, SmtpExtension::EightBitMime))
    }

    /// Check if the server supports BINARYMIME (RFC 3030).
    pub fn supports_binarymime(&self) -> bool {
        self.has_extension(|ext| matches!(ext, SmtpExtension::BinaryMime))
    }

    /// Check if the server supports either 8BITMIME (RFC 1652) or BINARYMIME (RFC 3030).
    ///
    /// RFC 1652 Section 1 / RFC 3030 Section 2: when neither extension is
    /// advertised, the SMTP client is limited to 7-bit US-ASCII content.
    /// Either extension satisfies the requirement for non-7-bit BODY parameters.
    pub fn supports_8bit_or_binary(&self) -> bool {
        self.supports_8bitmime() || self.supports_binarymime()
    }

    /// Check if the server supports PIPELINING (RFC 1854).
    pub fn supports_pipelining(&self) -> bool {
        self.has_extension(|ext| matches!(ext, SmtpExtension::Pipelining))
    }

    /// Check if the server supports SMTPUTF8 (RFC 6531).
    pub fn supports_smtputf8(&self) -> bool {
        self.has_extension(|ext| matches!(ext, SmtpExtension::SmtpUtf8))
    }

    /// Check if the server supports SASL-IR (RFC 4959).
    ///
    /// When advertised, the client may include an initial response
    /// on the AUTH command line (RFC 4954 Section 4).
    pub fn supports_sasl_ir(&self) -> bool {
        self.has_extension(|ext| matches!(ext, SmtpExtension::SaslIr))
    }

    /// Check if the server supports DSN (RFC 3461).
    ///
    /// When advertised, the server accepts Delivery Status Notification
    /// parameters on MAIL FROM (RET, ENVID) and RCPT TO (NOTIFY, ORCPT)
    /// per RFC 3461 Sections 4.1–4.4.
    pub fn supports_dsn(&self) -> bool {
        self.has_extension(|ext| matches!(ext, SmtpExtension::Dsn))
    }

    /// Check if the server supports REQUIRETLS (RFC 8689).
    ///
    /// When advertised, the client may include the REQUIRETLS parameter
    /// on MAIL FROM to enforce TLS on every hop (RFC 8689 Sections 2–4).
    pub fn supports_requiretls(&self) -> bool {
        self.has_extension(|ext| matches!(ext, SmtpExtension::RequireTls))
    }

    /// Check if the server supports FUTURERELEASE (RFC 4865).
    pub fn supports_future_release(&self) -> bool {
        self.has_extension(|ext| matches!(ext, SmtpExtension::FutureRelease { .. }))
    }

    /// Check if the server supports DELIVERBY (RFC 2852).
    pub fn supports_deliver_by(&self) -> bool {
        self.has_extension(|ext| matches!(ext, SmtpExtension::DeliverBy(_)))
    }

    /// Check if the server supports MT-PRIORITY (RFC 6758).
    pub fn supports_mt_priority(&self) -> bool {
        self.has_extension(|ext| matches!(ext, SmtpExtension::MtPriority))
    }

    /// Check if the server supports VRFY (RFC 5321 Section 4.1.1.6).
    pub fn supports_vrfy(&self) -> bool {
        self.has_extension(|ext| matches!(ext, SmtpExtension::Vrfy))
    }

    /// Check if the server supports EXPN (RFC 5321 Section 4.1.1.7).
    pub fn supports_expn(&self) -> bool {
        self.has_extension(|ext| matches!(ext, SmtpExtension::Expn))
    }

    /// Check if the server supports Enhanced Status Codes (RFC 2034).
    ///
    /// When advertised, the server includes enhanced status codes
    /// (`class.subject.detail`) in its response text per RFC 2034 Section 3.
    pub fn supports_enhanced_status_codes(&self) -> bool {
        self.has_extension(|ext| matches!(ext, SmtpExtension::EnhancedStatusCodes))
    }
}

/// Parameters for the MAIL FROM command extensions.
///
/// Used with [`encode_mail_from_full`](crate::codec::encode::encode_mail_from_full)
/// to include optional ESMTP parameters in the MAIL FROM command.
///
/// RFC 5321 Section 4.1.1.2.
#[derive(Debug, Clone, Default)]
pub struct MailFromParams {
    /// Message size estimate in bytes (RFC 1870 Section 3).
    pub size: Option<u64>,
    /// Body transfer type (RFC 1652, RFC 3030).
    pub body: Option<BodyType>,
    /// Include SMTPUTF8 parameter (RFC 6531 Section 3.4).
    pub smtputf8: bool,
    /// Require TLS on every hop (RFC 8689 Section 3).
    pub requiretls: bool,
    /// DSN RET parameter: controls which part of the message is returned
    /// in a delivery status notification (RFC 3461 Section 4.3).
    pub ret: Option<DsnRet>,
    /// DSN ENVID parameter: sender-chosen envelope identifier included
    /// in any delivery status notifications (RFC 3461 Section 4.4).
    pub envid: Option<String>,
    /// Hold message for N seconds before delivery (RFC 4865 Section 5).
    pub hold_for: Option<u64>,
    /// Hold message until a specific datetime (RFC 4865 Section 5).
    /// ISO 8601 timestamp string.
    pub hold_until: Option<String>,
    /// Deliver within N seconds or return (RFC 2852 Section 3).
    pub deliver_by: Option<DeliverBy>,
    /// Message transfer priority, -6 to +5 (RFC 6758 Section 4).
    pub mt_priority: Option<i8>,
}

/// Parameters for the RCPT TO command extensions.
///
/// Used with [`encode_rcpt_to_full`](crate::codec::encode::encode_rcpt_to_full)
/// to include optional ESMTP parameters in the RCPT TO command.
///
/// RFC 5321 Section 4.1.1.3.
#[derive(Debug, Clone, Default)]
pub struct RcptToParams {
    /// DSN NOTIFY parameter: conditions under which a DSN should be
    /// generated for this recipient (RFC 3461 Section 4.1).
    pub notify: Option<Vec<DsnNotify>>,
    /// DSN ORCPT parameter: original recipient address for accurate
    /// DSN generation (RFC 3461 Section 4.2).
    pub orcpt: Option<String>,
}

impl RcptToParams {
    /// Returns `true` if no parameters are set.
    ///
    /// When empty, [`encode_rcpt_to_full`](crate::codec::encode::encode_rcpt_to_full)
    /// produces the same output as [`encode_rcpt_to`](crate::codec::encode::encode_rcpt_to).
    pub fn is_empty(&self) -> bool {
        self.notify.is_none() && self.orcpt.is_none()
    }
}

/// DELIVERBY parameters for the MAIL FROM command (RFC 2852 Section 3).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DeliverBy {
    /// Number of seconds within which the message should be delivered.
    /// Negative values indicate the message has already been in transit
    /// for that many seconds (RFC 2852 Section 4).
    pub seconds: i64,
    /// Delivery mode (RFC 2852 Section 3).
    pub mode: DeliverByMode,
}

/// DELIVERBY mode (RFC 2852 Section 3).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeliverByMode {
    /// `N` — Notify sender if delivery fails within the time limit.
    Notify,
    /// `R` — Return the message if delivery fails within the time limit.
    Return,
}

/// DSN RET parameter value (RFC 3461 Section 4.3).
///
/// Controls which part of the original message is returned in a
/// delivery status notification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DsnRet {
    /// Return the full message in DSNs (RFC 3461 Section 4.3).
    Full,
    /// Return only the headers in DSNs (RFC 3461 Section 4.3).
    Hdrs,
}

/// DSN NOTIFY condition (RFC 3461 Section 4.1).
///
/// Specifies under which conditions a delivery status notification
/// should be generated for a given recipient.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DsnNotify {
    /// Notify on successful delivery (RFC 3461 Section 4.1).
    Success,
    /// Notify on delivery failure (RFC 3461 Section 4.1).
    Failure,
    /// Notify on delivery delay (RFC 3461 Section 4.1).
    Delay,
    /// Never send a DSN for this recipient (RFC 3461 Section 4.1).
    ///
    /// NEVER must not be combined with other values.
    Never,
}

/// Body transfer type for the MAIL FROM `BODY=` parameter.
///
/// RFC 1652 Section 3 (8BITMIME), RFC 3030 Section 2 (BINARYMIME).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BodyType {
    /// 7-bit content (default per RFC 5321 Section 4.5.2).
    SevenBit,
    /// 8-bit content (RFC 1652 Section 3).
    EightBitMime,
    /// Binary content (RFC 3030 Section 2).
    BinaryMime,
}

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

    #[test]
    fn smtp_response_classification() {
        let ok = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["OK".into()],
        };
        assert!(ok.is_success());
        assert!(!ok.is_transient_error());
        assert!(!ok.is_permanent_error());

        let transient = SmtpResponse {
            code: 421,
            enhanced_code: None,
            lines: vec!["Try again later".into()],
        };
        assert!(transient.is_transient_error());
        assert!(!transient.is_success());

        let permanent = SmtpResponse {
            code: 550,
            enhanced_code: None,
            lines: vec!["Mailbox not found".into()],
        };
        assert!(permanent.is_permanent_error());
        assert!(!permanent.is_transient_error());
    }

    #[test]
    fn smtp_response_text() {
        let resp = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["line1".into(), "line2".into()],
        };
        assert_eq!(resp.text(), "line1\nline2");
    }

    #[test]
    fn server_capabilities_starttls() {
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::StartTls, SmtpExtension::Pipelining],
        };
        assert!(caps.supports_starttls());
        assert!(!caps.supports_chunking());
    }

    #[test]
    fn server_capabilities_auth() {
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::Auth(vec![
                AuthMechanism::Plain,
                AuthMechanism::XOAuth2,
            ])],
        };
        assert!(caps.supports_auth(&AuthMechanism::Plain));
        assert!(caps.supports_auth(&AuthMechanism::XOAuth2));
        assert!(!caps.supports_auth(&AuthMechanism::Other("CRAM-MD5".into())));
    }

    #[test]
    fn intermediate_response() {
        let resp = SmtpResponse {
            code: 354,
            enhanced_code: None,
            lines: vec!["Start mail input".into()],
        };
        assert!(resp.is_intermediate());
        assert!(!resp.is_success());
    }

    #[test]
    fn supports_8bitmime() {
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::EightBitMime],
        };
        assert!(caps.supports_8bitmime());

        let empty = ServerCapabilities::default();
        assert!(!empty.supports_8bitmime());
    }

    #[test]
    fn supports_binarymime() {
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::BinaryMime],
        };
        assert!(caps.supports_binarymime());

        let empty = ServerCapabilities::default();
        assert!(!empty.supports_binarymime());
    }

    #[test]
    fn supports_8bit_or_binary() {
        // RFC 1652 / RFC 3030: either extension satisfies the 8-bit requirement.
        let with_8bit = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::EightBitMime],
        };
        assert!(with_8bit.supports_8bit_or_binary());

        let with_binary = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::BinaryMime],
        };
        assert!(with_binary.supports_8bit_or_binary());

        let with_both = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::EightBitMime, SmtpExtension::BinaryMime],
        };
        assert!(with_both.supports_8bit_or_binary());

        let empty = ServerCapabilities::default();
        assert!(!empty.supports_8bit_or_binary());
    }

    #[test]
    fn supports_pipelining() {
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::Pipelining],
        };
        assert!(caps.supports_pipelining());

        let empty = ServerCapabilities::default();
        assert!(!empty.supports_pipelining());
    }

    #[test]
    fn supports_smtputf8() {
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::SmtpUtf8],
        };
        assert!(caps.supports_smtputf8());

        let empty = ServerCapabilities::default();
        assert!(!empty.supports_smtputf8());
    }

    // ── RFC 4954 §3 / RFC 4422 §3.1 — mechanism names are case-insensitive ──

    #[test]
    fn supports_auth_case_insensitive_other_mechanism() {
        // RFC 4954 Section 3 / RFC 4422 Section 3.1: SASL mechanism
        // names are case-insensitive. supports_auth must match
        // Other("login") against a stored Other("LOGIN") and vice versa.
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::Auth(vec![
                AuthMechanism::Other("LOGIN".into()),
                AuthMechanism::Other("CRAM-MD5".into()),
            ])],
        };
        // Exact case — should match.
        assert!(
            caps.supports_auth(&AuthMechanism::Other("LOGIN".into())),
            "exact case must match"
        );
        // Different case — must still match per RFC 4954 Section 3.
        assert!(
            caps.supports_auth(&AuthMechanism::Other("login".into())),
            "RFC 4954 Section 3: mechanism names are case-insensitive; \
             'login' must match stored 'LOGIN'"
        );
        assert!(
            caps.supports_auth(&AuthMechanism::Other("Login".into())),
            "RFC 4954 Section 3: mixed-case 'Login' must match stored 'LOGIN'"
        );
        assert!(
            caps.supports_auth(&AuthMechanism::Other("cram-md5".into())),
            "RFC 4954 Section 3: 'cram-md5' must match stored 'CRAM-MD5'"
        );
        // Non-existent mechanism — must not match.
        assert!(
            !caps.supports_auth(&AuthMechanism::Other("NTLM".into())),
            "non-existent mechanism must not match"
        );
    }

    // ── RFC 4954 §3 — cross-variant mechanism name matching ──────────

    #[test]
    fn eq_mechanism_cross_variant_other_plain() {
        // RFC 4954 Section 3 / RFC 4422 Section 3.1: SASL mechanism
        // names are case-insensitive. Other("PLAIN") must match the
        // dedicated Plain variant, because they represent the same
        // SASL mechanism regardless of how the enum was constructed.
        assert!(
            AuthMechanism::Other("PLAIN".into()).eq_mechanism(&AuthMechanism::Plain),
            "Other(\"PLAIN\") must match Plain (RFC 4954 Section 3)"
        );
        assert!(
            AuthMechanism::Plain.eq_mechanism(&AuthMechanism::Other("plain".into())),
            "Plain must match Other(\"plain\") (RFC 4954 Section 3)"
        );
    }

    #[test]
    fn eq_mechanism_cross_variant_other_xoauth2() {
        // Same cross-variant matching for XOAUTH2.
        assert!(
            AuthMechanism::Other("XOAUTH2".into()).eq_mechanism(&AuthMechanism::XOAuth2),
            "Other(\"XOAUTH2\") must match XOAuth2"
        );
        assert!(
            AuthMechanism::XOAuth2.eq_mechanism(&AuthMechanism::Other("xoauth2".into())),
            "XOAuth2 must match Other(\"xoauth2\")"
        );
    }

    #[test]
    fn supports_auth_cross_variant_other_plain() {
        // When the server advertises PLAIN (stored as AuthMechanism::Plain),
        // querying with Other("PLAIN") must return true.
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::Auth(vec![AuthMechanism::Plain])],
        };
        assert!(
            caps.supports_auth(&AuthMechanism::Other("PLAIN".into())),
            "RFC 4954 Section 3: Other(\"PLAIN\") query must match \
             stored Plain variant"
        );
        assert!(
            caps.supports_auth(&AuthMechanism::Other("plain".into())),
            "RFC 4954 Section 3: Other(\"plain\") query must match \
             stored Plain variant (case-insensitive)"
        );
    }

    #[test]
    fn supports_chunking() {
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::Chunking],
        };
        assert!(caps.supports_chunking());

        let empty = ServerCapabilities::default();
        assert!(!empty.supports_chunking());
    }

    #[test]
    fn supports_size() {
        // SIZE with a limit (RFC 1870 Section 2).
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::Size(Some(10_485_760))],
        };
        assert!(caps.supports_size());

        // SIZE without a limit (server advertises SIZE with no value).
        let caps_no_limit = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::Size(None)],
        };
        assert!(caps_no_limit.supports_size());

        let empty = ServerCapabilities::default();
        assert!(!empty.supports_size());
    }

    #[test]
    fn supports_sasl_ir() {
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::SaslIr],
        };
        assert!(caps.supports_sasl_ir());

        let empty = ServerCapabilities::default();
        assert!(!empty.supports_sasl_ir());
    }

    #[test]
    fn supports_enhanced_status_codes() {
        // RFC 2034 Section 2: the server advertises ENHANCEDSTATUSCODES
        // in its EHLO response. There must be a convenience method to
        // check for this extension, consistent with all other extensions.
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::EnhancedStatusCodes],
        };
        assert!(caps.supports_enhanced_status_codes());

        let empty = ServerCapabilities::default();
        assert!(!empty.supports_enhanced_status_codes());
    }

    #[test]
    fn size_limit_with_value() {
        // RFC 1870 Section 2: server advertises a numeric size limit.
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::Size(Some(10_485_760))],
        };
        assert_eq!(caps.size_limit(), Some(10_485_760));
    }

    #[test]
    fn size_limit_without_value() {
        // RFC 1870 Section 2: server advertises SIZE with no numeric limit.
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::Size(None)],
        };
        assert_eq!(caps.size_limit(), None);
    }

    #[test]
    fn size_limit_not_advertised() {
        let empty = ServerCapabilities::default();
        assert_eq!(empty.size_limit(), None);
    }

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

    #[test]
    fn supports_dsn() {
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::Dsn],
        };
        assert!(caps.supports_dsn());

        let empty = ServerCapabilities::default();
        assert!(!empty.supports_dsn());
    }

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

    #[test]
    fn supports_requiretls() {
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::RequireTls],
        };
        assert!(caps.supports_requiretls());

        let empty = ServerCapabilities::default();
        assert!(!empty.supports_requiretls());
    }

    // ── AuthMechanism::Login — de-facto standard AUTH LOGIN ───────────

    #[test]
    fn supports_auth_login() {
        // AUTH LOGIN is a de-facto standard (draft-murchison-sasl-login).
        // The dedicated Login variant must be detected by supports_auth.
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::Auth(vec![
                AuthMechanism::Plain,
                AuthMechanism::Login,
            ])],
        };
        assert!(caps.supports_auth(&AuthMechanism::Login));
        assert!(caps.supports_auth(&AuthMechanism::Plain));
    }

    #[test]
    fn eq_mechanism_login_identity() {
        // Login variant must match itself.
        assert!(AuthMechanism::Login.eq_mechanism(&AuthMechanism::Login));
    }

    #[test]
    fn eq_mechanism_cross_variant_other_login() {
        // RFC 4954 Section 3 / RFC 4422 Section 3.1: SASL mechanism
        // names are case-insensitive. Other("LOGIN") must match the
        // dedicated Login variant.
        assert!(
            AuthMechanism::Other("LOGIN".into()).eq_mechanism(&AuthMechanism::Login),
            "Other(\"LOGIN\") must match Login"
        );
        assert!(
            AuthMechanism::Login.eq_mechanism(&AuthMechanism::Other("login".into())),
            "Login must match Other(\"login\") (case-insensitive)"
        );
        assert!(
            AuthMechanism::Login.eq_mechanism(&AuthMechanism::Other("Login".into())),
            "Login must match Other(\"Login\") (mixed case)"
        );
    }

    #[test]
    fn supports_auth_cross_variant_other_login() {
        // When the server advertises LOGIN (stored as AuthMechanism::Login),
        // querying with Other("LOGIN") must return true.
        let caps = ServerCapabilities {
            greeting_name: "mail.example.com".into(),
            extensions: vec![SmtpExtension::Auth(vec![AuthMechanism::Login])],
        };
        assert!(
            caps.supports_auth(&AuthMechanism::Other("LOGIN".into())),
            "Other(\"LOGIN\") query must match stored Login variant"
        );
        assert!(
            caps.supports_auth(&AuthMechanism::Other("login".into())),
            "Other(\"login\") query must match stored Login variant"
        );
    }

    #[test]
    fn eq_mechanism_login_does_not_match_plain() {
        // Login and Plain are distinct mechanisms.
        assert!(!AuthMechanism::Login.eq_mechanism(&AuthMechanism::Plain));
        assert!(!AuthMechanism::Plain.eq_mechanism(&AuthMechanism::Login));
    }
}