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
//! SMTP protocol types.
//!
//! # References
//! - RFC 5321 (SMTP)
//! - RFC 2033 (LMTP)
//! - RFC 2034 (Enhanced Status Codes)
//! - RFC 4954 (SMTP AUTH)

pub(crate) mod validated;

pub use validated::{
    AddressLiteral, Domain, DomainOrLiteral, EnvidValue, ForwardPath, Mailbox, ReversePath,
    ValidationError, XtextSafe,
};

/// 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).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
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.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RecipientResult {
    /// The recipient address (RFC 5321 Section 4.1.2).
    pub recipient: ForwardPath,
    /// The server's response for this recipient.
    pub response: SmtpResponse,
}

/// A recipient whose RCPT TO command was rejected by the server.
///
/// RFC 5321 Section 3.3: when some but not all RCPT TO commands are
/// rejected, the server accepts the message for the remaining recipients.
/// This struct preserves the rejection details so callers can report or
/// retry individual failures.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RejectedRecipient {
    /// The rejected recipient address (RFC 5321 Section 4.1.2).
    pub recipient: ForwardPath,
    /// The server's rejection response (4xx or 5xx).
    pub response: SmtpResponse,
}

/// Result of a successful SMTP send operation (RFC 5321 Section 3.3).
///
/// When the server accepts at least one recipient and the DATA (or BDAT)
/// transfer succeeds, the message is delivered to the accepted recipients.
/// Any recipients whose RCPT TO was rejected are listed in
/// `rejected_recipients` so callers can take appropriate action (e.g. log,
/// retry, or notify the sender).
///
/// If **all** recipients are rejected, the send methods return
/// [`Error::AllRecipientsFailed`](crate::error::Error::AllRecipientsFailed)
/// instead of an `Ok(SendResult)`.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SendResult {
    /// Recipients whose RCPT TO command was rejected (RFC 5321 Section 3.3).
    ///
    /// Empty when all recipients were accepted.
    pub rejected_recipients: Vec<RejectedRecipient>,
}

impl SendResult {
    /// Returns `true` if all recipients were accepted.
    pub fn all_accepted(&self) -> bool {
        self.rejected_recipients.is_empty()
    }

    /// Returns `true` if some (but not all) recipients were rejected.
    pub fn has_rejections(&self) -> bool {
        !self.rejected_recipients.is_empty()
    }
}

/// Result of a successful LMTP send operation (RFC 2033 Section 4.2).
///
/// Combines per-recipient delivery results (from the server's per-recipient
/// DATA/BDAT responses) with any recipients rejected during RCPT TO.
///
/// LMTP differs from SMTP in that the server sends one response per accepted
/// recipient after the final DATA dot (RFC 2033 Section 4.2), rather than a
/// single aggregate response as in SMTP. This struct captures both sets of
/// information so callers have full visibility into which recipients were
/// accepted, which were rejected at RCPT TO time, and the delivery status
/// of each accepted recipient.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct LmtpSendResult {
    /// Per-recipient delivery results from the server after DATA/BDAT
    /// (RFC 2033 Section 4.2).
    ///
    /// Each entry corresponds to a recipient whose RCPT TO was accepted.
    /// The response may still indicate a delivery failure (e.g. 452, 550)
    /// — this is normal in LMTP where each recipient can independently
    /// succeed or fail during delivery.
    pub results: Vec<RecipientResult>,
    /// Recipients whose RCPT TO command was rejected (RFC 5321 Section 3.3).
    ///
    /// These recipients never received a per-recipient DATA response because
    /// they were rejected before the message was transmitted. Empty when all
    /// recipients were accepted at RCPT TO time.
    pub rejected_recipients: Vec<RejectedRecipient>,
}

impl LmtpSendResult {
    /// Returns `true` if all recipients were accepted at RCPT TO time.
    pub fn all_accepted(&self) -> bool {
        self.rejected_recipients.is_empty()
    }

    /// Returns `true` if some (but not all) recipients were rejected at RCPT TO time.
    pub fn has_rejections(&self) -> bool {
        !self.rejected_recipients.is_empty()
    }
}

/// A parsed SMTP server response (RFC 5321 Section 4.2).
///
/// Multi-line responses are collected into a single `SmtpResponse` with the final
/// reply code.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
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 the 354 "Start mail input" response to DATA.
    ///
    /// RFC 5321 Section 4.1.1.4: the only valid intermediate response to the
    /// DATA command is 354. Other 3xx codes are not defined for DATA and must
    /// not be treated as a go-ahead to send message content.
    pub fn is_data_ready(&self) -> bool {
        self.code == 354
    }

    /// 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")
    }
}

