Skip to main content

serenade_mailer/
mime.rs

1//! Mime body tree: how Serenade structures multipart messages.
2
3use crate::attachment::{Attachment, ContentDisposition};
4use crate::email::Email;
5
6/// Top-level Mime body layout for an [`Email`].
7///
8/// This is the framework view of multipart structure. SMTP encoding still goes
9/// through lettre when the `smtp` feature is enabled.
10#[derive(Clone, Debug, Eq, PartialEq)]
11pub enum MimeTree {
12    /// Single body part (text or HTML without nested multiparts).
13    Single(MimePart),
14    /// `multipart/alternative`: plain text plus an HTML (or related) sibling.
15    Alternative {
16        /// Plain-text sibling when present.
17        text: Option<MimePart>,
18        /// HTML sibling: either a single HTML part or `multipart/related`.
19        html: Box<Self>,
20    },
21    /// `multipart/related` wrapping HTML plus inline CID parts.
22    Related {
23        /// Root content (usually a single HTML part).
24        root: Box<Self>,
25        /// Inline parts referenced via `cid:`.
26        related: Vec<MimePart>,
27    },
28    /// `multipart/mixed` with a primary body and downloadable attachments.
29    Mixed {
30        /// Primary message body (single, alternative, or related).
31        body: Box<Self>,
32        /// Downloadable attachments.
33        attachments: Vec<MimePart>,
34    },
35}
36
37/// One leaf Mime part.
38#[derive(Clone, Debug, Eq, PartialEq)]
39pub struct MimePart {
40    /// MIME content type.
41    pub content_type: String,
42    /// Suggested filename when this is a file part.
43    pub filename: Option<String>,
44    /// Content disposition.
45    pub disposition: ContentDisposition,
46    /// Content-ID without angle brackets when inline.
47    pub content_id: Option<String>,
48    /// Decoded body bytes (UTF-8 for text parts).
49    pub body: Vec<u8>,
50}
51
52impl MimePart {
53    /// Text body part.
54    #[must_use]
55    pub fn text(body: &str) -> Self {
56        Self {
57            content_type: "text/plain; charset=utf-8".to_owned(),
58            filename: None,
59            disposition: ContentDisposition::Inline,
60            content_id: None,
61            body: body.as_bytes().to_vec(),
62        }
63    }
64
65    /// HTML body part.
66    #[must_use]
67    pub fn html(body: &str) -> Self {
68        Self {
69            content_type: "text/html; charset=utf-8".to_owned(),
70            filename: None,
71            disposition: ContentDisposition::Inline,
72            content_id: None,
73            body: body.as_bytes().to_vec(),
74        }
75    }
76
77    /// File or inline attachment part.
78    #[must_use]
79    pub fn from_attachment(attachment: &Attachment) -> Self {
80        Self {
81            content_type: attachment.content_type().to_owned(),
82            filename: Some(attachment.filename().to_owned()),
83            disposition: attachment.disposition(),
84            content_id: attachment.content_id().map(str::to_owned),
85            body: attachment.body().to_vec(),
86        }
87    }
88}
89
90impl MimeTree {
91    /// Builds the Mime tree for an email (multipart rules used by SMTP encode).
92    ///
93    /// Nesting matches common client expectations:
94    /// - text + HTML → `multipart/alternative`
95    /// - HTML + CID inline → `multipart/related` (as the HTML alternative sibling when text exists)
96    /// - downloadable files → outer `multipart/mixed`
97    #[must_use]
98    pub fn from_email(email: &Email) -> Self {
99        let inline: Vec<MimePart> = email
100            .attachments()
101            .iter()
102            .filter(|part| part.is_inline())
103            .map(MimePart::from_attachment)
104            .collect();
105        let downloadable: Vec<MimePart> = email
106            .attachments()
107            .iter()
108            .filter(|part| !part.is_inline())
109            .map(MimePart::from_attachment)
110            .collect();
111
112        let body = content_tree(email, &inline);
113        if downloadable.is_empty() {
114            body
115        } else {
116            Self::Mixed {
117                body: Box::new(body),
118                attachments: downloadable,
119            }
120        }
121    }
122
123    /// Multipart subtype at this node (`alternative`, `related`, `mixed`), if any.
124    #[must_use]
125    pub const fn multipart_subtype(&self) -> Option<&'static str> {
126        match self {
127            Self::Single(_) => None,
128            Self::Alternative { .. } => Some("alternative"),
129            Self::Related { .. } => Some("related"),
130            Self::Mixed { .. } => Some("mixed"),
131        }
132    }
133}
134
135fn content_tree(email: &Email, inline: &[MimePart]) -> MimeTree {
136    let text = email.text_part().map(MimePart::text);
137    let html = email.html_part().map(MimePart::html);
138    let html_tree = html.map(|part| {
139        let single = MimeTree::Single(part);
140        if inline.is_empty() {
141            single
142        } else {
143            MimeTree::Related {
144                root: Box::new(single),
145                related: inline.to_vec(),
146            }
147        }
148    });
149
150    match (text, html_tree) {
151        (Some(text_part), Some(html_part)) => MimeTree::Alternative {
152            text: Some(text_part),
153            html: Box::new(html_part),
154        },
155        (Some(text_part), None) => {
156            // Inline without HTML is unusual; keep CID parts under related around text.
157            if inline.is_empty() {
158                MimeTree::Single(text_part)
159            } else {
160                MimeTree::Related {
161                    root: Box::new(MimeTree::Single(text_part)),
162                    related: inline.to_vec(),
163                }
164            }
165        }
166        (None, Some(html_part)) => html_part,
167        (None, None) => MimeTree::Single(MimePart::text("")),
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use crate::Attachment;
175    use crate::Email;
176
177    #[test]
178    fn plain_only_is_single() {
179        let email = Email::new()
180            .from("a@b.test")
181            .expect("from")
182            .to("c@d.test")
183            .expect("to")
184            .subject("s")
185            .text("hi");
186        let tree = MimeTree::from_email(&email);
187        assert!(matches!(tree, MimeTree::Single(_)));
188        assert_eq!(tree.multipart_subtype(), None);
189    }
190
191    #[test]
192    fn text_and_html_are_alternative() {
193        let email = Email::new()
194            .from("a@b.test")
195            .expect("from")
196            .to("c@d.test")
197            .expect("to")
198            .subject("s")
199            .text("hi")
200            .html("<p>hi</p>");
201        let tree = MimeTree::from_email(&email);
202        assert_eq!(tree.multipart_subtype(), Some("alternative"));
203    }
204
205    #[test]
206    fn text_with_inline_without_html_is_related() {
207        let email = Email::new()
208            .from("a@b.test")
209            .expect("from")
210            .to("c@d.test")
211            .expect("to")
212            .subject("s")
213            .text("see image")
214            .embed(Attachment::inline_from_bytes(
215                "x.png",
216                "image/png",
217                "x",
218                vec![1],
219            ));
220        assert!(matches!(
221            MimeTree::from_email(&email),
222            MimeTree::Related { root, related }
223                if matches!(root.as_ref(), MimeTree::Single(_)) && related.len() == 1
224        ));
225    }
226
227    #[test]
228    fn inline_and_file_nest_related_inside_mixed() {
229        let email = Email::new()
230            .from("a@b.test")
231            .expect("from")
232            .to("c@d.test")
233            .expect("to")
234            .subject("s")
235            .html("<img src=\"cid:logo@serenade\" />")
236            .embed(Attachment::inline_from_bytes(
237                "logo.png",
238                "image/png",
239                "logo@serenade",
240                vec![1, 2, 3],
241            ))
242            .attach(Attachment::from_bytes(
243                "invoice.pdf",
244                "application/pdf",
245                vec![9],
246            ));
247        assert!(matches!(
248            MimeTree::from_email(&email),
249            MimeTree::Mixed { body, attachments }
250                if attachments.len() == 1
251                    && attachments[0].filename.as_deref() == Some("invoice.pdf")
252                    && matches!(
253                        body.as_ref(),
254                        MimeTree::Related { root, related }
255                            if related.len() == 1
256                                && related[0].content_id.as_deref() == Some("logo@serenade")
257                                && matches!(root.as_ref(), MimeTree::Single(_))
258                    )
259        ));
260    }
261
262    #[test]
263    fn text_html_inline_puts_related_under_alternative() {
264        let email = Email::new()
265            .from("a@b.test")
266            .expect("from")
267            .to("c@d.test")
268            .expect("to")
269            .subject("s")
270            .text("hi")
271            .html("<img src=\"cid:x\" />")
272            .embed(Attachment::inline_from_bytes(
273                "x.png",
274                "image/png",
275                "x",
276                vec![1],
277            ));
278        assert!(matches!(
279            MimeTree::from_email(&email),
280            MimeTree::Alternative { text: Some(_), html }
281                if html.multipart_subtype() == Some("related")
282        ));
283    }
284}