Skip to main content

rmut_core/
compose.rs

1//! Draft building and finalizing for outgoing mail.
2
3use std::path::{Path, PathBuf};
4
5use anyhow::{Context, Result, ensure};
6use chrono::{Local, TimeZone};
7
8use crate::pattern::Me;
9
10pub struct DraftHeaders {
11    /// From line when an identity override applies (reverse_name, a
12    /// folder/recipient rule, the account); the user can edit it, and
13    /// finalize falls back to the default identity when absent.
14    pub from: Option<String>,
15    pub to: String,
16    pub cc: Option<String>,
17    pub subject: String,
18    pub in_reply_to: Option<String>,
19    pub references: Option<String>,
20}
21
22/// The text the user edits in $EDITOR: header block, blank line, body.
23pub fn draft_text(h: &DraftHeaders, body: &str) -> String {
24    let mut out = String::new();
25    if let Some(from) = &h.from {
26        out += &format!("From: {from}\n");
27    }
28    out += &format!("To: {}\n", h.to);
29    if let Some(cc) = &h.cc
30        && !cc.trim().is_empty()
31    {
32        out += &format!("Cc: {cc}\n");
33    }
34    out += &format!("Subject: {}\n", h.subject);
35    if let Some(x) = &h.in_reply_to {
36        out += &format!("In-Reply-To: {x}\n");
37    }
38    if let Some(x) = &h.references {
39        out += &format!("References: {x}\n");
40    }
41    out.push('\n');
42    out.push_str(body);
43    if !out.ends_with('\n') {
44        out.push('\n');
45    }
46    out
47}
48
49/// mutt's $attribution: the line a quoted reply opens with.
50pub const DEFAULT_ATTRIBUTION: &str = "On %d, %n wrote:";
51
52/// mutt's $forward_format: the subject a forward carries.
53pub const DEFAULT_FORWARD_FORMAT: &str = "[%a: %s]";
54
55/// mutt's $indent_string: what a quoted line is prefixed with.
56pub const DEFAULT_INDENT: &str = "> ";
57
58/// The message an attribution or a forward subject is about, for the
59/// format strings that describe it.
60pub struct Quoted<'a> {
61    /// The From header as written, name and address together.
62    pub from: &'a str,
63    pub subject: &'a str,
64    pub message_id: Option<&'a str>,
65    /// When it was sent, seconds since the epoch.
66    pub date: i64,
67}
68
69impl Quoted<'_> {
70    /// The author's display name, or their address when the header
71    /// carries no name (as mutt's %n does).
72    fn name(&self) -> String {
73        let trimmed = self.from.trim();
74        let name = match trimmed.split_once('<') {
75            Some((name, _)) => name.trim().trim_matches('"').trim(),
76            None => "",
77        };
78        match name.is_empty() {
79            true => self.address(),
80            false => name.to_string(),
81        }
82    }
83
84    fn address(&self) -> String {
85        bare_address(self.from).unwrap_or_else(|| self.from.trim().to_string())
86    }
87}
88
89/// Expand one of mutt's message format strings: `%a` the author's
90/// address, `%n` their name, `%s` the subject, `%i` the message-id,
91/// `%d` the date, `%{...}` the date through strftime, `%%` a percent.
92/// Padding and conditionals work as they do in the index format.
93pub fn render_quoted(fmt: &str, m: &Quoted) -> String {
94    // `%{...}` first: the strftime span would confuse the specifier
95    // machinery, which reads one character.
96    let fmt = expand_strftime(fmt, m.date);
97    crate::format::render_with(&fmt, &|spec| match spec {
98        'a' => m.address(),
99        'n' => m.name(),
100        'f' => m.from.trim().to_string(),
101        's' => m.subject.trim().to_string(),
102        'i' => m
103            .message_id
104            .unwrap_or_default()
105            .trim_matches(['<', '>'])
106            .to_string(),
107        'd' => format_date(m.date),
108        '%' => "%".to_string(),
109        other => format!("%{other}"),
110    })
111}
112
113/// mutt's `%{strftime}`: the message's date, in the caller's words.
114fn expand_strftime(fmt: &str, date: i64) -> String {
115    let mut out = String::new();
116    let mut rest = fmt;
117    while let Some(at) = rest.find("%{") {
118        out.push_str(&rest[..at]);
119        let Some(end) = rest[at + 2..].find('}') else {
120            break;
121        };
122        let spec = &rest[at + 2..at + 2 + end];
123        out.push_str(&strftime(spec, date));
124        rest = &rest[at + 2 + end + 1..];
125    }
126    out.push_str(rest);
127    out
128}
129
130fn strftime(spec: &str, epoch: i64) -> String {
131    match Local.timestamp_opt(epoch, 0) {
132        chrono::LocalResult::Single(dt) | chrono::LocalResult::Ambiguous(dt, _) => {
133            dt.format(spec).to_string()
134        }
135        chrono::LocalResult::None => String::new(),
136    }
137}
138
139/// mutt's $reply_regexp default: "Re:" with an optional bracketed
140/// count, as Re[2]: has it.
141pub const REPLY_REGEXP: &str = r"^(re)(\[[0-9]+\])*:[ \t]*";
142
143/// Compile a $reply_regexp the way mutt does: case-insensitively
144/// unless the pattern itself has an uppercase letter (mutt's
145/// mutt_which_case).
146pub fn reply_regexp(spec: &str) -> Result<regex_lite::Regex, regex_lite::Error> {
147    let smart = if spec.chars().any(char::is_uppercase) {
148        spec.to_string()
149    } else {
150        format!("(?i){spec}")
151    };
152    regex_lite::Regex::new(&smart)
153}
154
155pub fn default_reply_regexp() -> regex_lite::Regex {
156    reply_regexp(REPLY_REGEXP).expect("default reply_regexp compiles")
157}
158
159/// The subject of a reply, as mutt makes it: "Re: " over the original
160/// with whatever $reply_regexp matched at its start taken off, so an
161/// "RE: x" or "Re[2]: x" answers as "Re: x" rather than piling up.
162pub fn reply_subject(orig: &str, re: &regex_lite::Regex) -> String {
163    let t = orig.trim();
164    let rest = match re.find(t) {
165        Some(m) if m.start() == 0 => t[m.end()..].trim_start(),
166        _ => t,
167    };
168    format!("Re: {rest}")
169}
170
171/// mutt's $forward_format over the message being forwarded.
172pub fn forward_subject(fmt: &str, m: &Quoted) -> String {
173    render_quoted(fmt, m)
174}
175
176fn format_date(epoch: i64) -> String {
177    match Local.timestamp_opt(epoch, 0) {
178        chrono::LocalResult::Single(dt) | chrono::LocalResult::Ambiguous(dt, _) => {
179            dt.format("%a, %d %b %Y %H:%M").to_string()
180        }
181        chrono::LocalResult::None => "an unknown date".into(),
182    }
183}
184
185/// mutt's $attribution over the message being replied to.
186pub fn attribution(fmt: &str, m: &Quoted) -> String {
187    render_quoted(fmt, m)
188}
189
190/// Quote a body mutt-style under an attribution line, each line
191/// prefixed with $indent_string.
192pub fn quote(attribution: &str, indent: &str, body: &str) -> String {
193    let mut out = format!("{attribution}\n");
194    for line in body.lines() {
195        out += &format!("{indent}{line}\n");
196    }
197    out
198}
199
200/// The forwarded original between mutt's markers. With mutt's
201/// $forward_quote the message itself is prefixed with $indent_string,
202/// the way a reply is quoted; the markers stay flush, since they are
203/// rmut's words and not the original's.
204pub fn forward_body(
205    from: &str,
206    date_epoch: i64,
207    subject: &str,
208    body: &str,
209    quote_with: Option<&str>,
210) -> String {
211    let body = body.trim_end();
212    let body = match quote_with {
213        Some(indent) => body
214            .lines()
215            .map(|l| format!("{indent}{l}"))
216            .collect::<Vec<_>>()
217            .join("\n"),
218        None => body.to_string(),
219    };
220    format!(
221        "----- Forwarded message from {from} -----\nDate: {}\nSubject: {subject}\n\n{body}\n----- End forwarded message -----\n",
222        format_date(date_epoch),
223    )
224}
225
226/// mutt's $signature: the text a draft ends with. A name ending in
227/// `|` is a command whose standard output is the signature (mutt's
228/// rule); anything else is a file. A signature that cannot be read is
229/// no signature: a draft is worth more than the ornament on it.
230pub fn signature_text(setting: &str) -> Option<String> {
231    let setting = setting.trim();
232    if setting.is_empty() {
233        return None;
234    }
235    let text = match setting.strip_suffix('|') {
236        Some(command) => {
237            let out = std::process::Command::new("sh")
238                .arg("-c")
239                .arg(command.trim())
240                .output()
241                .ok()?;
242            String::from_utf8_lossy(&out.stdout).into_owned()
243        }
244        None => std::fs::read_to_string(expand_home(setting)).ok()?,
245    };
246    let text = text.trim_end_matches('\n');
247    (!text.is_empty()).then(|| text.to_string())
248}
249
250/// The body with the signature under it, mutt's way: a blank line,
251/// then $sig_dashes' "-- " line when it is on, then the signature.
252pub fn with_signature(body: &str, signature: &str, dashes: bool) -> String {
253    with_signature_at(body, signature, dashes, false)
254}
255
256/// The signature added to a draft. mutt's $sig_on_top puts it above
257/// the quoted original instead of below (with a blank line between,
258/// so the reply is written between the signature and the quote).
259pub fn with_signature_at(body: &str, signature: &str, dashes: bool, on_top: bool) -> String {
260    let mut sig = String::new();
261    if dashes {
262        sig += "-- \n";
263    }
264    sig += signature;
265    if !sig.ends_with('\n') {
266        sig.push('\n');
267    }
268    if on_top {
269        return format!("{sig}\n{body}");
270    }
271    let mut out = body.to_string();
272    if !out.is_empty() && !out.ends_with('\n') {
273        out.push('\n');
274    }
275    out.push('\n');
276    out += &sig;
277    out
278}
279
280pub fn make_message_id(hostname: &str) -> String {
281    format!(
282        "<{}.{}.rmut@{hostname}>",
283        Local::now().timestamp_millis(),
284        std::process::id(),
285    )
286}
287
288pub fn rfc2822_now() -> String {
289    Local::now().to_rfc2822()
290}
291
292fn header_present(head: &str, name: &str) -> bool {
293    head.lines().any(|l| {
294        l.get(..name.len())
295            .is_some_and(|k| k.eq_ignore_ascii_case(name))
296            && l.as_bytes().get(name.len()) == Some(&b':')
297    })
298}
299
300/// Finalize an edited draft for sending: require a recipient, add
301/// mutt's $user_agent header, when the caller asks for it.
302pub fn user_agent_header() -> String {
303    format!("User-Agent: rmut/{}", env!("CARGO_PKG_VERSION"))
304}
305
306/// From/Date/Message-ID when the user didn't write them.
307pub fn finalize(draft: &str, from: &str, msg_id: &str, date: &str) -> Result<String> {
308    finalize_with(draft, from, msg_id, date, false)
309}
310
311/// Like `finalize`, adding a `User-Agent` header when `user_agent`
312/// and the draft has none of its own.
313pub fn finalize_with(
314    draft: &str,
315    from: &str,
316    msg_id: &str,
317    date: &str,
318    user_agent: bool,
319) -> Result<String> {
320    let (head, body) = draft.split_once("\n\n").unwrap_or((draft.trim_end(), ""));
321    let has_recipients = head.lines().any(|l| {
322        l.split_once(':').is_some_and(|(k, v)| {
323            ["to", "cc", "bcc"].contains(&k.trim().to_lowercase().as_str()) && !v.trim().is_empty()
324        })
325    });
326    ensure!(has_recipients, "no recipients (To/Cc/Bcc)");
327    let mut head = head.trim_end().to_string();
328    if !header_present(&head, "From") {
329        head += &format!("\nFrom: {from}");
330    }
331    if !header_present(&head, "Date") {
332        head += &format!("\nDate: {date}");
333    }
334    if !header_present(&head, "Message-ID") {
335        head += &format!("\nMessage-ID: {msg_id}");
336    }
337    if user_agent && !header_present(&head, "User-Agent") {
338        head += &format!("\n{}", user_agent_header());
339    }
340    Ok(format!("{head}\n\n{body}"))
341}
342
343/// A file named in an `Attach:` pseudo-header of the draft.
344pub struct Attachment {
345    pub path: PathBuf,
346    /// Content-type override (compose menu ctrl+t); guessed from the
347    /// extension otherwise.
348    pub mime: Option<String>,
349    pub description: Option<String>,
350    /// mutt's rename-attachment: the filename the part is sent under,
351    /// when not the file's own. `@name="..."` on the line.
352    pub name: Option<String>,
353    /// mutt's toggle-disposition: Content-Disposition inline rather
354    /// than attachment. `@inline` on the line.
355    pub inline: bool,
356    /// mutt's toggle-unlink: the file goes once the message has been
357    /// sent. `@unlink` on the line.
358    pub unlink: bool,
359}
360
361impl Attachment {
362    /// A plain attachment of this file: nothing overridden.
363    pub fn of(path: PathBuf) -> Attachment {
364        Attachment {
365            path,
366            mime: None,
367            description: None,
368            name: None,
369            inline: false,
370            unlink: false,
371        }
372    }
373
374    /// The filename the part goes out under.
375    pub fn send_name(&self) -> &str {
376        self.name
377            .as_deref()
378            .filter(|n| !n.is_empty())
379            .unwrap_or_else(|| {
380                self.path
381                    .file_name()
382                    .and_then(|n| n.to_str())
383                    .unwrap_or("attachment")
384            })
385    }
386}
387
388/// A `type/subtype` token (letters, digits, `.+-`), so a content-type
389/// between the path and the description is recognizable.
390fn looks_like_mime(token: &str) -> bool {
391    match token.split_once('/') {
392        Some((t, s)) if !t.is_empty() && !s.is_empty() => token
393            .chars()
394            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '.' | '+' | '-')),
395        _ => false,
396    }
397}
398
399/// One Attach: line back from its parts (quotes around a path with
400/// spaces, then the optional type and description).
401pub fn attach_line(a: &Attachment) -> String {
402    let p = a.path.display().to_string();
403    let mut line = if p.contains(' ') {
404        format!("Attach: \"{p}\"")
405    } else {
406        format!("Attach: {p}")
407    };
408    if let Some(m) = &a.mime {
409        line += &format!(" {m}");
410    }
411    // The @-options sit between the type and the description, where
412    // a description is not expected to start with an @.
413    if let Some(n) = a.name.as_deref().filter(|n| !n.is_empty()) {
414        line += &format!(" @name=\"{}\"", n.replace('"', ""));
415    }
416    if a.inline {
417        line += " @inline";
418    }
419    if a.unlink {
420        line += " @unlink";
421    }
422    if let Some(d) = &a.description {
423        line += &format!(" {d}");
424    }
425    line
426}
427
428/// Pull mutt-style `Attach: <path> [type/subtype] [description]`
429/// pseudo-headers out of a draft's header block; quotes allow a path
430/// with spaces, `~/` means $HOME. Returns the draft without those
431/// lines.
432pub fn extract_attachments(draft: &str) -> (String, Vec<Attachment>) {
433    let (head, body) = match draft.split_once("\n\n") {
434        Some((h, b)) => (h, Some(b)),
435        None => (draft, None),
436    };
437    let mut attachments = Vec::new();
438    let mut kept = Vec::new();
439    for line in head.lines() {
440        let value = match line.split_once(':') {
441            Some((k, v)) if k.trim().eq_ignore_ascii_case("attach") => v.trim(),
442            _ => {
443                kept.push(line);
444                continue;
445            }
446        };
447        if value.is_empty() {
448            continue;
449        }
450        let (path, desc) = match value.strip_prefix('"') {
451            Some(rest) => rest.split_once('"').unwrap_or((rest, "")),
452            None => value.split_once(char::is_whitespace).unwrap_or((value, "")),
453        };
454        let mut desc = desc.trim();
455        let mut mime = None;
456        match desc.split_once(char::is_whitespace) {
457            Some((first, rest)) if looks_like_mime(first) => {
458                mime = Some(first.to_string());
459                desc = rest.trim();
460            }
461            None if looks_like_mime(desc) => {
462                mime = Some(desc.to_string());
463                desc = "";
464            }
465            _ => {}
466        }
467        // The @-options, in any order, ahead of the description.
468        let mut a = Attachment::of(expand_home(path));
469        a.mime = mime;
470        while let Some(rest) = desc.strip_prefix('@') {
471            if let Some(rest) = rest.strip_prefix("inline") {
472                a.inline = true;
473                desc = rest.trim_start();
474            } else if let Some(rest) = rest.strip_prefix("unlink") {
475                a.unlink = true;
476                desc = rest.trim_start();
477            } else if let Some(rest) = rest.strip_prefix("name=") {
478                let (name, rest) = match rest.strip_prefix('"') {
479                    Some(q) => q.split_once('"').unwrap_or((q, "")),
480                    None => rest.split_once(char::is_whitespace).unwrap_or((rest, "")),
481                };
482                a.name = (!name.is_empty()).then(|| name.to_string());
483                desc = rest.trim_start();
484            } else {
485                break; // a description that happens to start with @
486            }
487        }
488        a.description = (!desc.is_empty()).then(|| desc.to_string());
489        attachments.push(a);
490    }
491    let mut out = kept.join("\n");
492    if let Some(body) = body {
493        out += "\n\n";
494        out += body;
495    }
496    (out, attachments)
497}
498
499fn expand_home(path: &str) -> PathBuf {
500    if let Some(rest) = path.strip_prefix("~/")
501        && let Ok(home) = std::env::var("HOME")
502    {
503        return Path::new(&home).join(rest);
504    }
505    PathBuf::from(path)
506}
507
508/// Content type guessed from the filename extension.
509pub fn content_type(path: &Path) -> &'static str {
510    let ext = path
511        .extension()
512        .and_then(|e| e.to_str())
513        .map(|e| e.to_ascii_lowercase());
514    match ext.as_deref() {
515        Some("txt" | "log" | "md" | "patch" | "diff") => "text/plain",
516        Some("html" | "htm") => "text/html",
517        Some("csv") => "text/csv",
518        Some("pdf") => "application/pdf",
519        Some("png") => "image/png",
520        Some("jpg" | "jpeg") => "image/jpeg",
521        Some("gif") => "image/gif",
522        Some("zip") => "application/zip",
523        Some("gz") => "application/gzip",
524        Some("tar") => "application/x-tar",
525        Some("json") => "application/json",
526        Some("xml") => "application/xml",
527        _ => "application/octet-stream",
528    }
529}
530
531/// Base64 in MIME shape: 76-character lines, CRLF line endings.
532fn b64_wrapped(bytes: &[u8]) -> String {
533    let s = crate::smtp::b64(bytes);
534    let mut out = String::with_capacity(s.len() + s.len() / 38 + 2);
535    for chunk in s.as_bytes().chunks(76) {
536        out.push_str(std::str::from_utf8(chunk).expect("base64 is ascii"));
537        out.push_str("\r\n");
538    }
539    out
540}
541
542/// The text/plain entity of an outgoing message: its Content-Type
543/// header and the body in canonical CRLF form. With mutt's
544/// $text_flowed the part is declared `format=flowed` and the body is
545/// space-stuffed, so a reader may rewrap it (RFC 3676). The
546/// paragraphs are the editor's doing: rmut adds no trailing spaces.
547pub fn text_entity(body: &str, flowed: bool) -> String {
548    let mut out = String::from("Content-Type: text/plain; charset=utf-8");
549    if flowed {
550        out += "; format=flowed";
551    }
552    out += "\r\nContent-Transfer-Encoding: 8bit\r\n\r\n";
553    let body = match flowed {
554        true => crate::flowed::space_stuff(body),
555        false => body.to_string(),
556    };
557    out += &String::from_utf8_lossy(&crate::pgp::crlf(body.as_bytes()));
558    out
559}
560
561/// mutt's $text_flowed for a message that goes out with no MIME
562/// wrapper at all: declare the body and space-stuff it, in place, on
563/// a finalized draft. One that already carries a Content-Type (the
564/// user wrote their own) is left alone.
565pub fn flow_plain(text: &str) -> String {
566    let (head, body) = match text.split_once("\n\n") {
567        Some(pair) => pair,
568        None => return text.to_string(),
569    };
570    if header_present(head, "Content-Type") {
571        return text.to_string();
572    }
573    format!(
574        "{}\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8; format=flowed\n\
575         Content-Transfer-Encoding: 8bit\n\n{}",
576        head.trim_end(),
577        crate::flowed::space_stuff(body),
578    )
579}
580
581/// The MIME entity (Content-Type header + body, CRLF endings) for a
582/// draft body with attachments: multipart/mixed with the text first,
583/// files base64-encoded, and optionally the forwarded original as
584/// message/rfc822 (mutt's mime_forward). The caller puts it under the
585/// draft's top-level headers, or inside a PGP layer.
586pub fn mixed_entity(
587    body: &str,
588    files: &[Attachment],
589    original: Option<&[u8]>,
590    flowed: bool,
591) -> Result<String> {
592    let mut parts: Vec<String> = Vec::new();
593    parts.push(text_entity(body, flowed));
594    for a in files {
595        let bytes =
596            std::fs::read(&a.path).with_context(|| format!("reading {}", a.path.display()))?;
597        let mime = a.mime.as_deref().unwrap_or_else(|| content_type(&a.path));
598        let disposition = if a.inline { "inline" } else { "attachment" };
599        // An attached message (mutt's attach-message) goes in as it
600        // is, a message/rfc822 part with no encoding and no filename.
601        if mime.eq_ignore_ascii_case("message/rfc822") {
602            let mut p =
603                format!("Content-Type: message/rfc822\r\nContent-Disposition: {disposition}\r\n");
604            if let Some(d) = &a.description {
605                p += &format!("Content-Description: {d}\r\n");
606            }
607            p += "\r\n";
608            p += &String::from_utf8_lossy(&crate::pgp::crlf(&bytes));
609            parts.push(p);
610            continue;
611        }
612        let mut p = format!(
613            "Content-Type: {mime}\r\nContent-Disposition: {disposition}; filename=\"{}\"\r\n",
614            a.send_name(),
615        );
616        if let Some(d) = &a.description {
617            p += &format!("Content-Description: {d}\r\n");
618        }
619        p += "Content-Transfer-Encoding: base64\r\n\r\n";
620        p += &b64_wrapped(&bytes);
621        parts.push(p);
622    }
623    if let Some(orig) = original {
624        let mut p =
625            String::from("Content-Type: message/rfc822\r\nContent-Disposition: attachment\r\n\r\n");
626        p += &String::from_utf8_lossy(&crate::pgp::crlf(orig));
627        parts.push(p);
628    }
629    let boundary = {
630        let mut n = 0usize;
631        loop {
632            let b = format!("=-rmut-mixed-{}-{n}", std::process::id());
633            if !parts.iter().any(|p| p.contains(&b)) {
634                break b;
635            }
636            n += 1;
637        }
638    };
639    let mut out = format!("Content-Type: multipart/mixed; boundary=\"{boundary}\"\r\n\r\n");
640    for p in &parts {
641        out += &format!("--{boundary}\r\n");
642        out += p;
643        if !out.ends_with("\r\n") {
644            out += "\r\n";
645        }
646    }
647    out += &format!("--{boundary}--\r\n");
648    Ok(out)
649}
650
651/// Message text for a bounce: the original with a fresh Resent-* block
652/// prepended, per RFC 5322 (the newest resend goes first).
653pub fn bounce_text(original: &[u8], from: &str, to: &str, date: &str, msg_id: &str) -> String {
654    format!(
655        "Resent-From: {from}\r\nResent-Date: {date}\r\nResent-Message-ID: {msg_id}\r\nResent-To: {to}\r\n{}",
656        String::from_utf8_lossy(original),
657    )
658}
659
660/// First address in an RFC 5322 address field, without display name,
661/// e.g. the SMTP envelope sender from a From line.
662/// The posting address from a List-Post header value:
663/// `<mailto:dev@example.com>`, with the RFC 2369 `NO` meaning the list
664/// takes no posts. Extra mailto parameters are dropped.
665pub fn list_post_address(value: &str) -> Option<String> {
666    let value = value.trim();
667    if value.eq_ignore_ascii_case("NO") {
668        return None;
669    }
670    let start = value.to_ascii_lowercase().find("mailto:")? + "mailto:".len();
671    let rest = &value[start..];
672    let addr = rest
673        .split(['>', '?', ',', ' '])
674        .next()
675        .unwrap_or(rest)
676        .trim();
677    (!addr.is_empty()).then(|| addr.to_string())
678}
679
680/// mutt's $followup_to: the Mail-Followup-To for a message going to a
681/// mailing list. Every recipient goes in; your own address is left out
682/// when you are subscribed (the list copy is the one you will get) and
683/// kept when you are not.
684pub fn followup_to(to: &str, cc: &str, me: Me, subscribed: bool, my_from: &str) -> String {
685    let mut out: Vec<String> = Vec::new();
686    let mut push = |single: &mailparse::SingleInfo| {
687        if subscribed && me.is_me(&single.addr) {
688            return;
689        }
690        let written = match &single.display_name {
691            Some(name) if !name.trim().is_empty() => format!("{name} <{}>", single.addr),
692            _ => single.addr.clone(),
693        };
694        if !out.iter().any(|a| a == &written) {
695            out.push(written);
696        }
697    };
698    for field in [to, cc] {
699        let Ok(list) = mailparse::addrparse(field) else {
700            continue;
701        };
702        for addr in list.iter() {
703            match addr {
704                mailparse::MailAddr::Single(single) => push(single),
705                mailparse::MailAddr::Group(group) => group.addrs.iter().for_each(&mut push),
706            }
707        }
708    }
709    if !subscribed
710        && let Some(from) = bare_address(my_from)
711        && !out
712            .iter()
713            .any(|a| bare_address(a).is_some_and(|b| b == from))
714    {
715        out.push(my_from.trim().to_string());
716    }
717    out.join(", ")
718}
719
720/// The Cc a group reply gets: everyone the original named in To and
721/// Cc, written the way they were written, minus anyone already in
722/// `to` (the sender, normally) and, unless mutt's $metoo is set, minus
723/// me. Duplicates collapse on the bare address, so a person listed in
724/// both To and Cc appears once.
725pub fn group_recipients(orig_to: &str, orig_cc: &str, to: &str, me: Me, metoo: bool) -> String {
726    let mut seen: Vec<String> = addresses(to).iter().map(|a| a.to_lowercase()).collect();
727    let mut out: Vec<String> = Vec::new();
728    let mut push = |single: &mailparse::SingleInfo| {
729        let bare = single.addr.to_lowercase();
730        if seen.contains(&bare) || (!metoo && me.is_me(&bare)) {
731            return;
732        }
733        seen.push(bare);
734        out.push(match &single.display_name {
735            Some(name) if !name.trim().is_empty() => format!("{name} <{}>", single.addr),
736            _ => single.addr.clone(),
737        });
738    };
739    for field in [orig_to, orig_cc] {
740        let Ok(list) = mailparse::addrparse(field) else {
741            continue;
742        };
743        for addr in list.iter() {
744            match addr {
745                mailparse::MailAddr::Single(single) => push(single),
746                mailparse::MailAddr::Group(group) => group.addrs.iter().for_each(&mut push),
747            }
748        }
749    }
750    out.join(", ")
751}
752
753/// A draft seen as a message, so hook patterns (`~t`, `~c`, `~s`,
754/// `~f`, ...) can be matched against outgoing mail the way mutt
755/// matches fcc-hook. `path` is where the body lives, so `~b` and `~h`
756/// still have something to read; the date is now, since the draft has
757/// no Date header yet. Bcc joins the Cc
758/// addresses, so a hook on `~c` sees a blind recipient too.
759pub fn draft_envelope(text: &str, path: &Path) -> crate::message::Envelope {
760    let (head, body) = text.split_once("\n\n").unwrap_or((text.trim_end(), ""));
761    let header = |name: &str| -> String {
762        head.lines()
763            .filter_map(|l| {
764                let (k, v) = l.split_once(':')?;
765                k.trim().eq_ignore_ascii_case(name).then(|| v.trim())
766            })
767            .collect::<Vec<_>>()
768            .join(", ")
769    };
770    let bare = |field: &str| -> Vec<String> {
771        addresses(field).iter().map(|a| a.to_lowercase()).collect()
772    };
773    let from_full = header("From");
774    crate::message::Envelope {
775        file: crate::maildir::MailFile {
776            path: path.to_path_buf(),
777            is_new: false,
778            flags: crate::maildir::Flags {
779                seen: true,
780                ..Default::default()
781            },
782            size: text.len() as u64,
783        },
784        from: crate::message::short_from(&from_full),
785        from_full,
786        subject: header("Subject"),
787        date: Local::now().timestamp(),
788        msg_id: None,
789        references: Vec::new(),
790        tagged: false,
791        to: bare(&header("To")),
792        cc: [header("Cc"), header("Bcc")]
793            .iter()
794            .flat_map(|f| bare(f))
795            .collect(),
796        lines: Some(body.lines().count()),
797        list: None,
798        label: None,
799        broken: false,
800    }
801}
802
803/// mutt's `my_hdr`: extra header lines that go on every draft. An
804/// entry naming a header the draft already carries replaces it, so
805/// `my_hdr From:` and `my_hdr Reply-To:` win over what rmut chose;
806/// To, Cc and Bcc instead gain the address, like mutt, so a standing
807/// `my_hdr Bcc: me@example.com` cannot erase a reply's recipients.
808/// Malformed entries (no colon, no name) are ignored.
809pub fn apply_my_hdr(text: &str, my_hdr: &[String]) -> String {
810    if my_hdr.is_empty() {
811        return text.to_string();
812    }
813    let (head, body) = match text.split_once("\n\n") {
814        Some((head, body)) => (head, body),
815        None => (text.trim_end(), ""),
816    };
817    let mut lines: Vec<String> = head.lines().map(String::from).collect();
818    for entry in my_hdr {
819        let Some((name, value)) = entry.split_once(':') else {
820            continue;
821        };
822        let (name, value) = (name.trim(), value.trim());
823        if name.is_empty() {
824            continue;
825        }
826        let at = lines.iter().position(|l| {
827            l.get(..name.len())
828                .is_some_and(|k| k.eq_ignore_ascii_case(name))
829                && l.as_bytes().get(name.len()) == Some(&b':')
830        });
831        let addressy = ["to", "cc", "bcc"].contains(&name.to_lowercase().as_str());
832        match at {
833            Some(i) if addressy => {
834                let old = lines[i]
835                    .split_once(':')
836                    .map(|(_, v)| v.trim().to_string())
837                    .unwrap_or_default();
838                lines[i] = if old.is_empty() {
839                    format!("{name}: {value}")
840                } else {
841                    format!("{name}: {old}, {value}")
842                };
843            }
844            Some(i) => lines[i] = format!("{name}: {value}"),
845            None => lines.push(format!("{name}: {value}")),
846        }
847    }
848    format!("{}\n\n{body}", lines.join("\n"))
849}
850
851pub fn bare_address(field: &str) -> Option<String> {
852    match mailparse::addrparse(field)
853        .ok()?
854        .into_inner()
855        .into_iter()
856        .next()?
857    {
858        mailparse::MailAddr::Single(single) => Some(single.addr),
859        mailparse::MailAddr::Group(group) => group.addrs.first().map(|a| a.addr.clone()),
860    }
861}
862
863/// The SMTP envelope sender: the bare address of the From header.
864pub fn from_address(text: &str) -> Option<String> {
865    use mailparse::MailHeaderMap;
866    let mail = mailparse::parse_mail(text.as_bytes()).ok()?;
867    bare_address(&mail.get_headers().get_first_value("From")?)
868}
869
870fn field_addresses(value: &str, out: &mut Vec<String>) {
871    let Ok(list) = mailparse::addrparse(value) else {
872        return;
873    };
874    for addr in list.iter() {
875        match addr {
876            mailparse::MailAddr::Single(single) => out.push(single.addr.clone()),
877            mailparse::MailAddr::Group(group) => {
878                out.extend(group.addrs.iter().map(|a| a.addr.clone()));
879            }
880        }
881    }
882}
883
884/// Every bare address in an RFC 5322 address field.
885pub fn addresses(field: &str) -> Vec<String> {
886    let mut out = Vec::new();
887    field_addresses(field, &mut out);
888    out
889}
890
891/// mutt's reverse_name: the first of my addresses (`alternates`
892/// included) the original was addressed to, in the form it appeared:
893/// the display name from the To/Cc header is kept.
894pub fn reverse_from(orig_to: &str, orig_cc: &str, me: Me, realname: bool) -> Option<String> {
895    let mine = |single: &mailparse::SingleInfo| -> Option<String> {
896        if !me.is_me(&single.addr) {
897            return None;
898        }
899        Some(match &single.display_name {
900            // mutt's $reverse_realname off: the address is theirs,
901            // the name stays whatever the identity says.
902            Some(name) if realname && !name.trim().is_empty() => {
903                format!("{name} <{}>", single.addr)
904            }
905            _ => single.addr.clone(),
906        })
907    };
908    for field in [orig_to, orig_cc] {
909        let Ok(list) = mailparse::addrparse(field) else {
910            continue;
911        };
912        for addr in list.iter() {
913            match addr {
914                mailparse::MailAddr::Single(single) => {
915                    if let Some(from) = mine(single) {
916                        return Some(from);
917                    }
918                }
919                mailparse::MailAddr::Group(group) => {
920                    if let Some(from) = group.addrs.iter().find_map(&mine) {
921                        return Some(from);
922                    }
923                }
924            }
925        }
926    }
927    None
928}
929
930/// SMTP envelope for a finalized draft: every To/Cc/Bcc address, and
931/// the text with Bcc headers removed (they must not go on the wire).
932pub fn smtp_envelope(text: &str) -> Result<(Vec<String>, String)> {
933    let mail = mailparse::parse_mail(text.as_bytes())?;
934    let mut rcpts = Vec::new();
935    for header in &mail.headers {
936        let key = header.get_key();
937        if ["to", "cc", "bcc"].contains(&key.to_lowercase().as_str()) {
938            field_addresses(&header.get_value(), &mut rcpts);
939        }
940    }
941    rcpts.dedup();
942    let (head, body) = text.split_once("\n\n").unwrap_or((text.trim_end(), ""));
943    let mut out = String::new();
944    let mut skipping = false;
945    for line in head.lines() {
946        if line.starts_with(' ') || line.starts_with('\t') {
947            // Folded continuation belongs to the previous header.
948            if skipping {
949                continue;
950            }
951        } else {
952            skipping = line
953                .split_once(':')
954                .is_some_and(|(k, _)| k.trim().eq_ignore_ascii_case("bcc"));
955        }
956        if !skipping {
957            out.push_str(line);
958            out.push('\n');
959        }
960    }
961    out.push('\n');
962    out.push_str(body);
963    Ok((rcpts, out))
964}
965
966#[cfg(test)]
967mod tests {
968    use super::*;
969
970    #[test]
971    fn a_forward_can_come_in_quoted() {
972        let plain = forward_body("Ann <ann@x>", 0, "hi", "one\ntwo\n", None);
973        assert!(plain.contains("\none\ntwo\n"), "{plain}");
974        let quoted = forward_body("Ann <ann@x>", 0, "hi", "one\ntwo\n", Some("> "));
975        assert!(quoted.contains("\n> one\n> two\n"), "{quoted}");
976        // The markers are rmut's words, so they stay flush.
977        assert!(quoted.starts_with("----- Forwarded message from Ann <ann@x> -----"));
978        assert!(quoted.ends_with("----- End forwarded message -----\n"));
979    }
980
981    #[test]
982    fn the_signature_sits_under_a_dashes_line() {
983        let body = with_signature("hello\n", "Ann\nx.example", true);
984        assert_eq!(body, "hello\n\n-- \nAnn\nx.example\n");
985        // nosig_dashes: the text alone, still a blank line down.
986        assert_eq!(with_signature("hello\n", "Ann", false), "hello\n\nAnn\n");
987        // An empty draft starts with the blank line all the same.
988        assert_eq!(with_signature("", "Ann", true), "\n-- \nAnn\n");
989    }
990
991    #[test]
992    fn a_signature_comes_from_a_file_or_a_command() {
993        let dir = std::env::temp_dir().join(format!("rmut-sig-{}", std::process::id()));
994        std::fs::create_dir_all(&dir).unwrap();
995        let file = dir.join("signature");
996        std::fs::write(&file, "Ann\n\n\n").unwrap();
997        // Trailing blank lines are the file's, not the signature's.
998        assert_eq!(
999            signature_text(file.to_str().unwrap()).as_deref(),
1000            Some("Ann")
1001        );
1002        assert_eq!(signature_text("echo hello|").as_deref(), Some("hello"));
1003        // Nothing readable is no signature, not an empty one.
1004        assert_eq!(signature_text(dir.join("gone").to_str().unwrap()), None);
1005        assert_eq!(signature_text("  "), None);
1006        assert_eq!(signature_text("true|"), None);
1007        std::fs::remove_dir_all(&dir).unwrap();
1008    }
1009
1010    #[test]
1011    fn list_post_addresses() {
1012        assert_eq!(
1013            list_post_address("<mailto:dev@example.com>").as_deref(),
1014            Some("dev@example.com")
1015        );
1016        assert_eq!(
1017            list_post_address("<mailto:dev@example.com?subject=help>").as_deref(),
1018            Some("dev@example.com")
1019        );
1020        assert_eq!(
1021            list_post_address("NOTE: <mailto:dev@example.com>, <http://x/post>").as_deref(),
1022            Some("dev@example.com")
1023        );
1024        // RFC 2369: a list that takes no posts, and a non-mail method.
1025        assert_eq!(list_post_address("NO"), None);
1026        assert_eq!(list_post_address("<http://example.com/post>"), None);
1027    }
1028
1029    #[test]
1030    fn followup_to_drops_me_only_when_subscribed() {
1031        let addrs = vec!["jarda@example.com".to_string()];
1032        let me = Me::addresses(&addrs);
1033        let subscribed = followup_to(
1034            "dev@example.com, Jarda <jarda@example.com>",
1035            "",
1036            me,
1037            true,
1038            "Jarda <jarda@example.com>",
1039        );
1040        assert_eq!(subscribed, "dev@example.com");
1041        let unsubscribed = followup_to(
1042            "dev@example.com",
1043            "petr@example.com",
1044            me,
1045            false,
1046            "Jarda <jarda@example.com>",
1047        );
1048        assert_eq!(
1049            unsubscribed,
1050            "dev@example.com, petr@example.com, Jarda <jarda@example.com>"
1051        );
1052        // Already listed: no second copy of my address.
1053        let once = followup_to(
1054            "dev@example.com, jarda@example.com",
1055            "",
1056            me,
1057            false,
1058            "Jarda <jarda@example.com>",
1059        );
1060        assert_eq!(once, "dev@example.com, jarda@example.com");
1061    }
1062
1063    #[test]
1064    fn group_reply_drops_me_and_the_sender() {
1065        let addrs = vec!["jarda@example.com".to_string()];
1066        let alternates = vec![crate::pattern::Matcher::new("^jp@old\\.example\\.com$")];
1067        let me = Me::new(&addrs, &alternates);
1068        let cc = group_recipients(
1069            "Team <team@example.com>, Jarda <jarda@example.com>, jp@old.example.com",
1070            "boss@example.com, team@example.com",
1071            "Petr <petr@example.com>",
1072            me,
1073            false,
1074        );
1075        // My exact address and my alternate are gone, the sender in To
1076        // is gone, and team@ appears once despite being listed twice.
1077        assert_eq!(cc, "Team <team@example.com>, boss@example.com");
1078        // $metoo keeps me on the copy.
1079        let cc = group_recipients(
1080            "team@example.com, jarda@example.com",
1081            "",
1082            "petr@example.com",
1083            me,
1084            true,
1085        );
1086        assert_eq!(cc, "team@example.com, jarda@example.com");
1087    }
1088
1089    #[test]
1090    fn text_flowed_declares_and_stuffs_the_body() {
1091        let entity = text_entity("plain\n>looks quoted\n", true);
1092        assert!(
1093            entity.starts_with("Content-Type: text/plain; charset=utf-8; format=flowed\r\n"),
1094            "{entity}"
1095        );
1096        assert!(
1097            entity.ends_with("plain\r\n >looks quoted\r\n"),
1098            "{entity:?}"
1099        );
1100        // Off, the part is what it always was.
1101        let plain = text_entity("plain\n>looks quoted\n", false);
1102        assert!(plain.starts_with("Content-Type: text/plain; charset=utf-8\r\n"));
1103        assert!(plain.ends_with("plain\r\n>looks quoted\r\n"), "{plain:?}");
1104    }
1105
1106    #[test]
1107    fn flow_plain_declares_an_unwrapped_draft() {
1108        let draft = "From: a@x\nTo: b@x\nSubject: s\n\n>quoted line\n";
1109        let out = flow_plain(draft);
1110        assert!(out.contains("Content-Type: text/plain; charset=utf-8; format=flowed\n"));
1111        assert!(out.ends_with("\n\n >quoted line\n"), "{out:?}");
1112        // A draft that declares its own type is left alone.
1113        let typed = "From: a@x\nContent-Type: text/x-diff\n\nbody\n";
1114        assert_eq!(flow_plain(typed), typed);
1115    }
1116
1117    #[test]
1118    fn draft_envelope_reads_the_header_block() {
1119        let draft = "From: Jane Doe <jane@example.com>\n\
1120                     To: Bob <BOB@work.example.com>, team@x\n\
1121                     Cc: boss@x\n\
1122                     Bcc: archive@x\n\
1123                     Subject: quarterly\n\n\
1124                     two\nlines\n";
1125        let env = draft_envelope(draft, std::path::Path::new("/tmp/draft"));
1126        assert_eq!(env.subject, "quarterly");
1127        assert_eq!(env.from_full, "Jane Doe <jane@example.com>");
1128        assert_eq!(env.to, ["bob@work.example.com", "team@x"]);
1129        // Bcc joins Cc, so a hook on ~c sees a blind recipient too.
1130        assert_eq!(env.cc, ["boss@x", "archive@x"]);
1131        assert_eq!(env.lines, Some(2));
1132        let hit = |p: &str| {
1133            crate::pattern::matches_in(
1134                &crate::pattern::parse(p).unwrap(),
1135                &env,
1136                crate::pattern::Scope::default(),
1137                None,
1138            )
1139        };
1140        assert!(hit("~t @work\\.example\\.com"));
1141        assert!(hit("~c archive@"));
1142        assert!(hit("~A"));
1143        assert!(!hit("~t nobody@"));
1144    }
1145
1146    #[test]
1147    fn my_hdr_merges_into_the_draft_head() {
1148        let draft = "From: jane@example.com\nTo: bob@x\nSubject: s\n\nbody\n";
1149        let merged = apply_my_hdr(
1150            draft,
1151            &[
1152                "Organization: Acme".to_string(),
1153                "From: Jane <jane@work.example.com>".into(),
1154                "Bcc: jane@example.com".into(),
1155                "To: archive@x".into(),
1156                "bogus".into(),
1157            ],
1158        );
1159        assert_eq!(
1160            merged,
1161            "From: Jane <jane@work.example.com>\n\
1162             To: bob@x, archive@x\n\
1163             Subject: s\n\
1164             Organization: Acme\n\
1165             Bcc: jane@example.com\n\
1166             \nbody\n"
1167        );
1168        // Nothing configured: the draft is untouched.
1169        assert_eq!(apply_my_hdr(draft, &[]), draft);
1170    }
1171
1172    /// A message sent at a known moment, for the format strings.
1173    fn quoted() -> Quoted<'static> {
1174        Quoted {
1175            from: "Jane Doe <jane@example.com>",
1176            subject: "Lunch",
1177            message_id: Some("<m1@example.com>"),
1178            // 2024-03-11 10:00:00 UTC.
1179            date: 1_710_151_200,
1180        }
1181    }
1182
1183    #[test]
1184    fn subjects_do_not_stack_prefixes() {
1185        let re = default_reply_regexp();
1186        assert_eq!(reply_subject("Lunch", &re), "Re: Lunch");
1187        assert_eq!(reply_subject("RE: Lunch", &re), "Re: Lunch");
1188        assert_eq!(reply_subject("Re[2]: Lunch", &re), "Re: Lunch");
1189        // A locale's own prefixes, and mutt's smart case: an
1190        // uppercase letter in the regex makes it exact.
1191        let aw = reply_regexp("^(re|aw|sv):[ \t]*").unwrap();
1192        assert_eq!(reply_subject("AW: Lunch", &aw), "Re: Lunch");
1193        let exact = reply_regexp("^(Re):[ \t]*").unwrap();
1194        assert_eq!(reply_subject("RE: Lunch", &exact), "Re: RE: Lunch");
1195        assert_eq!(
1196            forward_subject(DEFAULT_FORWARD_FORMAT, &quoted()),
1197            "[jane@example.com: Lunch]"
1198        );
1199    }
1200
1201    #[test]
1202    fn quote_prefixes_every_line_with_the_indent_string() {
1203        assert_eq!(
1204            quote("On X, Y wrote:", DEFAULT_INDENT, "a\nb"),
1205            "On X, Y wrote:\n> a\n> b\n"
1206        );
1207        assert_eq!(quote("head", "| ", "a"), "head\n| a\n");
1208    }
1209
1210    #[test]
1211    fn an_attribution_says_who_and_when() {
1212        let m = quoted();
1213        // The default names the author and the date it was sent.
1214        let line = attribution(DEFAULT_ATTRIBUTION, &m);
1215        assert!(line.starts_with("On "), "{line}");
1216        assert!(line.ends_with(", Jane Doe wrote:"), "{line}");
1217        // Every specifier mutt's does, and an unknown one stays put.
1218        assert_eq!(render_quoted("%a", &m), "jane@example.com");
1219        assert_eq!(render_quoted("%n", &m), "Jane Doe");
1220        assert_eq!(render_quoted("%f", &m), "Jane Doe <jane@example.com>");
1221        assert_eq!(render_quoted("%s", &m), "Lunch");
1222        assert_eq!(render_quoted("%i", &m), "m1@example.com");
1223        assert_eq!(render_quoted("100%%", &m), "100%");
1224        assert_eq!(render_quoted("%q", &m), "%q");
1225        // %{...} is the date in the caller's own words.
1226        assert_eq!(render_quoted("%{%Y}", &m), "2024");
1227        assert_eq!(render_quoted("[%{%Y}] %s", &m), "[2024] Lunch");
1228    }
1229
1230    #[test]
1231    fn a_name_falls_back_to_the_address() {
1232        let m = Quoted {
1233            from: "bare@example.com",
1234            subject: "x",
1235            message_id: None,
1236            date: 0,
1237        };
1238        assert_eq!(render_quoted("%n", &m), "bare@example.com");
1239        assert_eq!(render_quoted("%i", &m), "");
1240    }
1241
1242    #[test]
1243    fn draft_text_skips_empty_optional_headers() {
1244        let text = draft_text(
1245            &DraftHeaders {
1246                from: None,
1247                to: "a@x".into(),
1248                cc: Some("".into()),
1249                subject: "s".into(),
1250                in_reply_to: None,
1251                references: None,
1252            },
1253            "hi",
1254        );
1255        assert_eq!(text, "To: a@x\nSubject: s\n\nhi\n");
1256        let text = draft_text(
1257            &DraftHeaders {
1258                from: Some("Jane Work <jane@work.example.com>".into()),
1259                to: "a@x".into(),
1260                cc: None,
1261                subject: "s".into(),
1262                in_reply_to: None,
1263                references: None,
1264            },
1265            "hi",
1266        );
1267        assert!(text.starts_with("From: Jane Work <jane@work.example.com>\nTo: a@x\n"));
1268    }
1269
1270    #[test]
1271    fn reverse_from_finds_my_address_as_it_appeared() {
1272        let addrs = vec!["jane@example.com".to_string(), "old@example.com".into()];
1273        let me = Me::addresses(&addrs);
1274        // Display name kept, match case-insensitive.
1275        assert_eq!(
1276            reverse_from("Boss Me <Jane@example.com>, bob@y", "", me, true).as_deref(),
1277            Some("Boss Me <Jane@example.com>")
1278        );
1279        // mutt's $reverse_realname off: the address alone comes over.
1280        assert_eq!(
1281            reverse_from("Boss Me <Jane@example.com>, bob@y", "", me, false).as_deref(),
1282            Some("Jane@example.com")
1283        );
1284        // Bare address stays bare; Cc is searched after To.
1285        assert_eq!(
1286            reverse_from("bob@y", "old@example.com", me, true).as_deref(),
1287            Some("old@example.com")
1288        );
1289        assert_eq!(reverse_from("bob@y, eve@z", "", me, true), None);
1290        assert_eq!(reverse_from("", "", me, true), None);
1291    }
1292
1293    #[test]
1294    fn finalize_adds_missing_headers_once() {
1295        let draft = "To: a@x\nSubject: s\n\nbody\n";
1296        let out = finalize(draft, "me@host", "<id@host>", "DATE").unwrap();
1297        assert!(out.contains("From: me@host"));
1298        assert!(out.contains("Message-ID: <id@host>"));
1299        assert!(out.contains("Date: DATE"));
1300        assert!(out.ends_with("\n\nbody\n"));
1301        // User-provided From wins.
1302        let draft2 = "To: a@x\nFrom: custom@x\n\nbody\n";
1303        let out2 = finalize(draft2, "me@host", "<i>", "D").unwrap();
1304        assert!(out2.contains("From: custom@x"));
1305        assert!(!out2.contains("me@host"));
1306    }
1307
1308    #[test]
1309    fn user_agent_and_signature_placement() {
1310        let draft = "To: a@b\n\nhi";
1311        let plain = finalize_with(draft, "me@x", "<id@h>", "Mon", false).unwrap();
1312        assert!(!plain.contains("User-Agent"));
1313        let ua = finalize_with(draft, "me@x", "<id@h>", "Mon", true).unwrap();
1314        assert!(ua.contains(&user_agent_header()), "{ua}");
1315        // A draft that already carries one is left alone.
1316        let own = finalize_with(
1317            "To: a@b\nUser-Agent: mine\n\nhi",
1318            "me@x",
1319            "<id@h>",
1320            "Mon",
1321            true,
1322        )
1323        .unwrap();
1324        assert_eq!(own.matches("User-Agent").count(), 1, "{own}");
1325        // sig_on_top puts the signature above the body.
1326        let below = with_signature_at("the reply", "Jane", true, false);
1327        assert!(below.trim_end().ends_with("Jane"), "{below}");
1328        let above = with_signature_at("the reply", "Jane", true, true);
1329        assert!(above.starts_with("-- \nJane\n"), "{above}");
1330        assert!(above.trim_end().ends_with("the reply"), "{above}");
1331    }
1332
1333    #[test]
1334    fn finalize_rejects_missing_recipients() {
1335        assert!(finalize("Subject: s\n\nbody", "f", "<i>", "d").is_err());
1336        assert!(finalize("To:   \nSubject: s\n\nbody", "f", "<i>", "d").is_err());
1337        assert!(finalize("Bcc: a@x\n\nbody", "f", "<i>", "d").is_ok());
1338    }
1339
1340    #[test]
1341    fn bare_address_drops_display_name() {
1342        assert_eq!(
1343            bare_address("Jane <jane@x.org>").as_deref(),
1344            Some("jane@x.org")
1345        );
1346        assert_eq!(bare_address("jane@x.org").as_deref(), Some("jane@x.org"));
1347        assert_eq!(bare_address(""), None);
1348    }
1349
1350    #[test]
1351    fn smtp_envelope_collects_rcpts_and_strips_bcc() {
1352        let text =
1353            "To: Alice <a@x>, b@y\nCc: c@z\nBcc: hidden@q,\n also-hidden@q\nSubject: s\n\nbody\n";
1354        let (rcpts, out) = smtp_envelope(text).unwrap();
1355        assert_eq!(
1356            rcpts,
1357            vec!["a@x", "b@y", "c@z", "hidden@q", "also-hidden@q"]
1358        );
1359        assert!(!out.to_lowercase().contains("bcc"));
1360        assert!(!out.contains("hidden@q"));
1361        assert!(out.contains("To: Alice <a@x>, b@y\n"));
1362        assert!(out.ends_with("\n\nbody\n"));
1363    }
1364
1365    #[test]
1366    fn extract_attachments_takes_the_pseudo_headers_out() {
1367        let draft = "To: a@x\nAttach: /tmp/report.pdf the Q2 numbers\n\
1368                     attach: \"/tmp/two words.png\"\nAttach:\nSubject: s\n\nbody\n";
1369        let (out, files) = extract_attachments(draft);
1370        assert_eq!(out, "To: a@x\nSubject: s\n\nbody\n");
1371        assert_eq!(files.len(), 2);
1372        assert_eq!(files[0].path, PathBuf::from("/tmp/report.pdf"));
1373        assert_eq!(files[0].description.as_deref(), Some("the Q2 numbers"));
1374        assert_eq!(files[1].path, PathBuf::from("/tmp/two words.png"));
1375        assert_eq!(files[1].description, None);
1376    }
1377
1378    #[test]
1379    fn attach_lines_carry_a_type_override() {
1380        let draft = "Attach: /tmp/x.bin application/x-custom raw dump\n\
1381                     Attach: /tmp/y.txt see notes\n\n";
1382        let (_, files) = extract_attachments(draft);
1383        assert_eq!(files[0].mime.as_deref(), Some("application/x-custom"));
1384        assert_eq!(files[0].description.as_deref(), Some("raw dump"));
1385        // "see notes" is not a type/subtype token.
1386        assert_eq!(files[1].mime, None);
1387        assert_eq!(files[1].description.as_deref(), Some("see notes"));
1388        // attach_line writes back what extract_attachments reads.
1389        let line = attach_line(&files[0]);
1390        assert_eq!(line, "Attach: /tmp/x.bin application/x-custom raw dump");
1391        let (_, roundtrip) = extract_attachments(&format!("{line}\n\n"));
1392        assert_eq!(roundtrip[0].mime.as_deref(), Some("application/x-custom"));
1393        // A quoted path with spaces survives too.
1394        let spaced = Attachment {
1395            path: PathBuf::from("/tmp/two words.png"),
1396            mime: Some("image/png".into()),
1397            description: None,
1398            name: None,
1399            inline: false,
1400            unlink: false,
1401        };
1402        let (_, files) = extract_attachments(&format!("{}\n\n", attach_line(&spaced)));
1403        assert_eq!(files[0].path, PathBuf::from("/tmp/two words.png"));
1404        assert_eq!(files[0].mime.as_deref(), Some("image/png"));
1405    }
1406
1407    #[test]
1408    fn extract_attachments_leaves_plain_drafts_alone() {
1409        let draft = "To: a@x\nSubject: s\n\nAttach: not a header, body text\n";
1410        let (out, files) = extract_attachments(draft);
1411        assert_eq!(out, draft);
1412        assert!(files.is_empty());
1413    }
1414
1415    #[test]
1416    fn mixed_entity_encodes_files_and_original() {
1417        use mailparse::MailHeaderMap;
1418        let dir = std::env::temp_dir().join(format!("rmut-attach-test-{}", std::process::id()));
1419        std::fs::create_dir_all(&dir).unwrap();
1420        let blob: Vec<u8> = (0..=255u8).collect();
1421        std::fs::write(dir.join("blob.bin"), &blob).unwrap();
1422        let files = [Attachment {
1423            path: dir.join("blob.bin"),
1424            mime: None,
1425            description: Some("raw bytes".into()),
1426            name: None,
1427            inline: false,
1428            unlink: false,
1429        }];
1430        let orig = b"From: jane@x\r\nSubject: hi\r\n\r\noriginal body\r\n";
1431        let entity = mixed_entity("see attached", &files, Some(orig), false).unwrap();
1432        let mail = mailparse::parse_mail(entity.as_bytes()).unwrap();
1433        assert_eq!(mail.ctype.mimetype, "multipart/mixed");
1434        assert_eq!(mail.subparts.len(), 3);
1435        assert_eq!(mail.subparts[0].get_body().unwrap().trim(), "see attached");
1436        let file = &mail.subparts[1];
1437        assert_eq!(file.ctype.mimetype, "application/octet-stream");
1438        assert_eq!(file.get_body_raw().unwrap(), blob);
1439        let disp = file.get_headers().get_first_value("Content-Disposition");
1440        assert!(disp.unwrap().contains("filename=\"blob.bin\""));
1441        assert_eq!(
1442            file.get_headers()
1443                .get_first_value("Content-Description")
1444                .as_deref(),
1445            Some("raw bytes")
1446        );
1447        assert_eq!(mail.subparts[2].ctype.mimetype, "message/rfc822");
1448        assert!(
1449            mail.subparts[2]
1450                .get_body()
1451                .unwrap()
1452                .contains("original body")
1453        );
1454        std::fs::remove_dir_all(&dir).unwrap();
1455    }
1456
1457    #[test]
1458    fn mixed_entity_reports_a_missing_file() {
1459        let files = [Attachment {
1460            path: PathBuf::from("/nonexistent/nope.pdf"),
1461            mime: None,
1462            description: None,
1463            name: None,
1464            inline: false,
1465            unlink: false,
1466        }];
1467        let err = mixed_entity("hi", &files, None, false).unwrap_err();
1468        assert!(err.to_string().contains("/nonexistent/nope.pdf"));
1469    }
1470
1471    #[test]
1472    fn bounce_text_prepends_resent_headers() {
1473        let orig = b"From: jane@x\nSubject: hi\n\nbody\n";
1474        let out = bounce_text(orig, "Me <me@x>", "bob@y", "DATE", "<id@x>");
1475        assert!(out.starts_with("Resent-From: Me <me@x>\r\n"));
1476        assert!(out.contains("Resent-Date: DATE\r\n"));
1477        assert!(out.contains("Resent-To: bob@y\r\n"));
1478        assert!(out.ends_with("From: jane@x\nSubject: hi\n\nbody\n"));
1479    }
1480
1481    #[test]
1482    fn smtp_envelope_without_bcc_is_unchanged() {
1483        let text = "To: a@x\nSubject: s\n\nbody\n";
1484        let (rcpts, out) = smtp_envelope(text).unwrap();
1485        assert_eq!(rcpts, vec!["a@x"]);
1486        assert_eq!(out, text);
1487    }
1488
1489    #[test]
1490    fn attach_line_options_round_trip() {
1491        let mut a = Attachment::of(PathBuf::from("/tmp/q2 report.pdf"));
1492        a.mime = Some("application/pdf".into());
1493        a.name = Some("report.pdf".into());
1494        a.inline = true;
1495        a.unlink = true;
1496        a.description = Some("the Q2 numbers".into());
1497        let line = attach_line(&a);
1498        assert_eq!(
1499            line,
1500            "Attach: \"/tmp/q2 report.pdf\" application/pdf @name=\"report.pdf\" @inline @unlink the Q2 numbers"
1501        );
1502        let (_, back) = extract_attachments(&format!("To: x\n{line}\n\nbody"));
1503        assert_eq!(back.len(), 1);
1504        let b = &back[0];
1505        assert_eq!(b.path, a.path);
1506        assert_eq!(b.mime.as_deref(), Some("application/pdf"));
1507        assert_eq!(b.name.as_deref(), Some("report.pdf"));
1508        assert!(b.inline && b.unlink);
1509        assert_eq!(b.description.as_deref(), Some("the Q2 numbers"));
1510        // A line without options reads as before, and a description
1511        // starting with @ is a description.
1512        let (_, plain) = extract_attachments("Attach: /tmp/a.txt text/plain @home notes\n\n");
1513        assert!(!plain[0].inline && plain[0].name.is_none());
1514        assert_eq!(plain[0].description.as_deref(), Some("@home notes"));
1515    }
1516
1517    #[test]
1518    fn mixed_entity_honours_name_disposition_and_rfc822() {
1519        let dir = std::env::temp_dir().join(format!("rmut-attach-opts-{}", std::process::id()));
1520        std::fs::create_dir_all(&dir).unwrap();
1521        let file = dir.join("data.bin");
1522        std::fs::write(&file, b"xyz").unwrap();
1523        let msg = dir.join("1.host:2,S");
1524        std::fs::write(&msg, "From: a@x\nSubject: inner\n\nhello\n").unwrap();
1525        let mut a = Attachment::of(file.clone());
1526        a.name = Some("renamed.bin".into());
1527        a.inline = true;
1528        let mut m = Attachment::of(msg.clone());
1529        m.mime = Some("message/rfc822".into());
1530        let entity = mixed_entity("see attached", &[a, m], None, false).unwrap();
1531        assert!(
1532            entity.contains("Content-Disposition: inline; filename=\"renamed.bin\""),
1533            "{entity}"
1534        );
1535        assert!(
1536            entity.contains(
1537                "Content-Type: message/rfc822\r\nContent-Disposition: attachment\r\n\r\nFrom: a@x"
1538            ),
1539            "{entity}"
1540        );
1541        assert!(
1542            !entity.contains("filename=\"1.host"),
1543            "a message has no filename"
1544        );
1545        let _ = std::fs::remove_dir_all(&dir);
1546    }
1547}