1use serde::{Deserialize, Serialize};
17#[cfg(target_os = "macos")]
18use std::process::Command;
19
20use super::{Availability, IntegrationError};
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct MailAccount {
24 pub id: String,
25 pub address: String,
26 pub display_name: Option<String>,
27 pub provider_hint: Option<String>,
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct InboxSummary {
32 pub account_id: String,
33 pub unread: u32,
34 pub total: u32,
35 pub most_recent_subject: Option<String>,
36}
37
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct AccountListing {
40 #[serde(flatten)]
41 pub availability: Availability,
42 pub accounts: Vec<MailAccount>,
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct InboxListing {
47 #[serde(flatten)]
48 pub availability: Availability,
49 pub summaries: Vec<InboxSummary>,
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct SendRequest {
54 pub account_id: String,
55 pub to: Vec<String>,
56 #[serde(default)]
57 pub cc: Vec<String>,
58 #[serde(default)]
59 pub bcc: Vec<String>,
60 pub subject: String,
61 pub body: String,
62 #[serde(default)]
64 pub draft_only: bool,
65}
66
67#[derive(Debug, Clone, Serialize, Deserialize)]
68pub struct SendResult {
69 #[serde(flatten)]
70 pub availability: Availability,
71 pub sent: bool,
73 pub message_id: Option<String>,
74}
75
76pub fn list_accounts() -> Result<AccountListing, IntegrationError> {
77 backend::list_accounts()
78}
79
80pub fn list_inbox(account_ids: &[String]) -> Result<InboxListing, IntegrationError> {
83 backend::list_inbox(account_ids)
84}
85
86pub fn send(req: SendRequest) -> Result<SendResult, IntegrationError> {
88 backend::send(req)
89}
90
91#[cfg(target_os = "macos")]
92mod backend {
93 use super::*;
94
95 const JXA: &str = r#"
96function normalizeAccount(account) {
97 let name = "";
98 let id = "";
99 let addresses = [];
100 try { name = String(account.name()); } catch (e) {}
101 try { id = String(account.id()); } catch (e) {}
102 if (!id) id = name;
103 try { addresses = account.emailAddresses().map(String); } catch (e) {}
104 return {
105 id: id,
106 address: addresses[0] || name,
107 display_name: name || null,
108 provider_hint: null
109 };
110}
111
112function accountMatches(account, requested) {
113 if (requested.length === 0) return true;
114 const normalized = normalizeAccount(account);
115 return requested.indexOf(normalized.id) >= 0 || requested.indexOf(normalized.address) >= 0 || requested.indexOf(normalized.display_name || "") >= 0;
116}
117
118function mailApp() {
119 const app = Application("/System/Applications/Mail.app");
120 app.includeStandardAdditions = true;
121 return app;
122}
123
124function run(argv) {
125 const mode = argv[0] || "accounts";
126 let Mail;
127 try {
128 Mail = mailApp();
129 } catch (e) {
130 return JSON.stringify({available:false, backend:"mail_app", reason:String(e), accounts:[], summaries:[], sent:false, message_id:null});
131 }
132
133 if (mode === "accounts") {
134 try {
135 return JSON.stringify({available:true, backend:"mail_app", reason:null, accounts: Mail.accounts().map(normalizeAccount)});
136 } catch (e) {
137 return JSON.stringify({available:false, backend:"mail_app", reason:String(e), accounts:[]});
138 }
139 }
140
141 if (mode === "inbox") {
142 const requested = argv.slice(1);
143 const summaries = [];
144 try {
145 Mail.accounts().forEach(account => {
146 if (!accountMatches(account, requested)) return;
147 const normalized = normalizeAccount(account);
148 let unread = 0;
149 let total = 0;
150 let subject = null;
151 try {
152 const inbox = account.mailboxes.byName("INBOX");
153 const messages = inbox.messages();
154 total = messages.length;
155 for (let i = 0; i < messages.length; i++) {
156 const message = messages[i];
157 try { if (message.readStatus() === false) unread += 1; } catch (e) {}
158 if (subject === null) {
159 try { subject = String(message.subject()); } catch (e) {}
160 }
161 }
162 } catch (e) {}
163 summaries.push({account_id: normalized.id, unread: unread, total: total, most_recent_subject: subject});
164 });
165 return JSON.stringify({available:true, backend:"mail_app", reason:null, summaries:summaries});
166 } catch (e) {
167 return JSON.stringify({available:false, backend:"mail_app", reason:String(e), summaries:[]});
168 }
169 }
170
171 if (mode === "send") {
172 try {
173 const req = JSON.parse(argv[1] || "{}");
174 const msg = Mail.OutgoingMessage({
175 subject: req.subject || "",
176 content: req.body || "",
177 visible: false
178 });
179 Mail.outgoingMessages.push(msg);
180 (req.to || []).forEach(address => msg.toRecipients.push(Mail.Recipient({address: String(address)})));
181 (req.cc || []).forEach(address => msg.ccRecipients.push(Mail.Recipient({address: String(address)})));
182 (req.bcc || []).forEach(address => msg.bccRecipients.push(Mail.Recipient({address: String(address)})));
183 if (req.account_id) {
184 const accounts = Mail.accounts();
185 for (let i = 0; i < accounts.length; i++) {
186 const normalized = normalizeAccount(accounts[i]);
187 if (normalized.id === req.account_id || normalized.address === req.account_id || normalized.display_name === req.account_id) {
188 try { msg.sender(normalized.address); } catch (e) {}
189 break;
190 }
191 }
192 }
193 if (req.draft_only) {
194 msg.save();
195 } else {
196 msg.send();
197 }
198 let messageId = null;
199 try { messageId = String(msg.id()); } catch (e) {}
200 return JSON.stringify({available:true, backend:"mail_app", reason:null, sent:true, message_id:messageId});
201 } catch (e) {
202 return JSON.stringify({available:false, backend:"mail_app", reason:String(e), sent:false, message_id:null});
203 }
204 }
205
206 return JSON.stringify({available:false, backend:"mail_app", reason:"unknown mail mode", accounts:[], summaries:[], sent:false, message_id:null});
207}
208"#;
209
210 pub fn list_accounts() -> Result<AccountListing, IntegrationError> {
211 let mail_listing: AccountListing = run_jxa(&["accounts"])?;
212 if mail_listing.availability.available || !mail_listing.accounts.is_empty() {
213 return Ok(mail_listing);
214 }
215
216 let accounts = car_accounts::list()
217 .map_err(|e| IntegrationError::Backend(format!("accounts fallback: {e}")))?
218 .accounts
219 .into_iter()
220 .filter(|account| account.capabilities.iter().any(|cap| cap == "mail"))
221 .map(|account| MailAccount {
222 id: account.id,
223 address: account.identifier.unwrap_or(account.label.clone()),
224 display_name: Some(account.label),
225 provider_hint: Some(account.provider),
226 })
227 .collect();
228
229 Ok(AccountListing {
230 availability: Availability::available("internet_accounts"),
231 accounts,
232 })
233 }
234
235 pub fn list_inbox(account_ids: &[String]) -> Result<InboxListing, IntegrationError> {
236 let mut args = vec!["inbox"];
237 args.extend(account_ids.iter().map(String::as_str));
238 run_jxa(&args)
239 }
240
241 pub fn send(req: SendRequest) -> Result<SendResult, IntegrationError> {
242 let req_json = serde_json::to_string(&req)
243 .map_err(|e| IntegrationError::Backend(format!("mail request json: {e}")))?;
244 run_jxa(&["send", req_json.as_str()])
245 }
246
247 fn run_jxa<T: serde::de::DeserializeOwned>(args: &[&str]) -> Result<T, IntegrationError> {
248 let output = Command::new("/usr/bin/osascript")
249 .arg("-l")
250 .arg("JavaScript")
251 .arg("-")
252 .args(args)
253 .stdin(std::process::Stdio::piped())
254 .stdout(std::process::Stdio::piped())
255 .stderr(std::process::Stdio::piped())
256 .spawn()
257 .and_then(|mut child| {
258 use std::io::Write;
259 if let Some(stdin) = child.stdin.as_mut() {
260 stdin.write_all(JXA.as_bytes())?;
261 }
262 child.wait_with_output()
263 })
264 .map_err(|e| IntegrationError::Backend(format!("osascript: {e}")))?;
265
266 if !output.status.success() {
267 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
268 return Err(IntegrationError::Backend(format!(
269 "mail osascript failed: {stderr}"
270 )));
271 }
272
273 serde_json::from_slice(&output.stdout)
274 .map_err(|e| IntegrationError::Backend(format!("mail json: {e}")))
275 }
276}
277
278#[cfg(not(target_os = "macos"))]
279mod backend {
280 use super::*;
281
282 pub fn list_accounts() -> Result<AccountListing, IntegrationError> {
283 Ok(AccountListing {
284 availability: current_backend_pending(),
285 accounts: vec![],
286 })
287 }
288
289 pub fn list_inbox(_account_ids: &[String]) -> Result<InboxListing, IntegrationError> {
290 Ok(InboxListing {
291 availability: current_backend_pending(),
292 summaries: vec![],
293 })
294 }
295
296 pub fn send(_req: SendRequest) -> Result<SendResult, IntegrationError> {
297 Ok(SendResult {
298 availability: current_backend_pending(),
299 sent: false,
300 message_id: None,
301 })
302 }
303
304 fn current_backend_pending() -> Availability {
305 Availability::pending(
306 "imap_smtp",
307 "Mail requires IMAP/SMTP client + per-OS Mail app inspection, \
308 not yet wired. Depends on car-accounts (which accounts to use) \
309 and car-secrets (credentials). API shape is stable.",
310 )
311 }
312}