Skip to main content

rusted_mail/api/
message.rs

1//! Typed outgoing messages and attachments.
2
3use super::*;
4
5/// An outgoing MIME attachment.
6#[derive(Clone, Serialize)]
7#[serde(rename_all = "camelCase")]
8#[must_use]
9pub struct Attachment {
10    filename: String,
11    content_type: String,
12    #[serde(skip_serializing_if = "Option::is_none")]
13    content_id: Option<String>,
14    inline: bool,
15    #[serde(skip_serializing_if = "Option::is_none")]
16    base64: Option<String>,
17    #[serde(skip_serializing_if = "Option::is_none")]
18    path: Option<String>,
19}
20
21impl Attachment {
22    /// Creates an attachment from in-memory bytes.
23    pub fn bytes(
24        filename: impl Into<String>,
25        content_type: impl Into<String>,
26        bytes: impl AsRef<[u8]>,
27    ) -> Self {
28        Self {
29            filename: filename.into(),
30            content_type: content_type.into(),
31            content_id: None,
32            inline: false,
33            base64: Some(base64::prelude::BASE64_STANDARD.encode(bytes.as_ref())),
34            path: None,
35        }
36    }
37
38    /// Creates an attachment that will be read from a filesystem path.
39    pub fn path(
40        filename: impl Into<String>,
41        content_type: impl Into<String>,
42        path: impl AsRef<Path>,
43    ) -> Self {
44        Self {
45            filename: filename.into(),
46            content_type: content_type.into(),
47            content_id: None,
48            inline: false,
49            base64: None,
50            path: Some(path.as_ref().to_string_lossy().into_owned()),
51        }
52    }
53
54    /// Marks the attachment as inline and sets its MIME content ID.
55    pub fn inline(mut self, content_id: impl Into<String>) -> Self {
56        self.inline = true;
57        self.content_id = Some(content_id.into());
58        self
59    }
60}
61
62impl fmt::Debug for Attachment {
63    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
64        formatter
65            .debug_struct("Attachment")
66            .field("filename", &self.filename)
67            .field("content_type", &self.content_type)
68            .field("content_id", &self.content_id)
69            .field("inline", &self.inline)
70            .field("content", &self.base64.as_ref().map(|_| "[REDACTED]"))
71            .field("path", &self.path.as_ref().map(|_| "[REDACTED]"))
72            .finish()
73    }
74}
75
76/// A typed outgoing email message.
77#[derive(Debug, Clone, Serialize)]
78#[serde(rename_all = "camelCase")]
79pub struct Message {
80    #[serde(skip_serializing_if = "Option::is_none")]
81    from: Option<String>,
82    to: Vec<String>,
83    cc: Vec<String>,
84    bcc: Vec<String>,
85    reply_to: Vec<String>,
86    subject: String,
87    #[serde(skip_serializing_if = "Option::is_none")]
88    text: Option<String>,
89    #[serde(skip_serializing_if = "Option::is_none")]
90    html: Option<String>,
91    attachments: Vec<Attachment>,
92}
93
94impl Message {
95    /// Starts a message builder.
96    pub fn builder() -> MessageBuilder {
97        MessageBuilder::default()
98    }
99}
100
101/// Builder for [`Message`].
102#[derive(Debug, Clone, Default)]
103#[must_use]
104pub struct MessageBuilder {
105    from: Option<String>,
106    to: Vec<String>,
107    cc: Vec<String>,
108    bcc: Vec<String>,
109    reply_to: Vec<String>,
110    subject: String,
111    text: Option<String>,
112    html: Option<String>,
113    attachments: Vec<Attachment>,
114}
115
116impl MessageBuilder {
117    /// Sets an explicit sender address.
118    pub fn from(mut self, address: impl Into<String>) -> Self {
119        self.from = Some(address.into());
120        self
121    }
122
123    /// Adds a primary recipient.
124    pub fn to(mut self, address: impl Into<String>) -> Self {
125        self.to.push(address.into());
126        self
127    }
128
129    /// Adds a carbon-copy recipient.
130    pub fn cc(mut self, address: impl Into<String>) -> Self {
131        self.cc.push(address.into());
132        self
133    }
134
135    /// Adds a blind-carbon-copy recipient.
136    pub fn bcc(mut self, address: impl Into<String>) -> Self {
137        self.bcc.push(address.into());
138        self
139    }
140
141    /// Adds a reply-to address.
142    pub fn reply_to(mut self, address: impl Into<String>) -> Self {
143        self.reply_to.push(address.into());
144        self
145    }
146
147    /// Sets the message subject.
148    pub fn subject(mut self, subject: impl Into<String>) -> Self {
149        self.subject = subject.into();
150        self
151    }
152
153    /// Sets the plain-text body.
154    pub fn text(mut self, text: impl Into<String>) -> Self {
155        self.text = Some(text.into());
156        self
157    }
158
159    /// Sets the HTML body.
160    pub fn html(mut self, html: impl Into<String>) -> Self {
161        self.html = Some(html.into());
162        self
163    }
164
165    /// Adds a MIME attachment.
166    pub fn attachment(mut self, attachment: Attachment) -> Self {
167        self.attachments.push(attachment);
168        self
169    }
170
171    /// Validates and creates the outgoing message.
172    ///
173    /// # Errors
174    ///
175    /// Returns [`Error::InvalidRequest`](crate::Error::InvalidRequest) when no
176    /// recipient or body is provided, or when the subject is invalid.
177    pub fn build(self) -> Result<Message, Error> {
178        if self.to.is_empty() && self.cc.is_empty() && self.bcc.is_empty() {
179            return Err(invalid("at least one recipient is required"));
180        }
181        require_text("subject", &self.subject)?;
182        if self.text.is_none() && self.html.is_none() {
183            return Err(invalid("a text or HTML body is required"));
184        }
185        Ok(Message {
186            from: self.from,
187            to: self.to,
188            cc: self.cc,
189            bcc: self.bcc,
190            reply_to: self.reply_to,
191            subject: self.subject,
192            text: self.text,
193            html: self.html,
194            attachments: self.attachments,
195        })
196    }
197}