Skip to main content

qualia_client_core/api/
mail.rs

1//! Local mail product (inbox + SMTP receiver)
2
3#![allow(non_snake_case)]
4
5/// List all locally configured interoperable mail accounts. Account labels and
6/// addresses provide provenance when their mail is harmonised into one inbox.
7pub fn mail_accounts() -> Result<serde_json::Value, String> {
8    let accounts: Vec<serde_json::Value> = crate::mail_accounts::list()
9        .into_iter()
10        .map(|account| {
11            serde_json::json!({
12                "id": account.id,
13                "label": account.label,
14                "address": account.address,
15                "smtp_configured": account.smtp.is_some(),
16                "imap_configured": account.imap.is_some(),
17                "pop3_configured": account.pop3.is_some(),
18            })
19        })
20        .collect();
21    Ok(serde_json::Value::Array(accounts))
22}
23
24/// Add or replace one account. This is intentionally local configuration; it
25/// makes no network request and does not fetch mail until the user asks to.
26pub fn save_mail_account(
27    account: crate::mail_accounts::MailAccount,
28) -> Result<serde_json::Value, String> {
29    crate::mail_accounts::save(account)?;
30    mail_accounts()
31}
32
33/// Send through one specifically selected, locally configured SMTP account.
34/// Credentials never leave the account store or appear in the response.
35#[cfg(not(target_arch = "wasm32"))]
36pub fn mail_send_account(
37    account_id: String,
38    to: String,
39    subject: String,
40    body: String,
41) -> Result<serde_json::Value, String> {
42    let account = crate::mail_accounts::find(&account_id)
43        .ok_or_else(|| "The configured mail account was not found.".to_string())?;
44    let smtp = account
45        .smtp
46        .as_ref()
47        .ok_or_else(|| "This account has no SMTP submission settings.".to_string())?;
48    let recipient = to.trim();
49    if recipient.is_empty() || subject.trim().is_empty() || body.trim().is_empty() {
50        return Err("Recipient, subject, and message are required.".to_string());
51    }
52    let message = crate::mail_transport::OutgoingMail {
53        from: account.address.clone(),
54        to: recipient.to_string(),
55        subject: subject.trim().to_string(),
56        body: body.trim().to_string(),
57    };
58    crate::mail_transport::send(smtp, &message)?;
59    Ok(serde_json::json!({
60        "account_id": account.id,
61        "account_label": account.label,
62        "from": account.address,
63        "to": message.to,
64        "subject": message.subject,
65        "sent": true,
66    }))
67}
68
69/// Fetch one configured account into the governed local inbox. The account
70/// label is recorded on every accepted import so a unified inbox never loses
71/// where a message came from. SMTP-only accounts have nothing to retrieve.
72#[cfg(not(target_arch = "wasm32"))]
73pub fn mail_fetch_account(id: String) -> Result<serde_json::Value, String> {
74    let account = crate::mail_accounts::find(&id)
75        .ok_or_else(|| "The configured mail account was not found.".to_string())?;
76    let mut imported = 0usize;
77    let mut rejected = 0usize;
78    if let Some(imap) = account.imap.as_ref() {
79        for message in crate::mail_transport::fetch_unseen(imap, "INBOX")? {
80            let to = if message.to_address.contains('@') {
81                message.to_address.clone()
82            } else {
83                account.address.clone()
84            };
85            let result = crate::mail_inbound::accept_message(
86                &message.from_address,
87                &to,
88                &message.subject,
89                &format!("(imported via IMAP; size {} bytes)", message.size_bytes),
90                false,
91                None,
92            );
93            if let Some(stored) = result.stored {
94                crate::mail_store::set_source_account(&stored.id, &account.label)?;
95                imported += 1;
96            } else {
97                rejected += 1;
98            }
99        }
100    } else if let Some(pop3) = account.pop3.as_ref() {
101        for message in crate::mail_transport::fetch_pop3(pop3, &account.address)? {
102            if crate::mail_accounts::has_pop3_receipt(&account.id, &message.uid) {
103                continue;
104            }
105            let result = crate::mail_inbound::accept_message(
106                &message.inbound.from_address,
107                &message.inbound.to_address,
108                &message.inbound.subject,
109                &message.body,
110                false,
111                None,
112            );
113            if let Some(stored) = result.stored {
114                crate::mail_store::set_source_account(&stored.id, &account.label)?;
115                imported += 1;
116            } else {
117                rejected += 1;
118            }
119            // Record both accepted and rejected deliveries. Re-evaluating a
120            // rejected POP3 message on every poll is neither useful nor fair.
121            crate::mail_accounts::record_pop3_receipt(&account.id, &message.uid)?;
122        }
123    } else {
124        return Err(
125            "This account has SMTP only; configure IMAP or POP3S to retrieve mail.".to_string(),
126        );
127    }
128    Ok(
129        serde_json::json!({ "account_id": account.id, "account_label": account.label, "imported": imported, "rejected": rejected }),
130    )
131}
132
133/// Fetch all accounts explicitly configured for incoming mail. Failures are
134/// reported per account so one provider outage cannot hide other accounts.
135#[cfg(not(target_arch = "wasm32"))]
136pub fn mail_fetch_all_accounts() -> Result<serde_json::Value, String> {
137    let accounts = crate::mail_accounts::list();
138    let mut results = Vec::with_capacity(accounts.len());
139    for account in accounts {
140        if account.imap.is_none() && account.pop3.is_none() {
141            continue;
142        }
143        let id = account.id.clone();
144        match mail_fetch_account(id) { Ok(result) => results.push(result), Err(error) => results.push(serde_json::json!({ "account_id": account.id, "account_label": account.label, "error": error })) }
145    }
146    Ok(serde_json::json!({ "results": results }))
147}
148
149/// Accept a message into the local inbox (same path as SMTP DATA) — for tests and mesh inject.
150pub fn mail_accept(
151    from: String,
152    to: String,
153    subject: String,
154    body: String,
155    sender_verified: bool,
156) -> Result<serde_json::Value, String> {
157    let r = crate::mail_inbound::accept_message(&from, &to, &subject, &body, sender_verified, None);
158    serde_json::to_value(r).map_err(|e| e.to_string())
159}
160
161/// List local inbox messages (newest first).
162pub fn mail_list(
163    mailbox: Option<String>,
164    include_quarantine: Option<bool>,
165) -> Result<serde_json::Value, String> {
166    let inc = include_quarantine.unwrap_or(true);
167    let list = crate::mail_store::list(mailbox.as_deref(), inc);
168    let (total, unread, quarantine) = crate::mail_store::counts();
169    Ok(serde_json::json!({
170        "messages": list,
171        "counts": { "total": total, "unread": unread, "quarantine": quarantine },
172    }))
173}
174
175/// Gets a mail message.
176pub fn mail_get(id: String) -> Result<serde_json::Value, String> {
177    let m = crate::mail_store::get(&id).ok_or_else(|| format!("unknown message '{id}'"))?;
178    serde_json::to_value(m).map_err(|e| e.to_string())
179}
180
181/// Marks mail read.
182pub fn mail_set_read(id: String, read: bool) -> Result<serde_json::Value, String> {
183    let m = crate::mail_store::set_read(&id, read)?;
184    serde_json::to_value(m).map_err(|e| e.to_string())
185}
186
187/// Deletes mail.
188pub fn mail_delete(id: String) -> Result<serde_json::Value, String> {
189    crate::mail_store::delete(&id)?;
190    Ok(serde_json::json!({ "deleted": id }))
191}
192
193/// MX/SPF paste block + local receiver status for a domain.
194pub fn mail_dns_forms(
195    domain: String,
196    mx_host: Option<String>,
197) -> Result<serde_json::Value, String> {
198    Ok(crate::mail_inbound::mail_dns_forms(
199        &domain,
200        mx_host.as_deref(),
201    ))
202}
203
204/// Mail receiver status.
205pub fn mail_receiver_status() -> Result<serde_json::Value, String> {
206    Ok(crate::mail_inbound::receiver_status())
207}
208
209/// Start local SMTP receiver (default `127.0.0.1:2525`). Use `0.0.0.0:2525` for LAN/tunnel.
210#[cfg(not(target_arch = "wasm32"))]
211pub fn mail_receiver_start(bind: Option<String>) -> Result<serde_json::Value, String> {
212    let b = bind.unwrap_or_default();
213    crate::mail_inbound::start_receiver(&b)
214}
215
216#[cfg(not(target_arch = "wasm32"))]
217/// Stops the mail receiver.
218pub fn mail_receiver_stop() -> Result<serde_json::Value, String> {
219    crate::mail_inbound::stop_receiver()
220}