agent-first-mail 0.2.1

Let your AI agent work your inbox — email pulled into plain files it reads, sorts, and drafts on your machine, with nothing sent until you confirm.
Documentation
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
use crate::config::{MailConfig, SmtpConfig};
use crate::error::{AppError, Result};
use crate::frontmatter::{CaseFrontmatter, DraftFrontmatter};
use crate::mail::parse_outbound_message_with_status;
use crate::markdown::read_doc;
use crate::types::CaseMessages;
#[cfg(test)]
use crate::types::{MessageAuthentication, MessageFile};
use crate::util::{write_bytes_atomic, write_json_pretty};
use lettre::address::{Address, Envelope};
use lettre::message::{header, Attachment, Mailbox, Message, MultiPart, SinglePart};
use lettre::transport::smtp::authentication::Credentials;
use lettre::{SmtpTransport, Transport};
use sanitize_filename::{sanitize_with_options, Options as SanitizeFilenameOptions};
use std::fs;
use std::path::{Path, PathBuf};

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PreparedOutbound {
    pub message_id: String,
    pub raw: Vec<u8>,
    pub envelope_from: String,
    pub envelope_to: Vec<String>,
}

pub fn prepare_outbound(
    root: &Path,
    case_path: &Path,
    case_uid: &str,
    draft_name: &str,
    config: &MailConfig,
    existing_message_id: Option<&str>,
) -> Result<PreparedOutbound> {
    let message_id = existing_message_id
        .map(ToString::to_string)
        .unwrap_or_else(|| unique_outbound_id(root));
    let message = build_draft_message(root, case_path, case_uid, draft_name, config, &message_id)?;
    let raw = message.formatted();
    let envelope = message.envelope();
    let envelope_from = envelope
        .from()
        .map(ToString::to_string)
        .ok_or_else(|| AppError::new("draft_invalid", "draft envelope from is required"))?;
    let envelope_to = envelope
        .to()
        .iter()
        .map(ToString::to_string)
        .collect::<Vec<_>>();
    Ok(PreparedOutbound {
        message_id,
        raw,
        envelope_from,
        envelope_to,
    })
}

pub fn message_id_for_push(push_id: &str) -> String {
    let suffix = push_id
        .strip_prefix("push_")
        .unwrap_or(push_id)
        .chars()
        .map(|ch| {
            if ch.is_ascii_alphanumeric() || ch == '_' || ch == '-' {
                ch
            } else {
                '_'
            }
        })
        .collect::<String>();
    format!("message_sent_{suffix}")
}

pub fn mark_sent_and_append_case(
    root: &Path,
    case_path: &Path,
    case_uid: &str,
    message_id: &str,
    raw: &[u8],
    _config: &MailConfig,
) -> Result<()> {
    let sent = crate::store::now_rfc3339();
    let parsed = parse_outbound_message_with_status(
        message_id.to_string(),
        raw,
        case_uid.to_string(),
        "case".to_string(),
        Some(sent),
    )?;
    let messages_dir = root.join(".afmail/messages");
    fs::create_dir_all(&messages_dir).map_err(|e| AppError::io("create messages dir", &e))?;
    write_bytes_atomic(
        &messages_dir.join(format!("{message_id}.eml")),
        raw,
        "write sent eml",
    )?;
    crate::store::Workspace::at(root).write_message_artifacts(&parsed.message)?;
    let mut case_data = read_case_messages(case_path, case_uid)?;
    let added_rfc3339 = parsed
        .message
        .sent_rfc3339
        .clone()
        .unwrap_or_else(crate::store::now_rfc3339);
    case_data.upsert_item(
        message_id,
        parsed.message.subject.as_deref(),
        &added_rfc3339,
    );
    update_case_metadata_after_append(case_path, &case_data)?;
    crate::store::Workspace::at(root).render_refresh()?;
    Ok(())
}

pub fn send_raw_message(
    config: &MailConfig,
    envelope_from: &str,
    envelope_to: &[String],
    raw: &[u8],
) -> Result<()> {
    let smtp = config.require_smtp()?;
    let sender = build_transport(&smtp)?;
    let from = envelope_from
        .parse::<Address>()
        .map_err(|e| AppError::new("smtp_send_failed", format!("invalid envelope from: {e}")))?;
    let mut to = Vec::new();
    for address in envelope_to {
        to.push(address.parse::<Address>().map_err(|e| {
            AppError::new(
                "smtp_send_failed",
                format!("invalid envelope recipient: {e}"),
            )
        })?);
    }
    let envelope = Envelope::new(Some(from), to)
        .map_err(|e| AppError::new("smtp_send_failed", e.to_string()))?;
    sender
        .send_raw(&envelope, raw)
        .map_err(|e| AppError::new("smtp_send_failed", e.to_string()))?;
    Ok(())
}