impl std::fmt::Display for SmtpResponse {
    /// Formats the response as `{code} {text}`, joining multi-line responses
    /// with newlines (RFC 5321 Section 4.2).
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for (i, line) in self.lines.iter().enumerate() {
            if i > 0 {
                f.write_str("\n")?;
            }
            write!(f, "{} {}", self.code, line)?;
        }
        if self.lines.is_empty() {
            write!(f, "{}", self.code)?;
        }
        Ok(())
    }
}

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

impl std::fmt::Display for EnhancedStatusCode {
    /// Formats as `class.subject.detail` per RFC 2034 Section 2.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.{}.{}", self.class, self.subject, self.detail)
    }
}

/// SMTP server extension capabilities, parsed from EHLO response
/// (RFC 5321 Section 4.1.1.1).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
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,
    /// Legacy, non-standard `SASL-IR` EHLO keyword seen on some SMTP servers.
    ///
    /// RFC 4954 Section 4 already defines `AUTH mechanism [initial-response]`,
    /// so SMTP does not require or standardize a separate capability for
    /// initial responses. We still preserve this keyword for compatibility
    /// and introspection.
    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 minimum delivery time in seconds
    /// (RFC 2852 Section 2).
    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),
}

impl std::fmt::Display for SmtpExtension {
    /// Formats as the canonical EHLO keyword (RFC 5321 Section 4.1.1.1).
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::EightBitMime => f.write_str("8BITMIME"),
            Self::Pipelining => f.write_str("PIPELINING"),
            Self::Size(Some(n)) => write!(f, "SIZE {n}"),
            Self::Size(None) => f.write_str("SIZE"),
            Self::StartTls => f.write_str("STARTTLS"),
            Self::Auth(mechs) => {
                f.write_str("AUTH")?;
                for m in mechs {
                    write!(f, " {m}")?;
                }
                Ok(())
            }
            Self::Chunking => f.write_str("CHUNKING"),
            Self::BinaryMime => f.write_str("BINARYMIME"),
            Self::SmtpUtf8 => f.write_str("SMTPUTF8"),
            Self::EnhancedStatusCodes => f.write_str("ENHANCEDSTATUSCODES"),
            Self::SaslIr => f.write_str("SASL-IR"),
            Self::Dsn => f.write_str("DSN"),
            Self::RequireTls => f.write_str("REQUIRETLS"),
            Self::FutureRelease {
                max_interval,
                max_datetime,
            } => {
                f.write_str("FUTURERELEASE")?;
                if let Some(interval) = max_interval {
                    write!(f, " {interval}")?;
                }
                if let Some(datetime) = max_datetime {
                    write!(f, " {datetime}")?;
                }
                Ok(())
            }
            Self::DeliverBy(Some(n)) => write!(f, "DELIVERBY {n}"),
            Self::DeliverBy(None) => f.write_str("DELIVERBY"),
            Self::MtPriority => f.write_str("MT-PRIORITY"),
            Self::Vrfy => f.write_str("VRFY"),
            Self::Expn => f.write_str("EXPN"),
            Self::NoSoliciting(Some(kw)) => write!(f, "NO-SOLICITING {kw}"),
            Self::NoSoliciting(None) => f.write_str("NO-SOLICITING"),
            Self::Other(s) => f.write_str(s),
        }
    }
}

/// SMTP authentication mechanism (RFC 4954 Section 3 / RFC 4422 Section 3.1).
///
/// Comparison and hashing are case-insensitive per RFC 4954 Section 3.
#[non_exhaustive]
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
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 {
    /// Returns the canonical SASL mechanism name used on the wire.
    ///
    /// RFC 4954 Section 3 / RFC 4422 Section 3.1: mechanism names are
    /// case-insensitive atoms.
    fn as_mechanism_name(&self) -> &str {
        match self {
            Self::Plain => "PLAIN",
            Self::Login => "LOGIN",
            Self::OAuthBearer => "OAUTHBEARER",
            Self::XOAuth2 => "XOAUTH2",
            Self::Other(name) => name,
        }
    }

    /// 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.
    pub(crate) fn eq_mechanism(&self, other: &Self) -> bool {
        self.as_mechanism_name()
            .eq_ignore_ascii_case(other.as_mechanism_name())
    }
}

impl PartialEq for AuthMechanism {
    fn eq(&self, other: &Self) -> bool {
        self.eq_mechanism(other)
    }
}

impl Eq for AuthMechanism {}

impl std::hash::Hash for AuthMechanism {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        for byte in self.as_mechanism_name().as_bytes() {
            byte.to_ascii_lowercase().hash(state);
        }
    }
}

