1use std::fs;
4use std::path::{Path, PathBuf};
5use std::time::{SystemTime, UNIX_EPOCH};
6
7use crate::null::validate_for_send;
8use crate::render::render_message;
9use crate::{Email, MailerError, Transport};
10
11#[derive(Clone, Debug)]
13pub struct FileTransport {
14 directory: PathBuf,
15}
16
17impl FileTransport {
18 #[must_use]
20 pub fn new(directory: impl Into<PathBuf>) -> Self {
21 Self {
22 directory: directory.into(),
23 }
24 }
25
26 #[must_use]
28 pub fn directory(&self) -> &Path {
29 &self.directory
30 }
31}
32
33impl Transport for FileTransport {
34 fn send(&self, email: &Email) -> Result<(), MailerError> {
35 validate_for_send(email)?;
36 fs::create_dir_all(&self.directory).map_err(|error| MailerError::Io {
37 message: error.to_string(),
38 })?;
39 let nanos = SystemTime::now()
40 .duration_since(UNIX_EPOCH)
41 .map_or(0, |duration| duration.as_nanos());
42 let path = self.directory.join(format!("{nanos}.message"));
43 let body = render_message(email);
44 fs::write(&path, body).map_err(|error| MailerError::Io {
45 message: error.to_string(),
46 })?;
47 Ok(())
48 }
49}