fn build_draft_message(
    root: &Path,
    case_path: &Path,
    case_uid: &str,
    draft_name: &str,
    config: &MailConfig,
    message_id: &str,
) -> Result<Message> {
    let draft_path = case_path.join("drafts").join(draft_name);
    let draft_text = fs::read_to_string(&draft_path).map_err(|e| AppError::io("read draft", &e))?;
    let (fm, raw_body) = read_doc::<DraftFrontmatter>(&draft_text)?;
    let body = raw_body.trim_start().to_string();
    let from = config.require_from()?;
    let rfc822_message_id = format!("<{message_id}@afmail.local>");
    build_message(
        root,
        case_path,
        case_uid,
        &fm,
        &body,
        &from,
        &rfc822_message_id,
    )
}

fn build_message(
    root: &Path,
    case_path: &Path,
    case_uid: &str,
    fm: &DraftFrontmatter,
    body: &str,
    from: &str,
    rfc822_message_id: &str,
) -> Result<Message> {
    if fm.case_uid != case_uid {
        return Err(AppError::new(
            "draft_invalid",
            "draft case_uid does not match case",
        ));
    }
    let mut builder = Message::builder()
        .from(parse_mailbox(from, "from")?)
        .message_id(Some(rfc822_message_id.to_string()))
        .subject(
            fm.subject
                .clone()
                .ok_or_else(|| AppError::new("draft_invalid", "draft subject is required"))?,
        );
    for to in &fm.to {
        builder = builder.to(parse_mailbox(to, "to")?);
    }
    for cc in &fm.cc {
        builder = builder.cc(parse_mailbox(cc, "cc")?);
    }
    if let Some(reply_id) = fm.reply_to_message_id.as_ref() {
        let headers = reply_headers(root, reply_id)?;
        builder = builder
            .in_reply_to(headers.in_reply_to)
            .references(headers.references);
    }
    let attachments = &fm.attachments;
    if attachments.is_empty() {
        return builder
            .header(header::ContentType::TEXT_PLAIN)
            .body(body.to_string())
            .map_err(|e| AppError::new("draft_invalid", e.to_string()));
    }
    let mut multipart = MultiPart::mixed().singlepart(SinglePart::plain(body.to_string()));
    for attachment in attachments {
        let path = draft_attachment_path(case_path, attachment)?;
        let data = fs::read(&path).map_err(|e| AppError::io("read draft attachment", &e))?;
        let raw_filename = path
            .file_name()
            .and_then(|s| s.to_str())
            .map(ToString::to_string)
            .ok_or_else(|| AppError::new("draft_invalid", "invalid attachment file name"))?;
        let filename = safe_outbound_attachment_filename(&raw_filename);
        let content_type_str = mime_guess::from_path(&filename)
            .first_raw()
            .unwrap_or("application/octet-stream");
        let content_type = header::ContentType::parse(content_type_str)
            .map_err(|e| AppError::new("draft_invalid", e.to_string()))?;
        multipart = multipart.singlepart(Attachment::new(filename).body(data, content_type));
    }
    builder
        .multipart(multipart)
        .map_err(|e| AppError::new("draft_invalid", e.to_string()))
}

fn draft_attachment_path(case_path: &Path, attachment: &str) -> Result<PathBuf> {
    let path = Path::new(attachment);
    if attachment.trim().is_empty() || path.is_absolute() {
        return Err(AppError::new(
            "draft_invalid",
            format!("invalid draft attachment path: {attachment}"),
        ));
    }
    let mut safe = PathBuf::new();
    for component in path.components() {
        match component {
            std::path::Component::Normal(part) => safe.push(part),
            _ => {
                return Err(AppError::new(
                    "draft_invalid",
                    format!("invalid draft attachment path: {attachment}"),
                ))
            }
        }
    }
    if safe.as_os_str().is_empty() {
        return Err(AppError::new(
            "draft_invalid",
            format!("invalid draft attachment path: {attachment}"),
        ));
    }
    Ok(case_path.join(safe))
}

