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
use std::fmt::Debug;

use log::{debug, info};

use crate::authentication::{Credentials, Mechanism};
use crate::commands::*;
use crate::error::{Error, SmtpResult};
use crate::extension::{ClientId, Extension, MailBodyParameter, MailParameter, ServerInfo};
use crate::stream::SmtpStream;
use crate::SendableEmail;

#[cfg(feature = "runtime-async-std")]
use async_std::io::{BufRead, Write};
#[cfg(feature = "runtime-tokio")]
use tokio::io::{AsyncBufRead as BufRead, AsyncWrite as Write};

/// Contains client configuration
#[derive(Debug)]
pub struct SmtpClient {
    /// Name sent during EHLO
    hello_name: ClientId,
    /// Enable UTF8 mailboxes in envelope or headers
    smtp_utf8: bool,
    /// Whether to expect greeting.
    /// Normally the server sends a greeting after connection,
    /// but not after STARTTLS.
    expect_greeting: bool,
    /// Use pipelining if the server supports it
    pipelining: bool,
}

impl Default for SmtpClient {
    fn default() -> Self {
        Self::new()
    }
}

/// Builder for the SMTP `SmtpTransport`
impl SmtpClient {
    /// Creates a new SMTP client.
    ///
    /// It does not connect to the server, but only creates the `SmtpTransport`.
    ///
    /// Defaults are:
    ///
    /// * No authentication
    /// * No SMTPUTF8 support
    pub fn new() -> Self {
        SmtpClient {
            smtp_utf8: false,
            hello_name: Default::default(),
            expect_greeting: true,
            pipelining: true,
        }
    }

    /// Enable SMTPUTF8 if the server supports it
    pub fn smtp_utf8(self, enabled: bool) -> SmtpClient {
        Self {
            smtp_utf8: enabled,
            ..self
        }
    }

    /// Enable PIPELINING if the server supports it
    pub fn pipelining(self, enabled: bool) -> SmtpClient {
        Self {
            pipelining: enabled,
            ..self
        }
    }

    /// Set the name used during EHLO
    pub fn hello_name(self, name: ClientId) -> SmtpClient {
        Self {
            hello_name: name,
            ..self
        }
    }

    /// Do not expect greeting.
    ///
    /// Could be used for STARTTLS connections.
    pub fn without_greeting(self) -> SmtpClient {
        Self {
            expect_greeting: false,
            ..self
        }
    }
}

/// Structure that implements the high level SMTP client
#[derive(Debug)]
pub struct SmtpTransport<S: BufRead + Write + Unpin> {
    /// Information about the server
    server_info: ServerInfo,
    /// Information about the client
    client_info: SmtpClient,
    /// Low level client
    stream: SmtpStream<S>,
}

impl<S: BufRead + Write + Unpin> SmtpTransport<S> {
    /// Creates a new SMTP transport and connects.
    pub async fn new(builder: SmtpClient, stream: S) -> Result<Self, Error> {
        let mut stream = SmtpStream::new(stream);
        if builder.expect_greeting {
            let _greeting = stream.read_response().await?;
        }
        let ehlo_response = stream
            .ehlo(ClientId::new(builder.hello_name.to_string()))
            .await?;
        let server_info = ServerInfo::from_response(&ehlo_response)?;

        // Print server information
        debug!("server {}", server_info);

        let transport = SmtpTransport {
            server_info,
            client_info: builder,
            stream,
        };
        Ok(transport)
    }

    /// Try to login with the given accepted mechanisms.
    pub async fn try_login(
        &mut self,
        credentials: &Credentials,
        accepted_mechanisms: &[Mechanism],
    ) -> Result<(), Error> {
        if let Some(mechanism) = accepted_mechanisms
            .iter()
            .find(|mechanism| self.server_info.supports_auth_mechanism(**mechanism))
        {
            self.auth(*mechanism, credentials).await?;
        } else {
            info!("No supported authentication mechanisms available");
        }

        Ok(())
    }

    /// Sends STARTTLS command if the server supports it.
    ///
    /// Returns inner stream which should be upgraded to TLS.
    pub async fn starttls(mut self) -> Result<S, Error> {
        if !self.supports_feature(Extension::StartTls) {
            return Err(From::from("server does not support STARTTLS"));
        }

        self.stream.command(StarttlsCommand).await?;

        // Return the stream, so the caller can upgrade it to TLS.
        Ok(self.stream.into_inner())
    }

    fn supports_feature(&self, keyword: Extension) -> bool {
        self.server_info.supports_feature(keyword)
    }

    /// Closes the SMTP transaction if possible.
    pub async fn quit(&mut self) -> Result<(), Error> {
        self.stream.command(QuitCommand).await?;

        Ok(())
    }

    /// Sends an AUTH command with the given mechanism, and handles challenge if needed
    pub async fn auth(&mut self, mechanism: Mechanism, credentials: &Credentials) -> SmtpResult {
        // TODO
        let mut challenges = 10;
        let mut response = self
            .stream
            .command(AuthCommand::new(mechanism, credentials.clone(), None)?)
            .await?;

        while challenges > 0 && response.has_code(334) {
            challenges -= 1;
            response = self
                .stream
                .command(AuthCommand::new_from_response(
                    mechanism,
                    credentials.clone(),
                    &response,
                )?)
                .await?;
        }

        if challenges == 0 {
            Err(Error::ResponseParsing("Unexpected number of challenges"))
        } else {
            Ok(response)
        }
    }

    /// Sends an email.
    pub async fn send(&mut self, email: SendableEmail) -> SmtpResult {
        // Mail
        let mut mail_options = vec![];

        if self.supports_feature(Extension::EightBitMime) {
            mail_options.push(MailParameter::Body(MailBodyParameter::EightBitMime));
        }

        if self.supports_feature(Extension::SmtpUtfEight) && self.client_info.smtp_utf8 {
            mail_options.push(MailParameter::SmtpUtfEight);
        }

        let pipelining =
            self.supports_feature(Extension::Pipelining) && self.client_info.pipelining;

        if pipelining {
            self.stream
                .send_command(MailCommand::new(
                    email.envelope().from().cloned(),
                    mail_options,
                ))
                .await?;
            let mut sent_commands = 1;

            // Recipient
            for to_address in email.envelope().to() {
                self.stream
                    .send_command(RcptCommand::new(to_address.clone(), vec![]))
                    .await?;
                sent_commands += 1;
            }

            // Data
            self.stream.send_command(DataCommand).await?;
            sent_commands += 1;

            for _ in 0..sent_commands {
                self.stream.read_response().await?;
            }
        } else {
            self.stream
                .command(MailCommand::new(
                    email.envelope().from().cloned(),
                    mail_options,
                ))
                .await?;

            // Recipient
            for to_address in email.envelope().to() {
                self.stream
                    .command(RcptCommand::new(to_address.clone(), vec![]))
                    .await?;
                // Log the rcpt command
                debug!("to=<{}>", to_address);
            }

            // Data
            self.stream.command(DataCommand).await?;
        }

        let res = self.stream.message(email.message()).await;

        // Message content
        if let Ok(result) = &res {
            // Log the message
            debug!(
                "status=sent ({})",
                result.message.first().unwrap_or(&"no response".to_string())
            );
        }

        res
    }
}