Skip to main content

turnloop_smtp/
message.rs

1//! Deterministic lettre message building. Caller supplies Date, Message-ID and
2//! MIME boundary seed; this wrapper never calls lettre's clock/random defaults.
3use crate::{Error, error};
4pub use lettre::{
5    Message,
6    message::{Attachment, Mailbox, MultiPart, SinglePart, header},
7};
8use std::time::SystemTime;
9pub struct FileAttachment {
10    pub filename: String,
11    pub content_type: String,
12    pub content: Vec<u8>,
13}
14pub struct Mail {
15    pub from: Mailbox,
16    pub to: Vec<Mailbox>,
17    pub cc: Vec<Mailbox>,
18    pub bcc: Vec<Mailbox>,
19    pub subject: String,
20    pub text: Option<String>,
21    pub html: Option<String>,
22    pub attachments: Vec<FileAttachment>,
23    pub headers: Vec<(String, String)>,
24    pub date: SystemTime,
25    pub message_id: String,
26    /// ASCII alphanumeric seed, 1..=48 bytes. Caller ensures it is absent from
27    /// content; derived mixed/alternative boundaries are distinct.
28    pub boundary_seed: String,
29}
30fn bad(message: &str) -> Error {
31    error("EMESSAGE", "API", message, None, "")
32}
33fn multipart(kind: &str, seed: &str) -> Result<lettre::message::MultiPartBuilder, Error> {
34    let content_type = header::ContentType::parse(&format!(
35        "multipart/{kind}; boundary=\"turnloop-{kind}-{seed}\""
36    ))
37    .map_err(|e| bad(&e.to_string()))?;
38    Ok(MultiPart::builder().header(content_type))
39}
40pub fn build(mut mail: Mail) -> Result<Message, Error> {
41    if mail.boundary_seed.is_empty()
42        || mail.boundary_seed.len() > 48
43        || !mail
44            .boundary_seed
45            .bytes()
46            .all(|b| b.is_ascii_alphanumeric())
47    {
48        return Err(bad("Invalid MIME boundary seed"));
49    }
50    if mail.message_id.is_empty() || mail.message_id.contains(['\r', '\n']) {
51        return Err(bad("Invalid Message-ID"));
52    }
53    let mut builder = Message::builder()
54        .from(mail.from)
55        .subject(mail.subject)
56        .date(mail.date)
57        .message_id(Some(mail.message_id));
58    for to in mail.to {
59        builder = builder.to(to);
60    }
61    for cc in mail.cc {
62        builder = builder.cc(cc);
63    }
64    for bcc in mail.bcc {
65        builder = builder.bcc(bcc);
66    }
67    for (name, value) in mail.headers {
68        if value.contains(['\r', '\n'])
69            || [
70                "date",
71                "message-id",
72                "from",
73                "to",
74                "cc",
75                "bcc",
76                "mime-version",
77                "content-type",
78                "content-transfer-encoding",
79            ]
80            .iter()
81            .any(|reserved| name.eq_ignore_ascii_case(reserved))
82        {
83            return Err(bad("Invalid or reserved custom header"));
84        }
85        let name = header::HeaderName::new_from_ascii(name).map_err(|e| bad(&e.to_string()))?;
86        builder = builder.raw_header(header::HeaderValue::new(name, value));
87    }
88    let alternative = mail.text.is_some() && mail.html.is_some();
89    let parts = if alternative {
90        Some(
91            multipart("alternative", &mail.boundary_seed)?
92                .singlepart(SinglePart::plain(mail.text.take().unwrap()))
93                .singlepart(SinglePart::html(mail.html.take().unwrap())),
94        )
95    } else {
96        None
97    };
98    if mail.attachments.is_empty() {
99        if let Some(parts) = parts {
100            builder.multipart(parts)
101        } else if let Some(html) = mail.html {
102            builder.singlepart(SinglePart::html(html))
103        } else {
104            builder.singlepart(SinglePart::plain(mail.text.unwrap_or_default()))
105        }
106    } else {
107        let mixed = multipart("mixed", &mail.boundary_seed)?;
108        let mut mixed = if let Some(parts) = parts {
109            mixed.multipart(parts)
110        } else if let Some(html) = mail.html {
111            mixed.singlepart(SinglePart::html(html))
112        } else {
113            mixed.singlepart(SinglePart::plain(mail.text.unwrap_or_default()))
114        };
115        for attachment in mail.attachments {
116            let content_type = header::ContentType::parse(&attachment.content_type)
117                .map_err(|e| bad(&e.to_string()))?;
118            mixed = mixed.singlepart(
119                Attachment::new(attachment.filename).body(attachment.content, content_type),
120            );
121        }
122        builder.multipart(mixed)
123    }
124    .map_err(|e| bad(&e.to_string()))
125}