mail_list/
email_builder.rs1use std::str::FromStr;
2
3use lettre::{Address, message::Mailbox};
4
5use crate::{MailListError, MailListResult};
6
7#[derive(Default, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
8pub struct EmailEnvelopeDetails {
9 pub to: (String, String),
10 pub subject: String,
11 pub body: String,
12 pub from: (String, String),
13 pub reply_to: (String, String),
14}
15
16impl EmailEnvelopeDetails {
17 pub fn new() -> Self {
18 Self::default()
19 }
20
21 pub fn set_to(mut self, to_name: &str, to_address: &str) -> MailListResult<Self> {
22 Mailbox::new(
23 Some(to_name.to_string()),
24 to_address
25 .parse::<Address>()
26 .map_err(|error| MailListError::Mailer(error.to_string()))?,
27 );
28 self.to = (to_name.to_string(), to_address.to_string());
29
30 Ok(self)
31 }
32
33 pub fn set_subject(mut self, subject: &str) -> Self {
34 self.subject = subject.to_string();
35
36 self
37 }
38
39 pub fn set_body(mut self, body: &str) -> Self {
40 self.body = body.to_string();
41
42 self
43 }
44
45 pub fn set_from(mut self, from_name: &str, from_address: &str) -> MailListResult<Self> {
46 Mailbox::new(
47 Some(from_name.to_string()),
48 from_address
49 .parse::<Address>()
50 .map_err(|error| MailListError::Mailer(error.to_string()))?,
51 );
52
53 self.reply_to = (from_name.to_string(), from_address.to_string());
54
55 Ok(self)
56 }
57
58 pub fn set_reply_to(
59 mut self,
60 reply_to_name: &str,
61 reply_to_address: &str,
62 ) -> MailListResult<Self> {
63 Mailbox::new(
64 Some(reply_to_name.to_string()),
65 reply_to_address
66 .parse::<Address>()
67 .map_err(|error| MailListError::Mailer(error.to_string()))?,
68 );
69
70 self.reply_to = (reply_to_name.to_string(), reply_to_address.to_string());
71
72 Ok(self)
73 }
74
75 pub fn from_as_mailbox(&self) -> Mailbox {
76 Mailbox::new(
77 Some(self.from.0.clone()),
78 Address::from_str(self.from.1.as_str()).unwrap(),
79 )
80 }
81
82 pub fn reply_as_mailbox(&self) -> Mailbox {
83 Mailbox::new(
84 Some(self.from.0.clone()),
85 Address::from_str(self.from.1.as_str()).unwrap(),
86 )
87 }
88
89 pub fn to_as_mailbox(&self) -> Mailbox {
90 Mailbox::new(
91 Some(self.from.0.clone()),
92 Address::from_str(self.from.1.as_str()).unwrap(),
93 )
94 }
95
96 pub fn from(&self) -> (&str, &str) {
97 (self.from.0.as_str(), self.from.1.as_str())
98 }
99
100 pub fn reply_to(&self) -> (&str, &str) {
101 (self.reply_to.0.as_str(), self.reply_to.1.as_str())
102 }
103
104 pub fn to(&self) -> (&str, &str) {
105 (self.to.0.as_str(), self.to.1.as_str())
106 }
107}
108
109#[cfg(test)]
110mod sanity_checks {
111 use crate::EmailEnvelopeDetails;
112
113 #[test]
114 fn smtps_builder() {
115 EmailEnvelopeDetails::new()
116 .set_from("Jane Doe [Automated]", "janedoe@example.com")
117 .unwrap()
118 .set_reply_to("Jane Doe", "janedoe@example.com")
119 .unwrap()
120 .set_to("Jonh Doe", "johndoe@example.com")
121 .unwrap()
122 .set_body("As systems normal");
123 }
124}