use std::str::FromStr;
use lettre::{Address, message::Mailbox};
use crate::{MailListError, MailListResult};
#[derive(Default, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct EmailEnvelopeDetails {
pub to: (String, String),
pub subject: String,
pub body: String,
pub from: (String, String),
pub reply_to: (String, String),
}
impl EmailEnvelopeDetails {
pub fn new() -> Self {
Self::default()
}
pub fn set_to(mut self, to_name: &str, to_address: &str) -> MailListResult<Self> {
Mailbox::new(
Some(to_name.to_string()),
to_address
.parse::<Address>()
.map_err(|error| MailListError::Mailer(error.to_string()))?,
);
self.to = (to_name.to_string(), to_address.to_string());
Ok(self)
}
pub fn set_subject(mut self, subject: &str) -> Self {
self.subject = subject.to_string();
self
}
pub fn set_body(mut self, body: &str) -> Self {
self.body = body.to_string();
self
}
pub fn set_from(mut self, from_name: &str, from_address: &str) -> MailListResult<Self> {
Mailbox::new(
Some(from_name.to_string()),
from_address
.parse::<Address>()
.map_err(|error| MailListError::Mailer(error.to_string()))?,
);
self.reply_to = (from_name.to_string(), from_address.to_string());
Ok(self)
}
pub fn set_reply_to(
mut self,
reply_to_name: &str,
reply_to_address: &str,
) -> MailListResult<Self> {
Mailbox::new(
Some(reply_to_name.to_string()),
reply_to_address
.parse::<Address>()
.map_err(|error| MailListError::Mailer(error.to_string()))?,
);
self.reply_to = (reply_to_name.to_string(), reply_to_address.to_string());
Ok(self)
}
pub fn from_as_mailbox(&self) -> Mailbox {
Mailbox::new(
Some(self.from.0.clone()),
Address::from_str(self.from.1.as_str()).unwrap(),
)
}
pub fn reply_as_mailbox(&self) -> Mailbox {
Mailbox::new(
Some(self.from.0.clone()),
Address::from_str(self.from.1.as_str()).unwrap(),
)
}
pub fn to_as_mailbox(&self) -> Mailbox {
Mailbox::new(
Some(self.from.0.clone()),
Address::from_str(self.from.1.as_str()).unwrap(),
)
}
pub fn from(&self) -> (&str, &str) {
(self.from.0.as_str(), self.from.1.as_str())
}
pub fn reply_to(&self) -> (&str, &str) {
(self.reply_to.0.as_str(), self.reply_to.1.as_str())
}
pub fn to(&self) -> (&str, &str) {
(self.to.0.as_str(), self.to.1.as_str())
}
}
#[cfg(test)]
mod sanity_checks {
use crate::EmailEnvelopeDetails;
#[test]
fn smtps_builder() {
EmailEnvelopeDetails::new()
.set_from("Jane Doe [Automated]", "janedoe@example.com")
.unwrap()
.set_reply_to("Jane Doe", "janedoe@example.com")
.unwrap()
.set_to("Jonh Doe", "johndoe@example.com")
.unwrap()
.set_body("As systems normal");
}
}