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};
#[derive(Debug)]
pub struct SmtpClient {
hello_name: ClientId,
smtp_utf8: bool,
expect_greeting: bool,
pipelining: bool,
}
impl Default for SmtpClient {
fn default() -> Self {
Self::new()
}
}
impl SmtpClient {
pub fn new() -> Self {
SmtpClient {
smtp_utf8: false,
hello_name: Default::default(),
expect_greeting: true,
pipelining: true,
}
}
pub fn smtp_utf8(self, enabled: bool) -> SmtpClient {
Self {
smtp_utf8: enabled,
..self
}
}
pub fn pipelining(self, enabled: bool) -> SmtpClient {
Self {
pipelining: enabled,
..self
}
}
pub fn hello_name(self, name: ClientId) -> SmtpClient {
Self {
hello_name: name,
..self
}
}
pub fn without_greeting(self) -> SmtpClient {
Self {
expect_greeting: false,
..self
}
}
}
#[derive(Debug)]
pub struct SmtpTransport<S: BufRead + Write + Unpin> {
server_info: ServerInfo,
client_info: SmtpClient,
stream: SmtpStream<S>,
}
impl<S: BufRead + Write + Unpin> SmtpTransport<S> {
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)?;
debug!("server {}", server_info);
let transport = SmtpTransport {
server_info,
client_info: builder,
stream,
};
Ok(transport)
}
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(())
}
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?;
Ok(self.stream.into_inner())
}
fn supports_feature(&self, keyword: Extension) -> bool {
self.server_info.supports_feature(keyword)
}
pub async fn quit(&mut self) -> Result<(), Error> {
self.stream.command(QuitCommand).await?;
Ok(())
}
pub async fn auth(&mut self, mechanism: Mechanism, credentials: &Credentials) -> SmtpResult {
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)
}
}
pub async fn send(&mut self, email: SendableEmail) -> SmtpResult {
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;
for to_address in email.envelope().to() {
self.stream
.send_command(RcptCommand::new(to_address.clone(), vec![]))
.await?;
sent_commands += 1;
}
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?;
for to_address in email.envelope().to() {
self.stream
.command(RcptCommand::new(to_address.clone(), vec![]))
.await?;
debug!("to=<{}>", to_address);
}
self.stream.command(DataCommand).await?;
}
let res = self.stream.message(email.message()).await;
if let Ok(result) = &res {
debug!(
"status=sent ({})",
result.message.get(0).unwrap_or(&"no response".to_string())
);
}
res
}
}