Skip to main content

aurelin_framework/mail/
message.rs

1use std::str::FromStr;
2
3use lettre::{
4    Message,
5    address::AddressError,
6    message::{Mailbox, MultiPart, SinglePart},
7};
8
9use super::MailError;
10
11#[derive(Clone, serde::Deserialize, serde::Serialize)]
12#[serde(try_from = "String", into = "String")]
13struct Address(Mailbox);
14
15impl FromStr for Address {
16    type Err = AddressError;
17
18    fn from_str(value: &str) -> Result<Self, Self::Err> {
19        value.parse().map(Self)
20    }
21}
22
23impl TryFrom<String> for Address {
24    type Error = AddressError;
25
26    fn try_from(value: String) -> Result<Self, Self::Error> {
27        value.parse()
28    }
29}
30
31impl From<Address> for String {
32    fn from(address: Address) -> Self {
33        address.0.to_string()
34    }
35}
36
37/// An application-rendered email, independent of its delivery transport.
38#[derive(Clone, serde::Deserialize, serde::Serialize)]
39pub struct MailMessage {
40    recipients: Vec<Address>,
41    subject: String,
42    text: String,
43    html: Option<String>,
44    from: Option<Address>,
45    reply_to: Vec<Address>,
46    cc: Vec<Address>,
47    bcc: Vec<Address>,
48}
49
50impl MailMessage {
51    /// Create a message with an explicit subject and rendered plain-text body.
52    pub fn new(subject: impl Into<String>, text: impl Into<String>) -> Self {
53        Self {
54            recipients: Vec::new(),
55            subject: subject.into(),
56            text: text.into(),
57            html: None,
58            from: None,
59            reply_to: Vec::new(),
60            cc: Vec::new(),
61            bcc: Vec::new(),
62        }
63    }
64
65    /// Add a recipient, validating its address.
66    pub fn to(mut self, address: &str) -> Result<Self, MailError> {
67        self.recipients.push(address.parse()?);
68        Ok(self)
69    }
70
71    /// Override the configured sender.
72    pub fn from(mut self, address: &str) -> Result<Self, MailError> {
73        self.from = Some(address.parse()?);
74        Ok(self)
75    }
76
77    /// Add a reply-to address.
78    pub fn reply_to(mut self, address: &str) -> Result<Self, MailError> {
79        self.reply_to.push(address.parse()?);
80        Ok(self)
81    }
82
83    /// Add a carbon-copy recipient.
84    pub fn cc(mut self, address: &str) -> Result<Self, MailError> {
85        self.cc.push(address.parse()?);
86        Ok(self)
87    }
88
89    /// Add a blind carbon-copy recipient.
90    pub fn bcc(mut self, address: &str) -> Result<Self, MailError> {
91        self.bcc.push(address.parse()?);
92        Ok(self)
93    }
94
95    /// Add an application-rendered HTML alternative.
96    pub fn html(mut self, html: impl Into<String>) -> Self {
97        self.html = Some(html.into());
98        self
99    }
100
101    pub(crate) fn routed_to(mut self, address: &str) -> Result<Self, MailError> {
102        self.recipients = vec![address.parse()?];
103        Ok(self)
104    }
105
106    pub(super) fn build(self, default_from: Option<Mailbox>) -> Result<Message, MailError> {
107        let from =
108            self.from.map(|address| address.0).or(default_from).ok_or(MailError::Missing("MAIL_FROM_ADDRESS"))?;
109        let mut builder = Message::builder().from(from).subject(self.subject);
110        for address in self.recipients {
111            builder = builder.to(address.0);
112        }
113        for address in self.reply_to {
114            builder = builder.reply_to(address.0);
115        }
116        for address in self.cc {
117            builder = builder.cc(address.0);
118        }
119        for address in self.bcc {
120            builder = builder.bcc(address.0);
121        }
122        Ok(match self.html {
123            Some(html) => builder.multipart(MultiPart::alternative_plain_html(self.text, html))?,
124            None => builder.singlepart(SinglePart::plain(self.text))?,
125        })
126    }
127}