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
//! LMTP sending and LMTP BDAT (RFC 2033 Section 4.2 + RFC 3030 Section 3).
//!
//! Per-recipient response handling for both DATA and BDAT paths.

#[allow(clippy::wildcard_imports)]
use super::*;

impl SmtpConnection {
    // -----------------------------------------------------------------------
    // Sending — LMTP (RFC 2033)
    // -----------------------------------------------------------------------

    /// Send a message via LMTP and return per-recipient results.
    ///
    /// LMTP (RFC 2033 Section 4.2) differs from SMTP in that the server
    /// returns one response per accepted recipient after the DATA terminator,
    /// rather than a single aggregate response.
    ///
    /// Accepts optional [`MailFromParams`](crate::types::MailFromParams) to include ESMTP parameters
    /// such as `BODY=8BITMIME` (RFC 1652 Section 3) and `SMTPUTF8`
    /// (RFC 6531 Section 3.4). The SIZE parameter is always included
    /// automatically when the server advertises the SIZE extension
    /// (RFC 1870 Section 3).
    ///
    /// Addresses are pre-validated by their type constructors
    /// ([`ReversePath::new`], [`ForwardPath::new`]) per RFC 5321
    /// Section 4.1.2.
    ///
    /// Returns `Error::Protocol` if this connection is not LMTP.
    #[allow(clippy::significant_drop_tightening)]
    pub async fn send_lmtp(
        &self,
        from: &ReversePath,
        recipients: &[ForwardPath],
        message: &[u8],
        params: Option<&crate::types::MailFromParams>,
        timeout: Duration,
    ) -> Result<crate::types::LmtpSendResult, Error> {
        if self.protocol != Protocol::Lmtp {
            return Err(Error::Protocol(
                "send_lmtp requires an LMTP connection (RFC 2033)".into(),
            ));
        }
        let mut inner = self.inner.lock().await;
        // RFC 5321 Section 3.8: after a 421 response the server will close
        // the transmission channel. Fail immediately.
        if inner.server_shutting_down {
            return Err(Error::Protocol(
                "connection is shutting down after 421 (RFC 5321 Section 3.8)".into(),
            ));
        }
        let effective_mail_params = Some(Self::effective_mail_from_params(
            &inner.capabilities,
            from,
            recipients,
            message,
            params,
        )?);
        Self::validate_send_addresses(from, recipients)?;
        let message_size = Self::validate_data_prerequisites(
            &inner.capabilities,
            message,
            effective_mail_params.as_ref(),
            inner.stream.is_tls(),
        )?;
        tokio::time::timeout(timeout, async {
            Self::send_lmtp_inner(
                &mut inner,
                from,
                recipients,
                message,
                message_size,
                effective_mail_params.as_ref(),
                None,
            )
            .await
        })
        .await
        .map_err(|_| Error::Timeout)?
    }