fn safe_outbound_attachment_filename(filename: &str) -> String {
    let sanitized = sanitize_with_options(
        filename.trim(),
        SanitizeFilenameOptions {
            windows: true,
            truncate: true,
            replacement: "_",
        },
    );
    if sanitized.trim().is_empty() {
        "attachment".to_string()
    } else {
        sanitized.trim().to_string()
    }
}

fn build_transport(config: &SmtpConfig) -> Result<SmtpTransport> {
    let mut builder = if config.tls_wrapper {
        SmtpTransport::relay(&config.host)
            .map_err(|e| AppError::new("smtp_connect_failed", e.to_string()))?
            .port(config.port)
    } else if config.starttls {
        SmtpTransport::starttls_relay(&config.host)
            .map_err(|e| AppError::new("smtp_connect_failed", e.to_string()))?
            .port(config.port)
    } else {
        SmtpTransport::builder_dangerous(&config.host).port(config.port)
    };
    if let (Some(username), Some(password)) = (&config.username, &config.password_secret) {
        builder = builder.credentials(Credentials::new(username.clone(), password.clone()));
    }
    Ok(builder.build())
}

fn parse_mailbox(value: &str, field: &str) -> Result<Mailbox> {
    value
        .parse::<Mailbox>()
        .map_err(|e| AppError::new("draft_invalid", format!("invalid {field} address: {e}")))
}

struct ReplyHeaders {
    in_reply_to: String,
    references: String,
}

/// Build RFC 5322 threading headers for a reply to `message_id`.
/// `In-Reply-To` is the parent's own Message-ID; `References` is the parent's
/// own References chain plus the parent's Message-ID appended.
fn reply_headers(root: &Path, message_id: &str) -> Result<ReplyHeaders> {
    let message = crate::store::Workspace::at(root).read_message_by_id(message_id)?;
    let parent_id = message.rfc822_message_id.ok_or_else(|| {
        AppError::new(
            "draft_invalid",
            format!("reply message has no rfc822_message_id: {message_id}"),
        )
    })?;
    let mut refs = message.references.clone();
    if !refs.contains(&parent_id) {
        refs.push(parent_id.clone());
    }
    let references = refs
        .iter()
        .map(|id| ensure_brackets(id))
        .collect::<Vec<_>>()
        .join(" ");
    Ok(ReplyHeaders {
        in_reply_to: ensure_brackets(&parent_id),
        references,
    })
}

/// Wrap a bare message-id in angle brackets unless it already has them.
fn ensure_brackets(id: &str) -> String {
    let trimmed = id.trim();
    if trimmed.starts_with('<') && trimmed.ends_with('>') {
        trimmed.to_string()
    } else {
        format!("<{trimmed}>")
    }
}

fn unique_outbound_id(root: &Path) -> String {
    let base = format!(
        "message_sent_{}",
        crate::store::now_rfc3339().replace([':', '-'], "")
    );
    let dir = root.join(".afmail/messages");
    if !dir.join(format!("{base}.json")).exists() {
        return base;
    }
    for i in 1..1000 {
        let candidate = format!("{base}_{i}");
        if !dir.join(format!("{candidate}.json")).exists() {
            return candidate;
        }
    }
    base
}

fn read_case_messages(case_path: &Path, case_uid: &str) -> Result<CaseMessages> {
    let path = case_path.join("data").join("case.json");
    let data = fs::read_to_string(&path).map_err(|e| AppError::io("read case metadata", &e))?;
    let messages: CaseMessages =
        serde_json::from_str(&data).map_err(|e| AppError::json("parse case metadata", &e))?;
    if messages.schema_name != crate::types::CASE_SCHEMA_NAME
        || messages.schema_version != crate::types::MESSAGE_COLLECTION_SCHEMA_VERSION
        || messages.collection_uid != case_uid
    {
        return Err(AppError::new(
            "case_metadata_invalid",
            "invalid case metadata schema",
        ));
    }
    Ok(messages)
}

