Skip to main content

mail_send/smtp/
builder.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, tls::build_tls_connector};
8use crate::{Credentials, SmtpClient, SmtpClientBuilder};
9use smtp_proto::{EXT_START_TLS, EhloResponse};
10use std::hash::Hash;
11use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
12use std::time::Duration;
13use tokio::net::TcpSocket;
14use tokio::{
15    io,
16    io::{AsyncRead, AsyncWrite},
17    net::TcpStream,
18};
19use tokio_rustls::{TlsConnector, client::TlsStream};
20
21impl<T: AsRef<str> + PartialEq + Eq + Hash> SmtpClientBuilder<T> {
22    pub fn new(hostname: T, port: u16) -> Result<Self, String> {
23        Ok(Self::new_with_tls_connector(
24            hostname,
25            port,
26            build_tls_connector(false)?,
27        ))
28    }
29
30    /// Creates a builder that uses the provided TLS connector.
31    ///
32    /// Unlike [`SmtpClientBuilder::new`], this does not build the default rustls
33    /// configuration, so it does not require a process-level `CryptoProvider`.
34    pub fn new_with_tls_connector(hostname: T, port: u16, tls_connector: TlsConnector) -> Self {
35        SmtpClientBuilder {
36            addr: format!("{}:{}", hostname.as_ref(), port),
37            timeout: Duration::from_secs(60 * 60),
38            tls_connector,
39            tls_hostname: hostname,
40            tls_implicit: true,
41            is_lmtp: false,
42            local_host: gethostname::gethostname()
43                .to_str()
44                .unwrap_or("[127.0.0.1]")
45                .to_string(),
46            credentials: None,
47            say_ehlo: true,
48            local_ip: None,
49        }
50    }
51
52    /// Allow invalid TLS certificates
53    pub fn allow_invalid_certs(mut self) -> Self {
54        self.tls_connector = build_tls_connector(true).unwrap();
55        self
56    }
57
58    /// Start connection in TLS or upgrade with STARTTLS
59    pub fn implicit_tls(mut self, tls_implicit: bool) -> Self {
60        self.tls_implicit = tls_implicit;
61        self
62    }
63
64    /// Use LMTP instead of SMTP
65    pub fn lmtp(mut self, is_lmtp: bool) -> Self {
66        self.is_lmtp = is_lmtp;
67        self
68    }
69
70    // Say EHLO/LHLO
71    pub fn say_ehlo(mut self, say_ehlo: bool) -> Self {
72        self.say_ehlo = say_ehlo;
73        self
74    }
75
76    /// Set the EHLO/LHLO hostname
77    pub fn helo_host(mut self, host: impl Into<String>) -> Self {
78        self.local_host = host.into();
79        self
80    }
81
82    /// Sets the authentication credentials
83    pub fn credentials(mut self, credentials: impl Into<Credentials<T>>) -> Self {
84        self.credentials = Some(credentials.into());
85        self
86    }
87
88    /// Sets the SMTP connection timeout
89    pub fn timeout(mut self, timeout: Duration) -> Self {
90        self.timeout = timeout;
91        self
92    }
93
94    /// Sets the local IP to use while sending the email.
95    ///
96    /// This is useful if your machine has multiple public IPs assigned and you want to ensure
97    /// that you are using the intended one. Using an IP with good repudiation is quite important
98    /// when you want to ensure deliverability.
99    ///
100    /// *NOTE:* If the IP is not available on that machine, the [`connect`] and [`connect_plain`] will return and error
101    pub fn local_ip(mut self, local_ip: IpAddr) -> Self {
102        self.local_ip = Some(local_ip);
103        self
104    }
105
106    async fn tcp_stream(&self) -> io::Result<TcpStream> {
107        if let Some(local_addr) = self.local_ip {
108            let remote_addrs = self.addr.to_socket_addrs()?;
109            let mut last_err = None;
110
111            for addr in remote_addrs {
112                let local_addr = SocketAddr::new(local_addr, 0);
113                let socket = match local_addr.ip() {
114                    IpAddr::V4(_) => TcpSocket::new_v4()?,
115                    IpAddr::V6(_) => TcpSocket::new_v6()?,
116                };
117                socket.bind(local_addr)?;
118
119                match socket.connect(addr).await {
120                    Ok(stream) => return Ok(stream),
121                    Err(e) => last_err = Some(e),
122                }
123            }
124
125            Err(last_err.unwrap_or_else(|| {
126                io::Error::new(
127                    io::ErrorKind::InvalidInput,
128                    "could not resolve to any address",
129                )
130            }))
131        } else {
132            TcpStream::connect(&self.addr).await
133        }
134    }
135
136    /// Connect over TLS
137    pub async fn connect(&self) -> crate::Result<SmtpClient<TlsStream<TcpStream>>> {
138        tokio::time::timeout(self.timeout, async {
139            let mut client = SmtpClient {
140                stream: self.tcp_stream().await?,
141                timeout: self.timeout,
142            };
143
144            let mut client = if self.tls_implicit {
145                let mut client = client
146                    .into_tls(&self.tls_connector, self.tls_hostname.as_ref())
147                    .await?;
148                // Read greeting
149                client.read().await?.assert_positive_completion()?;
150                client
151            } else {
152                // Read greeting
153                client.read().await?.assert_positive_completion()?;
154
155                // Send EHLO
156                let response = if !self.is_lmtp {
157                    client.ehlo(&self.local_host).await?
158                } else {
159                    client.lhlo(&self.local_host).await?
160                };
161                if response.has_capability(EXT_START_TLS) {
162                    client
163                        .start_tls(&self.tls_connector, self.tls_hostname.as_ref())
164                        .await?
165                } else {
166                    return Err(crate::Error::MissingStartTls);
167                }
168            };
169
170            if self.say_ehlo {
171                // Obtain capabilities
172                let capabilities = client.capabilities(&self.local_host, self.is_lmtp).await?;
173                // Authenticate
174                if let Some(credentials) = &self.credentials {
175                    client.authenticate(&credentials, &capabilities).await?;
176                }
177            }
178
179            Ok(client)
180        })
181        .await
182        .map_err(|_| crate::Error::Timeout)?
183    }
184
185    /// Connect over clear text (should not be used)
186    pub async fn connect_plain(&self) -> crate::Result<SmtpClient<TcpStream>> {
187        let mut client = SmtpClient {
188            stream: tokio::time::timeout(self.timeout, async { self.tcp_stream().await })
189                .await
190                .map_err(|_| crate::Error::Timeout)??,
191            timeout: self.timeout,
192        };
193
194        // Read greeting
195        client.read().await?.assert_positive_completion()?;
196
197        if self.say_ehlo {
198            // Obtain capabilities
199            let capabilities = client.capabilities(&self.local_host, self.is_lmtp).await?;
200            // Authenticate
201            if let Some(credentials) = &self.credentials {
202                client.authenticate(&credentials, &capabilities).await?;
203            }
204        }
205
206        Ok(client)
207    }
208}
209
210impl<T: AsyncRead + AsyncWrite + Unpin> SmtpClient<T> {
211    pub async fn capabilities(
212        &mut self,
213        local_host: &str,
214        is_lmtp: bool,
215    ) -> crate::Result<EhloResponse<String>> {
216        if !is_lmtp {
217            self.ehlo(local_host).await
218        } else {
219            self.lhlo(local_host).await
220        }
221    }
222}
223
224#[cfg(all(test, feature = "aws_lc_rs"))]
225mod test {
226    use std::sync::Arc;
227
228    use rustls::{ClientConfig, RootCertStore, crypto::aws_lc_rs};
229    use tokio_rustls::TlsConnector;
230
231    use crate::SmtpClientBuilder;
232
233    // Builder accepts a caller-provided connector without touching the process-level CryptoProvider.
234    #[test]
235    fn new_with_tls_connector() {
236        let config = Arc::new(
237            ClientConfig::builder_with_provider(Arc::new(aws_lc_rs::default_provider()))
238                .with_safe_default_protocol_versions()
239                .unwrap()
240                .with_root_certificates(RootCertStore::empty())
241                .with_no_client_auth(),
242        );
243        let builder = SmtpClientBuilder::new_with_tls_connector(
244            "mail.example.com",
245            587,
246            TlsConnector::from(config.clone()),
247        );
248
249        assert_eq!(builder.addr, "mail.example.com:587");
250        assert_eq!(builder.tls_hostname, "mail.example.com");
251        assert!(Arc::ptr_eq(builder.tls_connector.config(), &config));
252    }
253}