    /// Send a message via LMTP with both MAIL FROM and per-recipient
    /// RCPT TO parameters, returning per-recipient results.
    ///
    /// Like [`send_lmtp`](Self::send_lmtp) but also accepts per-recipient
    /// [`RcptToParams`](crate::types::RcptToParams) to include DSN parameters (NOTIFY, ORCPT) on each
    /// RCPT TO command (RFC 3461 Sections 4.1–4.2).
    ///
    /// `rcpt_params` must have the same length as `recipients` — each
    /// entry is paired by index. Returns `Error::Protocol` if the
    /// lengths do not match.
    ///
    /// Addresses are pre-validated by their type constructors
    /// ([`ReversePath::new`], [`ForwardPath::new`]) per RFC 5321
    /// Section 4.1.2.
    ///
    /// Returns `Error::Protocol` if this connection is not LMTP.
    #[allow(clippy::significant_drop_tightening)]
    pub async fn send_lmtp_with_all_params(
        &self,
        from: &ReversePath,
        recipients: &[ForwardPath],
        message: &[u8],
        mail_params: Option<&crate::types::MailFromParams>,
        rcpt_params: &[crate::types::RcptToParams],
        timeout: Duration,
    ) -> Result<crate::types::LmtpSendResult, Error> {
        // RFC 3461 Sections 4.1–4.2: each recipient must have a
        // corresponding RcptToParams entry.
        if recipients.len() != rcpt_params.len() {
            return Err(Error::Protocol(format!(
                "rcpt_params length ({}) must match recipients length ({}) \
                 (RFC 3461 Sections 4.1–4.2)",
                rcpt_params.len(),
                recipients.len(),
            )));
        }
        if self.protocol != Protocol::Lmtp {
            return Err(Error::Protocol(
                "send_lmtp_with_all_params requires an LMTP connection (RFC 2033)".into(),
            ));
        }
        let mut inner = self.inner.lock().await;
        // RFC 5321 Section 3.8: after a 421 response the server will close
        // the transmission channel. Fail immediately.
        if inner.server_shutting_down {
            return Err(Error::Protocol(
                "connection is shutting down after 421 (RFC 5321 Section 3.8)".into(),
            ));
        }
        let effective_mail_params = Some(Self::effective_mail_from_params(
            &inner.capabilities,
            from,
            recipients,
            message,
            mail_params,
        )?);
        Self::validate_send_addresses(from, recipients)?;
        Self::validate_rcpt_params(&inner.capabilities, rcpt_params)?;
        let message_size = Self::validate_data_prerequisites(
            &inner.capabilities,
            message,
            effective_mail_params.as_ref(),
            inner.stream.is_tls(),
        )?;
        tokio::time::timeout(timeout, async {
            Self::send_lmtp_inner(
                &mut inner,
                from,
                recipients,
                message,
                message_size,
                effective_mail_params.as_ref(),
                Some(rcpt_params),
            )
            .await
        })
        .await
        .map_err(|_| Error::Timeout)?
    }

    /// Inner LMTP send logic (RFC 2033 Section 4.2).
    ///
    /// When `rcpt_params` is `Some`, per-recipient DSN parameters are
    /// included on each RCPT TO command (RFC 3461 Sections 4.1–4.2).
    async fn send_lmtp_inner(
        inner: &mut SmtpInner,
        from: &ReversePath,
        recipients: &[ForwardPath],
        message: &[u8],
        message_size: usize,
        params: Option<&crate::types::MailFromParams>,
        rcpt_params: Option<&[crate::types::RcptToParams]>,
    ) -> Result<crate::types::LmtpSendResult, Error> {
        Self::send_mail_from(inner, from, message, message_size, params).await?;
        // RFC 2033 Section 4.2 / RFC 5321 Section 3.3: capture both accepted
        // and rejected recipients so callers have full visibility.
        let (accepted_recipients, rejected) =
            Self::send_rcpt_to_batch(inner, recipients, rcpt_params).await?;

        Self::send_data_body(inner, message).await?;
        // LMTP: one response per accepted recipient (RFC 2033 Section 4.2).
        let results = Self::collect_lmtp_results(inner, accepted_recipients).await?;
        Ok(crate::types::LmtpSendResult {
            results,
            rejected_recipients: rejected,
        })
    }

    // -----------------------------------------------------------------------
    // Sending — LMTP BDAT (RFC 3030 §3 + RFC 2033 §4.2)
    // -----------------------------------------------------------------------

