/ justapi / crates / justapi-py / src / message_builder.rs
swadhinbiswas 📝 docs: update PLAN/DECISIONS/AGENTS for 2.0.8 progress · 7/25/2026
be80cc4
64 lines · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::PyDict;

use justapi_core::mail::{Attachment, EmailAddress, EmailMessage};

pub fn build_message(
    to: String,
    subject: String,
    body: Option<String>,
    html: Option<String>,
    cc: Option<Vec<String>>,
    bcc: Option<Vec<String>>,
    reply_to: Option<String>,
    attachments: Option<Vec<Py<PyDict>>>,
    py: Python<'_>,
) -> PyResult<EmailMessage> {
    let to_addr = EmailAddress::new(to);
    let mut msg = EmailMessage::new(vec![to_addr], subject);

    if let Some(text) = body {
        msg = msg.text(text);
    }
    if let Some(h) = html {
        msg = msg.html(h);
    }
    if let Some(cc_list) = cc {
        let addrs: Vec<EmailAddress> = cc_list.into_iter().map(EmailAddress::new).collect();
        msg = msg.cc(addrs);
    }
    if let Some(bcc_list) = bcc {
        let addrs: Vec<EmailAddress> = bcc_list.into_iter().map(EmailAddress::new).collect();
        msg = msg.bcc(addrs);
    }
    if let Some(reply) = reply_to {
        msg = msg.reply_to(EmailAddress::new(reply));
    }
    if let Some(att_list) = attachments {
        for att_py in att_list {
            let dict: &Bound<'_, PyDict> = att_py.bind(py);
            let filename: String = dict
                .get_item("filename")?
                .ok_or_else(|| PyValueError::new_err("attachment missing 'filename'"))?
                .extract()
                .map_err(|_| PyValueError::new_err("attachment 'filename' must be a string"))?;
            let content_type: Option<String> =
                dict.get_item("content_type")?.and_then(|v| v.extract::<String>().ok());
            let data: Vec<u8> = dict
                .get_item("data")?
                .ok_or_else(|| PyValueError::new_err("attachment missing 'data'"))?
                .extract()
                .map_err(|_| PyValueError::new_err("attachment 'data' must be bytes"))?;
            let attachment = if let Some(ct) = content_type {
                Attachment::with_content_type(filename, ct, data)
            } else {
                Attachment::new(filename, data)
            };
            msg = msg.attach(attachment);
        }
    }

    Ok(msg)
}