impl std::fmt::Display for AuthMechanism {
    /// Formats as the canonical SASL mechanism name (RFC 4954 Section 3).
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_mechanism_name())
    }
}

/// Server capabilities parsed from EHLO response
/// (RFC 5321 Section 4.1.1.1).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ServerCapabilities {
    /// Server greeting name from the EHLO response.
    pub(crate) greeting_name: String,
    /// Extensions advertised by the server.
    pub(crate) extensions: Vec<SmtpExtension>,
}

impl ServerCapabilities {
    /// Returns the server's greeting name from the EHLO response.
    pub fn greeting_name(&self) -> &str {
        &self.greeting_name
    }

    /// Returns the server's advertised extensions.
    pub fn extensions(&self) -> &[SmtpExtension] {
        &self.extensions
    }

    /// 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 the server advertises the AUTH extension at all.
    ///
    /// RFC 4954 Section 3: the EHLO AUTH keyword advertises support for the
    /// AUTH command and the MAIL FROM AUTH parameter.
    pub fn supports_auth_extension(&self) -> bool {
        self.has_extension(|ext| matches!(ext, SmtpExtension::Auth(_)))
    }

    /// 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 [`Self::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 whether the server advertised the legacy `SASL-IR` keyword.
    ///
    /// RFC 4954 Section 4 already allows SMTP AUTH initial responses
    /// without a separate capability. This accessor is retained only so
    /// callers can inspect the EHLO response as advertised.
    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 { .. }))
    }

    /// Get the server-advertised FUTURERELEASE maximum hold interval in
    /// seconds, if any (RFC 4865 Section 4).
    pub fn future_release_max_interval(&self) -> Option<u64> {
        self.extensions.iter().find_map(|ext| {
            if let SmtpExtension::FutureRelease { max_interval, .. } = ext {
                *max_interval
            } else {
                None
            }
        })
    }

    /// Get the server-advertised FUTURERELEASE maximum hold-until datetime
    /// string, if any (RFC 4865 Section 4).
    pub fn future_release_max_datetime(&self) -> Option<&str> {
        self.extensions.iter().find_map(|ext| {
            if let SmtpExtension::FutureRelease { max_datetime, .. } = ext {
                max_datetime.as_deref()
            } else {
                None
            }
        })
    }

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

    /// Get the server-advertised DELIVERBY minimum time in seconds, if any
    /// (RFC 2852 Section 2).
    pub fn deliver_by_min(&self) -> Option<u64> {
        self.extensions.iter().find_map(|ext| {
            if let SmtpExtension::DeliverBy(min) = ext {
                *min
            } else {
                None
            }
        })
    }

    /// 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))
    }
}

/// AUTH= ESMTP parameter value for MAIL FROM (RFC 4954 Section 5).
///
/// When relaying a message, an SMTP server SHOULD include `AUTH=<mailbox>`
/// to declare the original authenticated sender, or `AUTH=<>` when the
/// identity is unknown or unauthenticated.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SmtpAuthParam {
    /// Authenticated sender mailbox — encoded as xtext on the wire
    /// (RFC 4954 Section 5).
    Mailbox(Mailbox),
    /// Unknown/unauthenticated origin — encoded as `<>` on the wire
    /// (RFC 4954 Section 5).
    Empty,
}

/// Parameters for the MAIL FROM command extensions.
///
/// Includes optional ESMTP parameters in the MAIL FROM command.
///
/// RFC 5321 Section 4.1.1.2.
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
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<EnvidValue>,
    /// 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, -9 to +9 (RFC 6758 Section 4).
    pub mt_priority: Option<i8>,
    /// AUTH= parameter: original authenticated sender identity
    /// (RFC 4954 Section 5). `None` omits the parameter entirely.
    pub auth: Option<SmtpAuthParam>,
}

/// Parameters for the RCPT TO command extensions.
///
/// Includes optional ESMTP parameters in the RCPT TO command.
///
/// RFC 5321 Section 4.1.1.3.
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
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, the RCPT TO command is encoded without any extension
    /// parameters.
    pub fn is_empty(&self) -> bool {
        let notify_is_empty = self.notify.as_ref().map_or(true, Vec::is_empty);
        notify_is_empty && self.orcpt.is_none()
    }
}

/// DELIVERBY parameters for the MAIL FROM command (RFC 2852 Section 3).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
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,
    /// RFC 2852 Section 4: optional trace flag (`T`) requesting return of
    /// trace information with any delivery status notification.
    pub trace: bool,
}

/// DELIVERBY mode (RFC 2852 Section 3).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
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.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
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.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
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).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
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)]
#[path = "tests.rs"]
mod tests;