Skip to main content

mail_send/smtp/
envelope.rs

1/*
2 * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
3 *
4 * SPDX-License-Identifier: Apache-2.0 OR MIT
5 */
6
7use super::{AssertReply, message::Parameters};
8use crate::SmtpClient;
9use smtp_proto::Response;
10use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt};
11
12impl<T: AsyncRead + AsyncWrite + Unpin> SmtpClient<T> {
13    /// Sends a MAIL FROM command to the server.
14    pub async fn mail_from(&mut self, addr: &str, params: &Parameters<'_>) -> crate::Result<()> {
15        self.cmd(format!("MAIL FROM:<{addr}>{params}\r\n").as_bytes())
16            .await?
17            .assert_positive_completion()
18    }
19
20    /// Sends a RCPT TO command to the server.
21    pub async fn rcpt_to(&mut self, addr: &str, params: &Parameters<'_>) -> crate::Result<()> {
22        self.cmd(format!("RCPT TO:<{addr}>{params}\r\n").as_bytes())
23            .await?
24            .assert_positive_completion()
25    }
26
27    /// Sends a DATA command to the server.
28    pub async fn data(&mut self, message: impl AsRef<[u8]>) -> crate::Result<Response<String>> {
29        self.cmd(b"DATA\r\n").await?.assert_code(354)?;
30        tokio::time::timeout(self.timeout, async {
31            // Write message
32            self.write_message(message.as_ref()).await?;
33            self.read().await
34        })
35        .await
36        .map_err(|_| crate::Error::Timeout)??
37        .into_positive_completion()
38    }
39
40    /// Sends a BDAT command to the server.
41    pub async fn bdat(&mut self, message: impl AsRef<[u8]>) -> crate::Result<Response<String>> {
42        let message = message.as_ref();
43        tokio::time::timeout(self.timeout, async {
44            self.stream
45                .write_all(format!("BDAT {} LAST\r\n", message.len()).as_bytes())
46                .await?;
47            self.stream.write_all(message).await?;
48            self.stream.flush().await?;
49            self.read().await
50        })
51        .await
52        .map_err(|_| crate::Error::Timeout)??
53        .into_positive_completion()
54    }
55
56    /// Sends a RSET command to the server.
57    pub async fn rset(&mut self) -> crate::Result<()> {
58        self.cmd(b"RSET\r\n").await?.assert_positive_completion()
59    }
60
61    /// Sends a NOOP command to the server.
62    pub async fn noop(&mut self) -> crate::Result<()> {
63        self.cmd(b"NOOP\r\n").await?.assert_positive_completion()
64    }
65
66    /// Sends a QUIT command to the server.
67    pub async fn quit(mut self) -> crate::Result<()> {
68        self.cmd(b"QUIT\r\n").await?.assert_positive_completion()
69    }
70}
71
72#[cfg(test)]
73mod test {
74    use std::time::Duration;
75
76    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, duplex};
77
78    use crate::{Error, SmtpClient, smtp::message::Message};
79
80    async fn send_with_final_reply(final_reply: &'static str) -> crate::Result<String> {
81        let (client_stream, server_stream) = duplex(4096);
82        let server = tokio::spawn(async move {
83            let (reader, mut writer) = tokio::io::split(server_stream);
84            let mut reader = BufReader::new(reader);
85            let mut line = String::new();
86            let mut in_data = false;
87            while reader.read_line(&mut line).await.unwrap_or(0) > 0 {
88                let reply = match (in_data, line.as_str()) {
89                    (false, "DATA\r\n") => {
90                        in_data = true;
91                        Some("354 Start mail input\r\n")
92                    }
93                    (false, _) => Some("250 OK\r\n"),
94                    (true, ".\r\n") => {
95                        in_data = false;
96                        Some(final_reply)
97                    }
98                    (true, _) => None,
99                };
100                if let Some(reply) = reply {
101                    writer.write_all(reply.as_bytes()).await.unwrap();
102                }
103                line.clear();
104            }
105        });
106
107        let mut client = SmtpClient {
108            stream: client_stream,
109            timeout: Duration::from_secs(5),
110        };
111        let result = client
112            .send(Message::new(
113                "sender@example.com",
114                ["rcpt@example.org"],
115                b"Subject: test\r\n\r\nHello\r\n".as_slice(),
116            ))
117            .await
118            .map(|response| response.message);
119        drop(client);
120        server.await.unwrap();
121        result
122    }
123
124    // send() returns the final DATA reply so callers can log the queue ID.
125    #[tokio::test]
126    async fn send_returns_data_reply() {
127        assert_eq!(
128            send_with_final_reply("250 2.0.0 Ok: queued as 224B824BD40\r\n")
129                .await
130                .unwrap(),
131            "Ok: queued as 224B824BD40"
132        );
133        assert!(matches!(
134            send_with_final_reply("554 5.7.1 Rejected\r\n").await,
135            Err(Error::UnexpectedReply(response)) if response.code == 554
136        ));
137    }
138}