    /// Send a message via LMTP using BDAT chunking and return per-recipient results.
    ///
    /// Combines LMTP per-recipient response handling (RFC 2033 Section 4.2)
    /// with BDAT chunking (RFC 3030 Section 3). Unlike DATA, BDAT does not
    /// require dot-stuffing, making it suitable for binary content.
    ///
    /// Addresses are pre-validated by their type constructors
    /// ([`ReversePath::new`], [`ForwardPath::new`]) per RFC 5321
    /// Section 4.1.2.
    ///
    /// The server must advertise CHUNKING (RFC 3030). Returns
    /// `Error::Protocol` if this is not an LMTP connection or if the server
    /// does not support CHUNKING.
    #[allow(clippy::significant_drop_tightening)]
    pub async fn send_lmtp_bdat(
        &self,
        from: &ReversePath,
        recipients: &[ForwardPath],
        message: &[u8],
        params: Option<&crate::types::MailFromParams>,
        timeout: Duration,
    ) -> Result<crate::types::LmtpSendResult, Error> {
        // RFC 2033: LMTP connection required.
        if self.protocol != Protocol::Lmtp {
            return Err(Error::Protocol(
                "send_lmtp_bdat requires an LMTP connection (RFC 2033)".into(),
            ));
        }
        let mut inner = self.inner.lock().await;
        // RFC 5321 Section 3.8: after a 421 response the server will close
        // the transmission channel. Fail immediately.
        if inner.server_shutting_down {
            return Err(Error::Protocol(
                "connection is shutting down after 421 (RFC 5321 Section 3.8)".into(),
            ));
        }
        let effective_mail_params = Some(Self::effective_mail_from_params(
            &inner.capabilities,
            from,
            recipients,
            message,
            params,
        )?);
        Self::validate_send_addresses(from, recipients)?;
        Self::validate_bdat_prerequisites(
            &inner.capabilities,
            message,
            effective_mail_params.as_ref(),
            inner.stream.is_tls(),
        )?;
        tokio::time::timeout(timeout, async {
            Self::send_lmtp_bdat_inner(
                &mut inner,
                from,
                recipients,
                message,
                effective_mail_params.as_ref(),
                None,
            )
            .await
        })
        .await
        .map_err(|_| Error::Timeout)?
    }

    /// Send a message via LMTP using BDAT chunking with both MAIL FROM
    /// and per-recipient RCPT TO parameters, returning per-recipient results.
    ///
    /// Like [`send_lmtp_bdat`](Self::send_lmtp_bdat) but also accepts
    /// per-recipient [`RcptToParams`](crate::types::RcptToParams) to include DSN parameters (NOTIFY,
    /// ORCPT) on each RCPT TO command (RFC 3461 Sections 4.1–4.2).
    ///
    /// `rcpt_params` must have the same length as `recipients` — each
    /// entry is paired by index. Returns `Error::Protocol` if the
    /// lengths do not match.
    ///
    /// Addresses are pre-validated by their type constructors
    /// ([`ReversePath::new`], [`ForwardPath::new`]) per RFC 5321
    /// Section 4.1.2.
    ///
    /// The server must advertise CHUNKING (RFC 3030). Returns
    /// `Error::Protocol` if this is not an LMTP connection or if the
    /// server does not support CHUNKING.
    #[allow(clippy::significant_drop_tightening)]
    pub async fn send_lmtp_bdat_with_all_params(
        &self,
        from: &ReversePath,
        recipients: &[ForwardPath],
        message: &[u8],
        mail_params: Option<&crate::types::MailFromParams>,
        rcpt_params: &[crate::types::RcptToParams],
        timeout: Duration,
    ) -> Result<crate::types::LmtpSendResult, Error> {
        // RFC 3461 Sections 4.1–4.2: each recipient must have a
        // corresponding RcptToParams entry.
        if recipients.len() != rcpt_params.len() {
            return Err(Error::Protocol(format!(
                "rcpt_params length ({}) must match recipients length ({}) \
                 (RFC 3461 Sections 4.1–4.2)",
                rcpt_params.len(),
                recipients.len(),
            )));
        }
        // RFC 2033: LMTP connection required.
        if self.protocol != Protocol::Lmtp {
            return Err(Error::Protocol(
                "send_lmtp_bdat_with_all_params requires an LMTP connection (RFC 2033)".into(),
            ));
        }
        let mut inner = self.inner.lock().await;
        // RFC 5321 Section 3.8: after a 421 response the server will close
        // the transmission channel. Fail immediately.
        if inner.server_shutting_down {
            return Err(Error::Protocol(
                "connection is shutting down after 421 (RFC 5321 Section 3.8)".into(),
            ));
        }
        let effective_mail_params = Some(Self::effective_mail_from_params(
            &inner.capabilities,
            from,
            recipients,
            message,
            mail_params,
        )?);
        Self::validate_send_addresses(from, recipients)?;
        Self::validate_rcpt_params(&inner.capabilities, rcpt_params)?;
        Self::validate_bdat_prerequisites(
            &inner.capabilities,
            message,
            effective_mail_params.as_ref(),
            inner.stream.is_tls(),
        )?;
        tokio::time::timeout(timeout, async {
            Self::send_lmtp_bdat_inner(
                &mut inner,
                from,
                recipients,
                message,
                effective_mail_params.as_ref(),
                Some(rcpt_params),
            )
            .await
        })
        .await
        .map_err(|_| Error::Timeout)?
    }

