1use serde::{Deserialize, Serialize};
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct SmtpConfig {
23 pub host: String,
25 pub port: u16,
27 pub username: String,
29 pub password: String,
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct ImapConfig {
36 pub host: String,
38 pub port: u16,
40 pub username: String,
42 pub password: String,
44}
45
46#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct Pop3Config {
51 pub host: String,
53 pub port: u16,
55 pub username: String,
56 pub password: String,
57}
58
59#[derive(Debug, Clone)]
62pub struct Pop3FetchedMessage {
63 pub uid: String,
64 pub inbound: crate::mail_rules::InboundMessage,
65 pub body: String,
66}
67
68#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct OutgoingMail {
71 pub from: String,
73 pub to: String,
75 pub subject: String,
77 pub body: String,
79}
80
81pub fn build_inbound(
87 from: &str,
88 to: &str,
89 subject: &str,
90 size: usize,
91 sender_verified: bool,
92 sender_did: Option<String>,
93) -> crate::mail_rules::InboundMessage {
94 crate::mail_rules::InboundMessage {
95 from_address: from.to_string(),
96 to_address: to.to_string(),
97 sender_did,
98 sender_verified,
99 subject: subject.to_string(),
100 size_bytes: size,
101 }
102}
103
104#[cfg(not(target_arch = "wasm32"))]
110pub fn send(cfg: &SmtpConfig, mail: &OutgoingMail) -> Result<(), String> {
111 use lettre::transport::smtp::authentication::Credentials;
112 use lettre::{Message, SmtpTransport, Transport};
113
114 let from = mail
115 .from
116 .parse::<lettre::message::Mailbox>()
117 .map_err(|e| format!("invalid from address {:?}: {}", mail.from, e))?;
118 let to = mail
119 .to
120 .parse::<lettre::message::Mailbox>()
121 .map_err(|e| format!("invalid to address {:?}: {}", mail.to, e))?;
122
123 let msg: Message = Message::builder()
124 .from(from)
125 .to(to)
126 .subject(mail.subject.clone())
127 .body(mail.body.clone())
128 .map_err(|e| format!("failed to build message: {}", e))?;
129
130 let creds = Credentials::new(cfg.username.clone(), cfg.password.clone());
131
132 let transport = SmtpTransport::starttls_relay(&cfg.host)
133 .map_err(|e| format!("failed to build STARTTLS relay for {:?}: {}", cfg.host, e))?
134 .port(cfg.port)
135 .credentials(creds)
136 .build();
137
138 transport
139 .send(&msg)
140 .map(|_| ())
141 .map_err(|e| format!("SMTP send failed: {}", e))
142}
143
144#[cfg(not(target_arch = "wasm32"))]
156pub fn fetch_unseen(
157 cfg: &ImapConfig,
158 mailbox: &str,
159) -> Result<Vec<crate::mail_rules::InboundMessage>, String> {
160 let tls = native_tls::TlsConnector::builder()
161 .build()
162 .map_err(|e| format!("failed to build TLS connector: {}", e))?;
163
164 let client = imap::connect((cfg.host.as_str(), cfg.port), &cfg.host, &tls)
165 .map_err(|e| format!("IMAP connect to {:?}:{} failed: {}", cfg.host, cfg.port, e))?;
166
167 let mut session = client
168 .login(&cfg.username, &cfg.password)
169 .map_err(|e| format!("IMAP login failed: {}", e.0))?;
171
172 let result = (|| -> Result<Vec<crate::mail_rules::InboundMessage>, String> {
174 session
175 .select(mailbox)
176 .map_err(|e| format!("IMAP SELECT {:?} failed: {}", mailbox, e))?;
177
178 let unseen = session
179 .search("UNSEEN")
180 .map_err(|e| format!("IMAP SEARCH UNSEEN failed: {}", e))?;
181
182 let mut out: Vec<crate::mail_rules::InboundMessage> = Vec::with_capacity(unseen.len());
183
184 for uid in unseen {
185 let fetches = match session.fetch(uid.to_string(), "RFC822.SIZE ENVELOPE") {
187 Ok(f) => f,
188 Err(_) => continue,
190 };
191
192 for fetch in fetches.iter() {
193 let envelope = match fetch.envelope() {
194 Some(e) => e,
195 None => continue,
196 };
197
198 let subject = envelope
200 .subject
201 .as_ref()
202 .map(|s| String::from_utf8_lossy(s).into_owned())
203 .unwrap_or_default();
204
205 let parts_to_string =
207 |mailbox_bytes: Option<&[u8]>, host_bytes: Option<&[u8]>| -> String {
208 let mailbox_part = mailbox_bytes
209 .map(|m| String::from_utf8_lossy(m).into_owned())
210 .unwrap_or_default();
211 let host_part = host_bytes
212 .map(|h| String::from_utf8_lossy(h).into_owned())
213 .unwrap_or_default();
214 if host_part.is_empty() {
215 mailbox_part
216 } else {
217 format!("{mailbox_part}@{host_part}")
218 }
219 };
220
221 let from = envelope
223 .from
224 .as_ref()
225 .and_then(|addrs| addrs.first())
226 .map(|addr| {
227 parts_to_string(
228 addr.mailbox.as_ref().map(|m| m.as_ref()),
229 addr.host.as_ref().map(|h| h.as_ref()),
230 )
231 })
232 .unwrap_or_default();
233
234 let to = envelope
237 .to
238 .as_ref()
239 .and_then(|addrs| addrs.first())
240 .map(|addr| {
241 parts_to_string(
242 addr.mailbox.as_ref().map(|m| m.as_ref()),
243 addr.host.as_ref().map(|h| h.as_ref()),
244 )
245 })
246 .filter(|s| s.contains('@'))
247 .unwrap_or_else(|| mailbox.to_string());
248
249 let size = fetch.size.unwrap_or(0) as usize;
251
252 out.push(build_inbound(
253 &from, &to, &subject, size,
254 false, None, ));
257 }
258 }
259
260 Ok(out)
261 })();
262
263 let _ = session.logout();
265
266 result
267}
268
269#[cfg(not(target_arch = "wasm32"))]
274pub fn fetch_pop3(cfg: &Pop3Config, mailbox: &str) -> Result<Vec<Pop3FetchedMessage>, String> {
275 use std::io::{BufRead, BufReader, Write};
276 use std::net::TcpStream;
277
278 fn response_line<S: std::io::Read>(reader: &mut BufReader<S>) -> Result<String, String> {
279 let mut line = String::new();
280 reader
281 .read_line(&mut line)
282 .map_err(|e| format!("POP3 read failed: {e}"))?;
283 if !line.starts_with("+OK") {
284 return Err(format!("POP3 rejected command: {}", line.trim()));
285 }
286 Ok(line)
287 }
288 fn command<S: std::io::Read + Write>(
289 reader: &mut BufReader<S>,
290 command: &str,
291 ) -> Result<(), String> {
292 reader
293 .get_mut()
294 .write_all(command.as_bytes())
295 .map_err(|e| format!("POP3 write failed: {e}"))?;
296 reader
297 .get_mut()
298 .flush()
299 .map_err(|e| format!("POP3 flush failed: {e}"))?;
300 response_line(reader).map(|_| ())
301 }
302 fn multiline<S: std::io::Read>(reader: &mut BufReader<S>) -> Result<Vec<String>, String> {
303 let mut lines = Vec::new();
304 loop {
305 let mut line = String::new();
306 reader
307 .read_line(&mut line)
308 .map_err(|e| format!("POP3 read failed: {e}"))?;
309 let line = line.trim_end_matches(['\r', '\n']).to_string();
310 if line == "." {
311 break;
312 }
313 lines.push(line.strip_prefix("..").unwrap_or(&line).to_string());
314 }
315 Ok(lines)
316 }
317 fn headers_and_body(lines: &[String]) -> (String, String, String, String) {
318 let mut from = String::new();
319 let mut to = String::new();
320 let mut subject = String::new();
321 let mut body_at = lines.len();
322 for (index, line) in lines.iter().enumerate() {
323 if line.is_empty() {
324 body_at = index + 1;
325 break;
326 }
327 if let Some(value) = line
328 .strip_prefix("From:")
329 .or_else(|| line.strip_prefix("from:"))
330 {
331 from = value.trim().to_string();
332 }
333 if let Some(value) = line
334 .strip_prefix("To:")
335 .or_else(|| line.strip_prefix("to:"))
336 {
337 to = value.trim().to_string();
338 }
339 if let Some(value) = line
340 .strip_prefix("Subject:")
341 .or_else(|| line.strip_prefix("subject:"))
342 {
343 subject = value.trim().to_string();
344 }
345 }
346 (from, to, subject, lines[body_at..].join("\n"))
347 }
348
349 let tcp = TcpStream::connect((cfg.host.as_str(), cfg.port))
350 .map_err(|e| format!("POP3S connect to {}:{} failed: {e}", cfg.host, cfg.port))?;
351 let tls = native_tls::TlsConnector::builder()
352 .build()
353 .map_err(|e| format!("POP3S TLS setup failed: {e}"))?;
354 let stream = tls
355 .connect(&cfg.host, tcp)
356 .map_err(|e| format!("POP3S TLS connect failed: {e}"))?;
357 let mut reader = BufReader::new(stream);
358 response_line(&mut reader)?;
359 command(&mut reader, &format!("USER {}\r\n", cfg.username))?;
360 command(&mut reader, &format!("PASS {}\r\n", cfg.password))?;
361 command(&mut reader, "UIDL\r\n")?;
362 let uids = multiline(&mut reader)?;
363 let mut messages = Vec::new();
364 for entry in uids {
365 let mut parts = entry.split_whitespace();
366 let Some(number) = parts.next() else {
367 continue;
368 };
369 let Some(uid) = parts.next() else {
370 continue;
371 };
372 command(&mut reader, &format!("RETR {number}\r\n"))?;
373 let lines = multiline(&mut reader)?;
374 let (from, mut to, subject, body) = headers_and_body(&lines);
375 if !to.contains('@') {
376 to = mailbox.to_string();
377 }
378 let inbound = build_inbound(&from, &to, &subject, body.len(), false, None);
379 messages.push(Pop3FetchedMessage {
380 uid: uid.to_string(),
381 inbound,
382 body,
383 });
384 }
385 let _ = command(&mut reader, "QUIT\r\n");
386 Ok(messages)
387}
388
389#[cfg(test)]
390mod tests {
391 use super::*;
392
393 #[test]
394 fn build_inbound_populates_fields() {
395 let msg = build_inbound(
396 "alice@example.org",
397 "me@example.org",
398 "Hello there",
399 2048,
400 true,
401 Some("did:example:alice".to_string()),
402 );
403
404 assert_eq!(msg.from_address, "alice@example.org");
405 assert_eq!(msg.to_address, "me@example.org");
406 assert_eq!(msg.subject, "Hello there");
407 assert_eq!(msg.size_bytes, 2048);
408 assert!(msg.sender_verified);
409 assert_eq!(msg.sender_did.as_deref(), Some("did:example:alice"));
410 }
411
412 #[test]
413 fn build_inbound_defaults_unverified_no_did() {
414 let msg = build_inbound("spam@nowhere.test", "junk@example.org", "", 0, false, None);
415
416 assert_eq!(msg.from_address, "spam@nowhere.test");
417 assert_eq!(msg.to_address, "junk@example.org");
418 assert_eq!(msg.subject, "");
419 assert_eq!(msg.size_bytes, 0);
420 assert!(!msg.sender_verified);
421 assert!(msg.sender_did.is_none());
422 }
423}