fn update_case_metadata_after_append(case_path: &Path, case: &CaseMessages) -> Result<()> {
    let path = case_path.join("data").join("case.json");
    let mut updated: CaseFrontmatter = case.clone();
    updated.updated_rfc3339 = Some(crate::store::now_rfc3339());
    updated.normalize(
        crate::types::CASE_SCHEMA_NAME,
        &case.collection_uid,
        &case.collection_name,
    );
    write_json_pretty(&path, &updated)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn temp_root(name: &str) -> PathBuf {
        let stamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        std::env::temp_dir().join(format!("afmail-smtp-{name}-{}-{stamp}", std::process::id()))
    }

    fn draft(text: &str) -> DraftFrontmatter {
        crate::markdown::parse_frontmatter(text).unwrap_or_default()
    }

    #[test]
    fn builds_plain_draft_message() {
        let root = temp_root("build");
        let case_path = root.join("cases/open/c20260521001");
        let _ = fs::create_dir_all(case_path.join("drafts"));
        let fm = draft(
            "kind: draft\ncase_uid: c20260521001\nto:\n  - alice@example.com\nsubject: Hello",
        );
        let msg = build_message(
            &root,
            &case_path,
            "c20260521001",
            &fm,
            "Hi",
            "Me <me@example.com>",
            "<msg@example.com>",
        );
        assert!(msg.is_ok());
        let raw = msg
            .map(|m| String::from_utf8(m.formatted()).unwrap_or_default())
            .unwrap_or_default();
        assert!(raw.contains("Subject: Hello"));
        assert!(raw.contains("Hi"));
        assert!(raw.contains("Message-ID: <msg@example.com>"));
        let _ = fs::remove_dir_all(root);
    }

    fn write_parent(root: &Path, message_id: &str, rfc822_id: &str, references: &[&str]) {
        let msg = MessageFile {
            schema_name: "message".to_string(),
            schema_version: 1,
            message_id: message_id.to_string(),
            rfc822_message_id: Some(rfc822_id.to_string()),
            in_reply_to: None,
            references: references.iter().map(|s| s.to_string()).collect(),
            remote: None,
            direction: Some("inbound".to_string()),
            subject: Some("Hi".to_string()),
            from: Some("a@example.com".to_string()),
            to: Vec::new(),
            cc: Vec::new(),
            bcc: Vec::new(),
            reply_to: Vec::new(),
            sender: None,
            delivered_to: Vec::new(),
            x_original_to: Vec::new(),
            envelope_to: Vec::new(),
            list_id: None,
            mailing_list_headers: Vec::new(),
            authentication: MessageAuthentication::default(),
            received_rfc3339: None,
            sent_rfc3339: None,
            body_text: String::new(),
            eml_path: None,
            attachments: Vec::new(),
            workspace: crate::types::WorkspaceState {
                status: "triage".to_string(),
                archive_uid: None,
                archived_rfc3339: None,
                origin: None,
                remote_sync: None,
                push: None,
            },
        };
        let _ = crate::store::Workspace::at(root).write_message_materialized_cache(&msg);
    }

    #[test]
    fn reply_builds_full_references_chain() {
        let root = temp_root("reply-chain");
        let case_path = root.join("cases/open/c20260521001");
        let _ = fs::create_dir_all(case_path.join("drafts"));
        // Parent already carries a References chain (bracket-less, as stored).
        write_parent(
            &root,
            "message_p",
            "parent@example.com",
            &["root@example.com"],
        );
        let fm = draft(
            "kind: draft\ncase_uid: c20260521001\nto:\n  - a@example.com\nsubject: \"Re: Hi\"\nreply_to_message_id: message_p",
        );
        let raw = build_message(
            &root,
            &case_path,
            "c20260521001",
            &fm,
            "reply body",
            "Me <me@example.com>",
            "<reply@afmail.local>",
        )
        .map(|m| String::from_utf8(m.formatted()).unwrap_or_default())
        .unwrap_or_default();
        assert!(raw.contains("In-Reply-To: <parent@example.com>"));
        assert!(raw.contains("References: <root@example.com> <parent@example.com>"));
        let _ = fs::remove_dir_all(root);
    }

    #[test]
    fn reply_without_parent_references_falls_back_to_parent_id() {
        let root = temp_root("reply-fallback");
        let case_path = root.join("cases/open/c20260521001");
        let _ = fs::create_dir_all(case_path.join("drafts"));
        write_parent(&root, "message_p", "parent@example.com", &[]);
        let fm = draft(
            "kind: draft\ncase_uid: c20260521001\nto:\n  - a@example.com\nsubject: \"Re: Hi\"\nreply_to_message_id: message_p",
        );
        let raw = build_message(
            &root,
            &case_path,
            "c20260521001",
            &fm,
            "reply body",
            "Me <me@example.com>",
            "<reply@afmail.local>",
        )
        .map(|m| String::from_utf8(m.formatted()).unwrap_or_default())
        .unwrap_or_default();
        assert!(raw.contains("In-Reply-To: <parent@example.com>"));
        assert!(raw.contains("References: <parent@example.com>"));
        let _ = fs::remove_dir_all(root);
    }
}