    /// Inner LMTP BDAT send logic (RFC 3030 Section 3 + RFC 2033 Section 4.2).
    ///
    /// When `rcpt_params` is `Some`, per-recipient DSN parameters are
    /// included on each RCPT TO command (RFC 3461 Sections 4.1–4.2).
    async fn send_lmtp_bdat_inner(
        inner: &mut SmtpInner,
        from: &ReversePath,
        recipients: &[ForwardPath],
        message: &[u8],
        params: Option<&crate::types::MailFromParams>,
        rcpt_params: Option<&[crate::types::RcptToParams]>,
    ) -> Result<crate::types::LmtpSendResult, Error> {
        // RFC 2033 Section 4.2 / RFC 5321 Section 3.3: capture both accepted
        // and rejected recipients so callers have full visibility.
        let (accepted, rejected) =
            Self::send_bdat_envelope(inner, from, recipients, message, params, rcpt_params).await?;

        // LMTP: one response per accepted recipient after BDAT LAST
        // (RFC 2033 Section 4.2).
        let results = Self::collect_lmtp_results(inner, accepted).await?;
        Ok(crate::types::LmtpSendResult {
            results,
            rejected_recipients: rejected,
        })
    }

    /// Send the DATA command, dot-stuff the message body, and write the
    /// terminator (RFC 5321 Sections 4.1.1.4 / 4.5.2).
    ///
    /// On return the message body has been sent, but the final response(s)
    /// have NOT been read — the caller must read them (SMTP: one response;
    /// LMTP: one per accepted recipient per RFC 2033 Section 4.2).
    pub(super) async fn send_data_body(inner: &mut SmtpInner, message: &[u8]) -> Result<(), Error> {
        // DATA (RFC 5321 Section 4.1.1.4).
        let mut buf = BytesMut::new();
        encode::encode_data(&mut buf);
        inner.write_all(&buf).await?;
        let resp = inner.read_response().await?;
        // RFC 5321 Section 4.1.1.4: 354 is the only valid intermediate
        // response to DATA. Any other code means DATA was rejected.
        if resp.code != 354 {
            // RFC 5321 Section 3.3: DATA was rejected but the mail
            // transaction (MAIL FROM) is still open. RSET to clean up.
            inner.rset_best_effort().await;
            return Err(Self::response_to_error(resp));
        }

        // Send dot-stuffed message body + terminator in a single write
        // (RFC 5321 Section 4.5.2 / Section 4.1.1.4).
        let body = encode::dot_stuff_and_terminate(message);
        inner.write_all(&body).await?;
        Ok(())
    }

    /// Collect per-recipient LMTP responses (RFC 2033 Section 4.2).
    ///
    /// After DATA or BDAT LAST, LMTP returns one response per accepted
    /// recipient. This helper reads them all and pairs each with its
    /// recipient address.
    pub(super) async fn collect_lmtp_results(
        inner: &mut SmtpInner,
        accepted_recipients: Vec<ForwardPath>,
    ) -> Result<Vec<RecipientResult>, Error> {
        let mut results = Vec::with_capacity(accepted_recipients.len());
        for fp in accepted_recipients {
            let resp = inner.read_response().await?;
            results.push(RecipientResult {
                recipient: fp,
                response: resp,
            });
        }
        Ok(results)
    }
}