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/// The draft's text as a MIME entity: text/plain, or with markdown
562/// compose a multipart/alternative of that text/plain and the
563/// text/html rendered from it. The plain half comes first, so a
564/// reader that shows the last part it can (every graphical one) shows
565/// the html, and a plain one loses nothing.
566pub fn body_entity(body: &str, flowed: bool, markdown: bool) -> String {
567    let plain = text_entity(body, flowed);
568    if !markdown {
569        return plain;
570    }
571    let html = format!(
572        "Content-Type: text/html; charset=utf-8\r\n\
573         Content-Transfer-Encoding: quoted-printable\r\n\r\n{}",
574        quoted_printable(&crate::markdown::to_html(body))
575    );
576    let boundary = {
577        let mut n = 0usize;
578        loop {
579            let b = format!("=-rmut-alt-{}-{n}", std::process::id());
580            if !plain.contains(&b) && !html.contains(&b) {
581                break b;
582            }
583            n += 1;
584        }
585    };
586    let mut out = format!("Content-Type: multipart/alternative; boundary=\"{boundary}\"\r\n\r\n");
587    for part in [plain, html] {
588        out += &format!("--{boundary}\r\n{part}");
589        if !out.ends_with("\r\n") {
590            out += "\r\n";
591        }
592    }
593    out += &format!("--{boundary}--\r\n");
594    out
595}
596
597/// Quoted-printable (RFC 2045), CRLF line ends: the html half's
598/// paragraphs are single lines, often past the 998 bytes SMTP allows.
599pub fn quoted_printable(text: &str) -> String {
600    let mut out = String::new();
601    for (i, line) in text.split('\n').enumerate() {
602        if i > 0 {
603            out += "\r\n";
604        }
605        let line = line.strip_suffix('\r').unwrap_or(line);
606        let bytes = line.as_bytes();
607        let mut width = 0;
608        for (j, &b) in bytes.iter().enumerate() {
609            let last = j + 1 == bytes.len();
610            let piece = match b {
611                b'=' => "=3D".to_string(),
612                b' ' | b'\t' if last => format!("={b:02X}"),
613                b' ' | b'\t' | 33..=126 => (b as char).to_string(),
614                _ => format!("={b:02X}"),
615            };
616            // A soft break keeps every line within 76, its "=" included.
617            if width + piece.len() > 75 {
618                out += "=\r\n";
619                width = 0;
620            }
621            width += piece.len();
622            out += &piece;
623        }
624    }
625    out
626}
627
628/// The draft header that says whether this draft is markdown: rmut's
629/// own, written by the compose menu's toggle, kept through postpone,
630/// and taken off before the message goes anywhere.
631pub const MARKDOWN_HEADER: &str = "X-Rmut-Markdown";
632
633/// The draft without its markdown header, and what the header said
634/// (None when it has none, and the config decides).
635pub fn take_markdown(draft: &str) -> (String, Option<bool>) {
636    let (head, body) = match draft.split_once("\n\n") {
637        Some((h, b)) => (h, Some(b)),
638        None => (draft, None),
639    };
640    let mut said = None;
641    let kept: Vec<&str> = head
642        .lines()
643        .filter(|line| match line.split_once(':') {
644            Some((k, v)) if k.trim().eq_ignore_ascii_case(MARKDOWN_HEADER) => {
645                said = Some(matches!(
646                    v.trim().to_lowercase().as_str(),
647                    "yes" | "true" | "on"
648                ));
649                false
650            }
651            _ => true,
652        })
653        .collect();
654    let head = kept.join("\n");
655    let text = match body {
656        Some(body) => format!("{head}\n\n{body}"),
657        None => head,
658    };
659    (text, said)
660}
661
662/// mutt's $text_flowed for a message that goes out with no MIME
663/// wrapper at all: declare the body and space-stuff it, in place, on
664/// a finalized draft. One that already carries a Content-Type (the
665/// user wrote their own) is left alone.
666pub fn flow_plain(text: &str) -> String {
667    let (head, body) = match text.split_once("\n\n") {
668        Some(pair) => pair,
669        None => return text.to_string(),
670    };
671    if header_present(head, "Content-Type") {
672        return text.to_string();
673    }
674    format!(
675        "{}\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8; format=flowed\n\
676         Content-Transfer-Encoding: 8bit\n\n{}",
677        head.trim_end(),
678        crate::flowed::space_stuff(body),
679    )
680}
681
682/// The MIME entity (Content-Type header + body, CRLF endings) for a
683/// draft body with attachments: multipart/mixed with the text first,
684/// files base64-encoded, and optionally the forwarded original as
685/// message/rfc822 (mutt's mime_forward). The caller puts it under the
686/// draft's top-level headers, or inside a PGP layer.
687pub fn mixed_entity(
688    body: &str,
689    files: &[Attachment],
690    original: Option<&[u8]>,
691    flowed: bool,
692    markdown: bool,
693) -> Result<String> {
694    let mut parts: Vec<String> = Vec::new();
695    parts.push(body_entity(body, flowed, markdown));
696    for a in files {
697        let bytes =
698            std::fs::read(&a.path).with_context(|| format!("reading {}", a.path.display()))?;
699        let mime = a.mime.as_deref().unwrap_or_else(|| content_type(&a.path));
700        let disposition = if a.inline { "inline" } else { "attachment" };
701        // An attached message (mutt's attach-message) goes in as it
702        // is, a message/rfc822 part with no encoding and no filename.
703        if mime.eq_ignore_ascii_case("message/rfc822") {
704            let mut p =
705                format!("Content-Type: message/rfc822\r\nContent-Disposition: {disposition}\r\n");
706            if let Some(d) = &a.description {
707                p += &format!("Content-Description: {d}\r\n");
708            }
709            p += "\r\n";
710            p += &String::from_utf8_lossy(&crate::pgp::crlf(&bytes));
711            parts.push(p);
712            continue;
713        }
714        let mut p = format!(
715            "Content-Type: {mime}\r\nContent-Disposition: {disposition}; filename=\"{}\"\r\n",
716            a.send_name(),
717        );
718        if let Some(d) = &a.description {
719            p += &format!("Content-Description: {d}\r\n");
720        }
721        p += "Content-Transfer-Encoding: base64\r\n\r\n";
722        p += &b64_wrapped(&bytes);
723        parts.push(p);
724    }
725    if let Some(orig) = original {
726        let mut p =
727            String::from("Content-Type: message/rfc822\r\nContent-Disposition: attachment\r\n\r\n");
728        p += &String::from_utf8_lossy(&crate::pgp::crlf(orig));
729        parts.push(p);
730    }
731    let boundary = {
732        let mut n = 0usize;
733        loop {
734            let b = format!("=-rmut-mixed-{}-{n}", std::process::id());
735            if !parts.iter().any(|p| p.contains(&b)) {
736                break b;
737            }
738            n += 1;
739        }
740    };
741    let mut out = format!("Content-Type: multipart/mixed; boundary=\"{boundary}\"\r\n\r\n");
742    for p in &parts {
743        out += &format!("--{boundary}\r\n");
744        out += p;
745        if !out.ends_with("\r\n") {
746            out += "\r\n";
747        }
748    }
749    out += &format!("--{boundary}--\r\n");
750    Ok(out)
751}
752
753/// Message text for a bounce: the original with a fresh Resent-* block
754/// prepended, per RFC 5322 (the newest resend goes first).
755pub fn bounce_text(original: &[u8], from: &str, to: &str, date: &str, msg_id: &str) -> String {
756    format!(
757        "Resent-From: {from}\r\nResent-Date: {date}\r\nResent-Message-ID: {msg_id}\r\nResent-To: {to}\r\n{}",
758        String::from_utf8_lossy(original),
759    )
760}
761
762/// First address in an RFC 5322 address field, without display name,
763/// e.g. the SMTP envelope sender from a From line.
764/// The posting address from a List-Post header value:
765/// `<mailto:dev@example.com>`, with the RFC 2369 `NO` meaning the list
766/// takes no posts. Extra mailto parameters are dropped.
767pub fn list_post_address(value: &str) -> Option<String> {
768    let value = value.trim();
769    if value.eq_ignore_ascii_case("NO") {
770        return None;
771    }
772    let start = value.to_ascii_lowercase().find("mailto:")? + "mailto:".len();
773    let rest = &value[start..];
774    let addr = rest
775        .split(['>', '?', ',', ' '])
776        .next()
777        .unwrap_or(rest)
778        .trim();
779    (!addr.is_empty()).then(|| addr.to_string())
780}
781
782/// mutt's $followup_to: the Mail-Followup-To for a message going to a
783/// mailing list. Every recipient goes in; your own address is left out
784/// when you are subscribed (the list copy is the one you will get) and
785/// kept when you are not.
786pub fn followup_to(to: &str, cc: &str, me: Me, subscribed: bool, my_from: &str) -> String {
787    let mut out: Vec<String> = Vec::new();
788    let mut push = |single: &mailparse::SingleInfo| {
789        if subscribed && me.is_me(&single.addr) {
790            return;
791        }
792        let written = match &single.display_name {
793            Some(name) if !name.trim().is_empty() => format!("{name} <{}>", single.addr),
794            _ => single.addr.clone(),
795        };
796        if !out.iter().any(|a| a == &written) {
797            out.push(written);
798        }
799    };
800    for field in [to, cc] {
801        let Ok(list) = mailparse::addrparse(field) else {
802            continue;
803        };
804        for addr in list.iter() {
805            match addr {
806                mailparse::MailAddr::Single(single) => push(single),
807                mailparse::MailAddr::Group(group) => group.addrs.iter().for_each(&mut push),
808            }
809        }
810    }
811    if !subscribed
812        && let Some(from) = bare_address(my_from)
813        && !out
814            .iter()
815            .any(|a| bare_address(a).is_some_and(|b| b == from))
816    {
817        out.push(my_from.trim().to_string());
818    }
819    out.join(", ")
820}
821
822/// The Cc a group reply gets: everyone the original named in To and
823/// Cc, written the way they were written, minus anyone already in
824/// `to` (the sender, normally) and, unless mutt's $metoo is set, minus
825/// me. Duplicates collapse on the bare address, so a person listed in
826/// both To and Cc appears once.
827pub fn group_recipients(orig_to: &str, orig_cc: &str, to: &str, me: Me, metoo: bool) -> String {
828    let mut seen: Vec<String> = addresses(to).iter().map(|a| a.to_lowercase()).collect();
829    let mut out: Vec<String> = Vec::new();
830    let mut push = |single: &mailparse::SingleInfo| {
831        let bare = single.addr.to_lowercase();
832        if seen.contains(&bare) || (!metoo && me.is_me(&bare)) {
833            return;
834        }
835        seen.push(bare);
836        out.push(match &single.display_name {
837            Some(name) if !name.trim().is_empty() => format!("{name} <{}>", single.addr),
838            _ => single.addr.clone(),
839        });
840    };
841    for field in [orig_to, orig_cc] {
842        let Ok(list) = mailparse::addrparse(field) else {
843            continue;
844        };
845        for addr in list.iter() {
846            match addr {
847                mailparse::MailAddr::Single(single) => push(single),
848                mailparse::MailAddr::Group(group) => group.addrs.iter().for_each(&mut push),
849            }
850        }
851    }
852    out.join(", ")
853}
854
855/// A draft seen as a message, so hook patterns (`~t`, `~c`, `~s`,
856/// `~f`, ...) can be matched against outgoing mail the way mutt
857/// matches fcc-hook. `path` is where the body lives, so `~b` and `~h`
858/// still have something to read; the date is now, since the draft has
859/// no Date header yet. Bcc joins the Cc
860/// addresses, so a hook on `~c` sees a blind recipient too.
861pub fn draft_envelope(text: &str, path: &Path) -> crate::message::Envelope {
862    let (head, body) = text.split_once("\n\n").unwrap_or((text.trim_end(), ""));
863    let header = |name: &str| -> String {
864        head.lines()
865            .filter_map(|l| {
866                let (k, v) = l.split_once(':')?;
867                k.trim().eq_ignore_ascii_case(name).then(|| v.trim())
868            })
869            .collect::<Vec<_>>()
870            .join(", ")
871    };
872    let bare = |field: &str| -> Vec<String> {
873        addresses(field).iter().map(|a| a.to_lowercase()).collect()
874    };
875    let from_full = header("From");
876    crate::message::Envelope {
877        file: crate::maildir::MailFile {
878            path: path.to_path_buf(),
879            is_new: false,
880            flags: crate::maildir::Flags {
881                seen: true,
882                ..Default::default()
883            },
884            size: text.len() as u64,
885        },
886        from: crate::message::short_from(&from_full),
887        from_full,
888        subject: header("Subject"),
889        date: Local::now().timestamp(),
890        msg_id: None,
891        references: Vec::new(),
892        tagged: false,
893        to: bare(&header("To")),
894        cc: [header("Cc"), header("Bcc")]
895            .iter()
896            .flat_map(|f| bare(f))
897            .collect(),
898        lines: Some(body.lines().count()),
899        list: None,
900        label: None,
901        broken: false,
902    }
903}
904
905/// mutt's `my_hdr`: extra header lines that go on every draft. An
906/// entry naming a header the draft already carries replaces it, so
907/// `my_hdr From:` and `my_hdr Reply-To:` win over what rmut chose;
908/// To, Cc and Bcc instead gain the address, like mutt, so a standing
909/// `my_hdr Bcc: me@example.com` cannot erase a reply's recipients.
910/// Malformed entries (no colon, no name) are ignored.
911pub fn apply_my_hdr(text: &str, my_hdr: &[String]) -> String {
912    if my_hdr.is_empty() {
913        return text.to_string();
914    }
915    let (head, body) = match text.split_once("\n\n") {
916        Some((head, body)) => (head, body),
917        None => (text.trim_end(), ""),
918    };
919    let mut lines: Vec<String> = head.lines().map(String::from).collect();
920    for entry in my_hdr {
921        let Some((name, value)) = entry.split_once(':') else {
922            continue;
923        };
924        let (name, value) = (name.trim(), value.trim());
925        if name.is_empty() {
926            continue;
927        }
928        let at = lines.iter().position(|l| {
929            l.get(..name.len())
930                .is_some_and(|k| k.eq_ignore_ascii_case(name))
931                && l.as_bytes().get(name.len()) == Some(&b':')
932        });
933        let addressy = ["to", "cc", "bcc"].contains(&name.to_lowercase().as_str());
934        match at {
935            Some(i) if addressy => {
936                let old = lines[i]
937                    .split_once(':')
938                    .map(|(_, v)| v.trim().to_string())
939                    .unwrap_or_default();
940                lines[i] = if old.is_empty() {
941                    format!("{name}: {value}")
942                } else {
943                    format!("{name}: {old}, {value}")
944                };
945            }
946            Some(i) => lines[i] = format!("{name}: {value}"),
947            None => lines.push(format!("{name}: {value}")),
948        }
949    }
950    format!("{}\n\n{body}", lines.join("\n"))
951}
952
953pub fn bare_address(field: &str) -> Option<String> {
954    match mailparse::addrparse(field)
955        .ok()?
956        .into_inner()
957        .into_iter()
958        .next()?
959    {
960        mailparse::MailAddr::Single(single) => Some(single.addr),
961        mailparse::MailAddr::Group(group) => group.addrs.first().map(|a| a.addr.clone()),
962    }
963}
964
965/// The SMTP envelope sender: the bare address of the From header.
966pub fn from_address(text: &str) -> Option<String> {
967    let mail = mailparse::parse_mail(text.as_bytes()).ok()?;
968    bare_address(&crate::rfc2047::first(&mail.get_headers(), "From")?)
969}
970
971fn field_addresses(value: &str, out: &mut Vec<String>) {
972    let Ok(list) = mailparse::addrparse(value) else {
973        return;
974    };
975    for addr in list.iter() {
976        match addr {
977            mailparse::MailAddr::Single(single) => out.push(single.addr.clone()),
978            mailparse::MailAddr::Group(group) => {
979                out.extend(group.addrs.iter().map(|a| a.addr.clone()));
980            }
981        }
982    }
983}
984
985/// Every bare address in an RFC 5322 address field.
986pub fn addresses(field: &str) -> Vec<String> {
987    let mut out = Vec::new();
988    field_addresses(field, &mut out);
989    out
990}
991
992/// mutt's reverse_name: the first of my addresses (`alternates`
993/// included) the original was addressed to, in the form it appeared:
994/// the display name from the To/Cc header is kept.
995pub fn reverse_from(orig_to: &str, orig_cc: &str, me: Me, realname: bool) -> Option<String> {
996    let mine = |single: &mailparse::SingleInfo| -> Option<String> {
997        if !me.is_me(&single.addr) {
998            return None;
999        }
1000        Some(match &single.display_name {
1001            // mutt's $reverse_realname off: the address is theirs,
1002            // the name stays whatever the identity says.
1003            Some(name) if realname && !name.trim().is_empty() => {
1004                format!("{name} <{}>", single.addr)
1005            }
1006            _ => single.addr.clone(),
1007        })
1008    };
1009    for field in [orig_to, orig_cc] {
1010        let Ok(list) = mailparse::addrparse(field) else {
1011            continue;
1012        };
1013        for addr in list.iter() {
1014            match addr {
1015                mailparse::MailAddr::Single(single) => {
1016                    if let Some(from) = mine(single) {
1017                        return Some(from);
1018                    }
1019                }
1020                mailparse::MailAddr::Group(group) => {
1021                    if let Some(from) = group.addrs.iter().find_map(&mine) {
1022                        return Some(from);
1023                    }
1024                }
1025            }
1026        }
1027    }
1028    None
1029}
1030
1031/// SMTP envelope for a finalized draft: every To/Cc/Bcc address, and
1032/// the text with Bcc headers removed (they must not go on the wire).
1033pub fn smtp_envelope(text: &str) -> Result<(Vec<String>, String)> {
1034    let mail = mailparse::parse_mail(text.as_bytes())?;
1035    let mut rcpts = Vec::new();
1036    for header in &mail.headers {
1037        let key = header.get_key();
1038        if ["to", "cc", "bcc"].contains(&key.to_lowercase().as_str()) {
1039            field_addresses(&crate::rfc2047::value(header), &mut rcpts);
1040        }
1041    }
1042    rcpts.dedup();
1043    let (head, body) = text.split_once("\n\n").unwrap_or((text.trim_end(), ""));
1044    let mut out = String::new();
1045    let mut skipping = false;
1046    for line in head.lines() {
1047        if line.starts_with(' ') || line.starts_with('\t') {
1048            // Folded continuation belongs to the previous header.
1049            if skipping {
1050                continue;
1051            }
1052        } else {
1053            skipping = line
1054                .split_once(':')
1055                .is_some_and(|(k, _)| k.trim().eq_ignore_ascii_case("bcc"));
1056        }
1057        if !skipping {
1058            out.push_str(line);
1059            out.push('\n');
1060        }
1061    }
1062    out.push('\n');
1063    out.push_str(body);
1064    Ok((rcpts, out))
1065}
1066
1067#[cfg(test)]
1068mod tests {
1069    use super::*;
1070
1071    #[test]
1072    fn a_markdown_body_is_text_and_html() {
1073        let entity = body_entity("Hi *Jane*\n", false, true);
1074        assert!(
1075            entity.starts_with("Content-Type: multipart/alternative; boundary="),
1076            "{entity}"
1077        );
1078        let plain = entity.find("Content-Type: text/plain").expect(&entity);
1079        let html = entity.find("Content-Type: text/html").expect(&entity);
1080        assert!(plain < html, "the plain half first: {entity}");
1081        assert!(
1082            entity.contains("\r\nHi *Jane*\r\n"),
1083            "the text as typed: {entity}"
1084        );
1085        assert!(entity.contains("<em>Jane</em>"), "{entity}");
1086        assert!(entity.contains("Content-Transfer-Encoding: quoted-printable"));
1087        // Off, it is the plain part alone.
1088        assert!(body_entity("Hi\n", false, false).starts_with("Content-Type: text/plain"));
1089    }
1090
1091    #[test]
1092    fn quoted_printable_keeps_lines_short_and_bytes_safe() {
1093        let long = "word ".repeat(40);
1094        let qp = quoted_printable(&format!("{long}\na=b \u{17e}luť"));
1095        assert!(
1096            qp.lines().all(|l| l.trim_end_matches('\r').len() <= 76),
1097            "{qp}"
1098        );
1099        assert!(qp.contains("=\r\n"), "a soft break: {qp}");
1100        // The trailing space of the long line is encoded, = is, and
1101        // the UTF-8 bytes are.
1102        assert!(qp.contains("=20\r\na=3Db =C5=BElu=C5=A5"), "{qp}");
1103        let back: String = qp.replace("=\r\n", "");
1104        assert!(back.starts_with("word word"), "{back}");
1105    }
1106
1107    #[test]
1108    fn the_markdown_header_is_read_and_taken_off() {
1109        let (text, said) = take_markdown("To: a@x\nX-Rmut-Markdown: yes\nSubject: s\n\nbody\n");
1110        assert_eq!(said, Some(true));
1111        assert_eq!(text, "To: a@x\nSubject: s\n\nbody\n");
1112        let (_, said) = take_markdown("To: a@x\nx-rmut-markdown: no\n\nbody\n");
1113        assert_eq!(said, Some(false));
1114        let (text, said) = take_markdown("To: a@x\n\nX-Rmut-Markdown: yes in the body\n");
1115        assert_eq!(said, None, "only the header block counts");
1116        assert!(text.contains("in the body"));
1117    }
1118
1119    #[test]
1120    fn a_forward_can_come_in_quoted() {
1121        let plain = forward_body("Ann <ann@x>", 0, "hi", "one\ntwo\n", None);
1122        assert!(plain.contains("\none\ntwo\n"), "{plain}");
1123        let quoted = forward_body("Ann <ann@x>", 0, "hi", "one\ntwo\n", Some("> "));
1124        assert!(quoted.contains("\n> one\n> two\n"), "{quoted}");
1125        // The markers are rmut's words, so they stay flush.
1126        assert!(quoted.starts_with("----- Forwarded message from Ann <ann@x> -----"));
1127        assert!(quoted.ends_with("----- End forwarded message -----\n"));
1128    }
1129
1130    #[test]
1131    fn the_signature_sits_under_a_dashes_line() {
1132        let body = with_signature("hello\n", "Ann\nx.example", true);
1133        assert_eq!(body, "hello\n\n-- \nAnn\nx.example\n");
1134        // nosig_dashes: the text alone, still a blank line down.
1135        assert_eq!(with_signature("hello\n", "Ann", false), "hello\n\nAnn\n");
1136        // An empty draft starts with the blank line all the same.
1137        assert_eq!(with_signature("", "Ann", true), "\n-- \nAnn\n");
1138    }
1139
1140    #[test]
1141    fn a_signature_comes_from_a_file_or_a_command() {
1142        let dir = std::env::temp_dir().join(format!("rmut-sig-{}", std::process::id()));
1143        std::fs::create_dir_all(&dir).unwrap();
1144        let file = dir.join("signature");
1145        std::fs::write(&file, "Ann\n\n\n").unwrap();
1146        // Trailing blank lines are the file's, not the signature's.
1147        assert_eq!(
1148            signature_text(file.to_str().unwrap()).as_deref(),
1149            Some("Ann")
1150        );
1151        assert_eq!(signature_text("echo hello|").as_deref(), Some("hello"));
1152        // Nothing readable is no signature, not an empty one.
1153        assert_eq!(signature_text(dir.join("gone").to_str().unwrap()), None);
1154        assert_eq!(signature_text("  "), None);
1155        assert_eq!(signature_text("true|"), None);
1156        std::fs::remove_dir_all(&dir).unwrap();
1157    }
1158
1159    #[test]
1160    fn list_post_addresses() {
1161        assert_eq!(
1162            list_post_address("<mailto:dev@example.com>").as_deref(),
1163            Some("dev@example.com")
1164        );
1165        assert_eq!(
1166            list_post_address("<mailto:dev@example.com?subject=help>").as_deref(),
1167            Some("dev@example.com")
1168        );
1169        assert_eq!(
1170            list_post_address("NOTE: <mailto:dev@example.com>, <http://x/post>").as_deref(),
1171            Some("dev@example.com")
1172        );
1173        // RFC 2369: a list that takes no posts, and a non-mail method.
1174        assert_eq!(list_post_address("NO"), None);
1175        assert_eq!(list_post_address("<http://example.com/post>"), None);
1176    }
1177
1178    #[test]
1179    fn followup_to_drops_me_only_when_subscribed() {
1180        let addrs = vec!["alex@example.com".to_string()];
1181        let me = Me::addresses(&addrs);
1182        let subscribed = followup_to(
1183            "dev@example.com, Alex <alex@example.com>",
1184            "",
1185            me,
1186            true,
1187            "Alex <alex@example.com>",
1188        );
1189        assert_eq!(subscribed, "dev@example.com");
1190        let unsubscribed = followup_to(
1191            "dev@example.com",
1192            "petr@example.com",
1193            me,
1194            false,
1195            "Alex <alex@example.com>",
1196        );
1197        assert_eq!(
1198            unsubscribed,
1199            "dev@example.com, petr@example.com, Alex <alex@example.com>"
1200        );
1201        // Already listed: no second copy of my address.
1202        let once = followup_to(
1203            "dev@example.com, alex@example.com",
1204            "",
1205            me,
1206            false,
1207            "Alex <alex@example.com>",
1208        );
1209        assert_eq!(once, "dev@example.com, alex@example.com");
1210    }
1211
1212    #[test]
1213    fn group_reply_drops_me_and_the_sender() {
1214        let addrs = vec!["alex@example.com".to_string()];
1215        let alternates = vec![crate::pattern::Matcher::new("^jp@old\\.example\\.com$")];
1216        let me = Me::new(&addrs, &alternates);
1217        let cc = group_recipients(
1218            "Team <team@example.com>, Alex <alex@example.com>, jp@old.example.com",
1219            "boss@example.com, team@example.com",
1220            "Petr <petr@example.com>",
1221            me,
1222            false,
1223        );
1224        // My exact address and my alternate are gone, the sender in To
1225        // is gone, and team@ appears once despite being listed twice.
1226        assert_eq!(cc, "Team <team@example.com>, boss@example.com");
1227        // $metoo keeps me on the copy.
1228        let cc = group_recipients(
1229            "team@example.com, alex@example.com",
1230            "",
1231            "petr@example.com",
1232            me,
1233            true,
1234        );
1235        assert_eq!(cc, "team@example.com, alex@example.com");
1236    }
1237
1238    #[test]
1239    fn text_flowed_declares_and_stuffs_the_body() {
1240        let entity = text_entity("plain\n>looks quoted\n", true);
1241        assert!(
1242            entity.starts_with("Content-Type: text/plain; charset=utf-8; format=flowed\r\n"),
1243            "{entity}"
1244        );
1245        assert!(
1246            entity.ends_with("plain\r\n >looks quoted\r\n"),
1247            "{entity:?}"
1248        );
1249        // Off, the part is what it always was.
1250        let plain = text_entity("plain\n>looks quoted\n", false);
1251        assert!(plain.starts_with("Content-Type: text/plain; charset=utf-8\r\n"));
1252        assert!(plain.ends_with("plain\r\n>looks quoted\r\n"), "{plain:?}");
1253    }
1254
1255    #[test]
1256    fn flow_plain_declares_an_unwrapped_draft() {
1257        let draft = "From: a@x\nTo: b@x\nSubject: s\n\n>quoted line\n";
1258        let out = flow_plain(draft);
1259        assert!(out.contains("Content-Type: text/plain; charset=utf-8; format=flowed\n"));
1260        assert!(out.ends_with("\n\n >quoted line\n"), "{out:?}");
1261        // A draft that declares its own type is left alone.
1262        let typed = "From: a@x\nContent-Type: text/x-diff\n\nbody\n";
1263        assert_eq!(flow_plain(typed), typed);
1264    }
1265
1266    #[test]
1267    fn draft_envelope_reads_the_header_block() {
1268        let draft = "From: Jane Doe <jane@example.com>\n\
1269                     To: Bob <BOB@work.example.com>, team@x\n\
1270                     Cc: boss@x\n\
1271                     Bcc: archive@x\n\
1272                     Subject: quarterly\n\n\
1273                     two\nlines\n";
1274        let env = draft_envelope(draft, std::path::Path::new("/tmp/draft"));
1275        assert_eq!(env.subject, "quarterly");
1276        assert_eq!(env.from_full, "Jane Doe <jane@example.com>");
1277        assert_eq!(env.to, ["bob@work.example.com", "team@x"]);
1278        // Bcc joins Cc, so a hook on ~c sees a blind recipient too.
1279        assert_eq!(env.cc, ["boss@x", "archive@x"]);
1280        assert_eq!(env.lines, Some(2));
1281        let hit = |p: &str| {
1282            crate::pattern::matches_in(
1283                &crate::pattern::parse(p).unwrap(),
1284                &env,
1285                crate::pattern::Scope::default(),
1286                None,
1287            )
1288        };
1289        assert!(hit("~t @work\\.example\\.com"));
1290        assert!(hit("~c archive@"));
1291        assert!(hit("~A"));
1292        assert!(!hit("~t nobody@"));
1293    }
1294
1295    #[test]
1296    fn my_hdr_merges_into_the_draft_head() {
1297        let draft = "From: jane@example.com\nTo: bob@x\nSubject: s\n\nbody\n";
1298        let merged = apply_my_hdr(
1299            draft,
1300            &[
1301                "Organization: Acme".to_string(),
1302                "From: Jane <jane@work.example.com>".into(),
1303                "Bcc: jane@example.com".into(),
1304                "To: archive@x".into(),
1305                "bogus".into(),
1306            ],
1307        );
1308        assert_eq!(
1309            merged,
1310            "From: Jane <jane@work.example.com>\n\
1311             To: bob@x, archive@x\n\
1312             Subject: s\n\
1313             Organization: Acme\n\
1314             Bcc: jane@example.com\n\
1315             \nbody\n"
1316        );
1317        // Nothing configured: the draft is untouched.
1318        assert_eq!(apply_my_hdr(draft, &[]), draft);
1319    }
1320
1321    /// A message sent at a known moment, for the format strings.
1322    fn quoted() -> Quoted<'static> {
1323        Quoted {
1324            from: "Jane Doe <jane@example.com>",
1325            subject: "Lunch",
1326            message_id: Some("<m1@example.com>"),
1327            // 2024-03-11 10:00:00 UTC.
1328            date: 1_710_151_200,
1329        }
1330    }
1331
1332    #[test]
1333    fn subjects_do_not_stack_prefixes() {
1334        let re = default_reply_regexp();
1335        assert_eq!(reply_subject("Lunch", &re), "Re: Lunch");
1336        assert_eq!(reply_subject("RE: Lunch", &re), "Re: Lunch");
1337        assert_eq!(reply_subject("Re[2]: Lunch", &re), "Re: Lunch");
1338        // A locale's own prefixes, and mutt's smart case: an
1339        // uppercase letter in the regex makes it exact.
1340        let aw = reply_regexp("^(re|aw|sv):[ \t]*").unwrap();
1341        assert_eq!(reply_subject("AW: Lunch", &aw), "Re: Lunch");
1342        let exact = reply_regexp("^(Re):[ \t]*").unwrap();
1343        assert_eq!(reply_subject("RE: Lunch", &exact), "Re: RE: Lunch");
1344        assert_eq!(
1345            forward_subject(DEFAULT_FORWARD_FORMAT, &quoted()),
1346            "[jane@example.com: Lunch]"
1347        );
1348    }
1349
1350    #[test]
1351    fn quote_prefixes_every_line_with_the_indent_string() {
1352        assert_eq!(
1353            quote("On X, Y wrote:", DEFAULT_INDENT, "a\nb"),
1354            "On X, Y wrote:\n> a\n> b\n"
1355        );
1356        assert_eq!(quote("head", "| ", "a"), "head\n| a\n");
1357    }
1358
1359    #[test]
1360    fn an_attribution_says_who_and_when() {
1361        let m = quoted();
1362        // The default names the author and the date it was sent.
1363        let line = attribution(DEFAULT_ATTRIBUTION, &m);
1364        assert!(line.starts_with("On "), "{line}");
1365        assert!(line.ends_with(", Jane Doe wrote:"), "{line}");
1366        // Every specifier mutt's does, and an unknown one stays put.
1367        assert_eq!(render_quoted("%a", &m), "jane@example.com");
1368        assert_eq!(render_quoted("%n", &m), "Jane Doe");
1369        assert_eq!(render_quoted("%f", &m), "Jane Doe <jane@example.com>");
1370        assert_eq!(render_quoted("%s", &m), "Lunch");
1371        assert_eq!(render_quoted("%i", &m), "m1@example.com");
1372        assert_eq!(render_quoted("100%%", &m), "100%");
1373        assert_eq!(render_quoted("%q", &m), "%q");
1374        // %{...} is the date in the caller's own words.
1375        assert_eq!(render_quoted("%{%Y}", &m), "2024");
1376        assert_eq!(render_quoted("[%{%Y}] %s", &m), "[2024] Lunch");
1377    }
1378
1379    #[test]
1380    fn a_name_falls_back_to_the_address() {
1381        let m = Quoted {
1382            from: "bare@example.com",
1383            subject: "x",
1384            message_id: None,
1385            date: 0,
1386        };
1387        assert_eq!(render_quoted("%n", &m), "bare@example.com");
1388        assert_eq!(render_quoted("%i", &m), "");
1389    }
1390
1391    #[test]
1392    fn draft_text_skips_empty_optional_headers() {
1393        let text = draft_text(
1394            &DraftHeaders {
1395                from: None,
1396                to: "a@x".into(),
1397                cc: Some("".into()),
1398                subject: "s".into(),
1399                in_reply_to: None,
1400                references: None,
1401            },
1402            "hi",
1403        );
1404        assert_eq!(text, "To: a@x\nSubject: s\n\nhi\n");
1405        let text = draft_text(
1406            &DraftHeaders {
1407                from: Some("Jane Work <jane@work.example.com>".into()),
1408                to: "a@x".into(),
1409                cc: None,
1410                subject: "s".into(),
1411                in_reply_to: None,
1412                references: None,
1413            },
1414            "hi",
1415        );
1416        assert!(text.starts_with("From: Jane Work <jane@work.example.com>\nTo: a@x\n"));
1417    }
1418
1419    #[test]
1420    fn reverse_from_finds_my_address_as_it_appeared() {
1421        let addrs = vec!["jane@example.com".to_string(), "old@example.com".into()];
1422        let me = Me::addresses(&addrs);
1423        // Display name kept, match case-insensitive.
1424        assert_eq!(
1425            reverse_from("Boss Me <Jane@example.com>, bob@y", "", me, true).as_deref(),
1426            Some("Boss Me <Jane@example.com>")
1427        );
1428        // mutt's $reverse_realname off: the address alone comes over.
1429        assert_eq!(
1430            reverse_from("Boss Me <Jane@example.com>, bob@y", "", me, false).as_deref(),
1431            Some("Jane@example.com")
1432        );
1433        // Bare address stays bare; Cc is searched after To.
1434        assert_eq!(
1435            reverse_from("bob@y", "old@example.com", me, true).as_deref(),
1436            Some("old@example.com")
1437        );
1438        assert_eq!(reverse_from("bob@y, eve@z", "", me, true), None);
1439        assert_eq!(reverse_from("", "", me, true), None);
1440    }
1441
1442    #[test]
1443    fn finalize_adds_missing_headers_once() {
1444        let draft = "To: a@x\nSubject: s\n\nbody\n";
1445        let out = finalize(draft, "me@host", "<id@host>", "DATE").unwrap();
1446        assert!(out.contains("From: me@host"));
1447        assert!(out.contains("Message-ID: <id@host>"));
1448        assert!(out.contains("Date: DATE"));
1449        assert!(out.ends_with("\n\nbody\n"));
1450        // User-provided From wins.
1451        let draft2 = "To: a@x\nFrom: custom@x\n\nbody\n";
1452        let out2 = finalize(draft2, "me@host", "<i>", "D").unwrap();
1453        assert!(out2.contains("From: custom@x"));
1454        assert!(!out2.contains("me@host"));
1455    }
1456
1457    #[test]
1458    fn user_agent_and_signature_placement() {
1459        let draft = "To: a@b\n\nhi";
1460        let plain = finalize_with(draft, "me@x", "<id@h>", "Mon", false).unwrap();
1461        assert!(!plain.contains("User-Agent"));
1462        let ua = finalize_with(draft, "me@x", "<id@h>", "Mon", true).unwrap();
1463        assert!(ua.contains(&user_agent_header()), "{ua}");
1464        // A draft that already carries one is left alone.
1465        let own = finalize_with(
1466            "To: a@b\nUser-Agent: mine\n\nhi",
1467            "me@x",
1468            "<id@h>",
1469            "Mon",
1470            true,
1471        )
1472        .unwrap();
1473        assert_eq!(own.matches("User-Agent").count(), 1, "{own}");
1474        // sig_on_top puts the signature above the body.
1475        let below = with_signature_at("the reply", "Jane", true, false);
1476        assert!(below.trim_end().ends_with("Jane"), "{below}");
1477        let above = with_signature_at("the reply", "Jane", true, true);
1478        assert!(above.starts_with("-- \nJane\n"), "{above}");
1479        assert!(above.trim_end().ends_with("the reply"), "{above}");
1480    }
1481
1482    #[test]
1483    fn finalize_rejects_missing_recipients() {
1484        assert!(finalize("Subject: s\n\nbody", "f", "<i>", "d").is_err());
1485        assert!(finalize("To:   \nSubject: s\n\nbody", "f", "<i>", "d").is_err());
1486        assert!(finalize("Bcc: a@x\n\nbody", "f", "<i>", "d").is_ok());
1487    }
1488
1489    #[test]
1490    fn bare_address_drops_display_name() {
1491        assert_eq!(
1492            bare_address("Jane <jane@x.org>").as_deref(),
1493            Some("jane@x.org")
1494        );
1495        assert_eq!(bare_address("jane@x.org").as_deref(), Some("jane@x.org"));
1496        assert_eq!(bare_address(""), None);
1497    }
1498
1499    #[test]
1500    fn smtp_envelope_collects_rcpts_and_strips_bcc() {
1501        let text =
1502            "To: Alice <a@x>, b@y\nCc: c@z\nBcc: hidden@q,\n also-hidden@q\nSubject: s\n\nbody\n";
1503        let (rcpts, out) = smtp_envelope(text).unwrap();
1504        assert_eq!(
1505            rcpts,
1506            vec!["a@x", "b@y", "c@z", "hidden@q", "also-hidden@q"]
1507        );
1508        assert!(!out.to_lowercase().contains("bcc"));
1509        assert!(!out.contains("hidden@q"));
1510        assert!(out.contains("To: Alice <a@x>, b@y\n"));
1511        assert!(out.ends_with("\n\nbody\n"));
1512    }
1513
1514    #[test]
1515    fn extract_attachments_takes_the_pseudo_headers_out() {
1516        let draft = "To: a@x\nAttach: /tmp/report.pdf the Q2 numbers\n\
1517                     attach: \"/tmp/two words.png\"\nAttach:\nSubject: s\n\nbody\n";
1518        let (out, files) = extract_attachments(draft);
1519        assert_eq!(out, "To: a@x\nSubject: s\n\nbody\n");
1520        assert_eq!(files.len(), 2);
1521        assert_eq!(files[0].path, PathBuf::from("/tmp/report.pdf"));
1522        assert_eq!(files[0].description.as_deref(), Some("the Q2 numbers"));
1523        assert_eq!(files[1].path, PathBuf::from("/tmp/two words.png"));
1524        assert_eq!(files[1].description, None);
1525    }
1526
1527    #[test]
1528    fn attach_lines_carry_a_type_override() {
1529        let draft = "Attach: /tmp/x.bin application/x-custom raw dump\n\
1530                     Attach: /tmp/y.txt see notes\n\n";
1531        let (_, files) = extract_attachments(draft);
1532        assert_eq!(files[0].mime.as_deref(), Some("application/x-custom"));
1533        assert_eq!(files[0].description.as_deref(), Some("raw dump"));
1534        // "see notes" is not a type/subtype token.
1535        assert_eq!(files[1].mime, None);
1536        assert_eq!(files[1].description.as_deref(), Some("see notes"));
1537        // attach_line writes back what extract_attachments reads.
1538        let line = attach_line(&files[0]);
1539        assert_eq!(line, "Attach: /tmp/x.bin application/x-custom raw dump");
1540        let (_, roundtrip) = extract_attachments(&format!("{line}\n\n"));
1541        assert_eq!(roundtrip[0].mime.as_deref(), Some("application/x-custom"));
1542        // A quoted path with spaces survives too.
1543        let spaced = Attachment {
1544            path: PathBuf::from("/tmp/two words.png"),
1545            mime: Some("image/png".into()),
1546            description: None,
1547            name: None,
1548            inline: false,
1549            unlink: false,
1550        };
1551        let (_, files) = extract_attachments(&format!("{}\n\n", attach_line(&spaced)));
1552        assert_eq!(files[0].path, PathBuf::from("/tmp/two words.png"));
1553        assert_eq!(files[0].mime.as_deref(), Some("image/png"));
1554    }
1555
1556    #[test]
1557    fn extract_attachments_leaves_plain_drafts_alone() {
1558        let draft = "To: a@x\nSubject: s\n\nAttach: not a header, body text\n";
1559        let (out, files) = extract_attachments(draft);
1560        assert_eq!(out, draft);
1561        assert!(files.is_empty());
1562    }
1563
1564    #[test]
1565    fn mixed_entity_encodes_files_and_original() {
1566        use mailparse::MailHeaderMap;
1567        let dir = std::env::temp_dir().join(format!("rmut-attach-test-{}", std::process::id()));
1568        std::fs::create_dir_all(&dir).unwrap();
1569        let blob: Vec<u8> = (0..=255u8).collect();
1570        std::fs::write(dir.join("blob.bin"), &blob).unwrap();
1571        let files = [Attachment {
1572            path: dir.join("blob.bin"),
1573            mime: None,
1574            description: Some("raw bytes".into()),
1575            name: None,
1576            inline: false,
1577            unlink: false,
1578        }];
1579        let orig = b"From: jane@x\r\nSubject: hi\r\n\r\noriginal body\r\n";
1580        let entity = mixed_entity("see attached", &files, Some(orig), false, false).unwrap();
1581        let mail = mailparse::parse_mail(entity.as_bytes()).unwrap();
1582        assert_eq!(mail.ctype.mimetype, "multipart/mixed");
1583        assert_eq!(mail.subparts.len(), 3);
1584        assert_eq!(mail.subparts[0].get_body().unwrap().trim(), "see attached");
1585        let file = &mail.subparts[1];
1586        assert_eq!(file.ctype.mimetype, "application/octet-stream");
1587        assert_eq!(file.get_body_raw().unwrap(), blob);
1588        let disp = file.get_headers().get_first_value("Content-Disposition");
1589        assert!(disp.unwrap().contains("filename=\"blob.bin\""));
1590        assert_eq!(
1591            file.get_headers()
1592                .get_first_value("Content-Description")
1593                .as_deref(),
1594            Some("raw bytes")
1595        );
1596        assert_eq!(mail.subparts[2].ctype.mimetype, "message/rfc822");
1597        assert!(
1598            mail.subparts[2]
1599                .get_body()
1600                .unwrap()
1601                .contains("original body")
1602        );
1603        std::fs::remove_dir_all(&dir).unwrap();
1604    }
1605
1606    #[test]
1607    fn mixed_entity_reports_a_missing_file() {
1608        let files = [Attachment {
1609            path: PathBuf::from("/nonexistent/nope.pdf"),
1610            mime: None,
1611            description: None,
1612            name: None,
1613            inline: false,
1614            unlink: false,
1615        }];
1616        let err = mixed_entity("hi", &files, None, false, false).unwrap_err();
1617        assert!(err.to_string().contains("/nonexistent/nope.pdf"));
1618    }
1619
1620    #[test]
1621    fn bounce_text_prepends_resent_headers() {
1622        let orig = b"From: jane@x\nSubject: hi\n\nbody\n";
1623        let out = bounce_text(orig, "Me <me@x>", "bob@y", "DATE", "<id@x>");
1624        assert!(out.starts_with("Resent-From: Me <me@x>\r\n"));
1625        assert!(out.contains("Resent-Date: DATE\r\n"));
1626        assert!(out.contains("Resent-To: bob@y\r\n"));
1627        assert!(out.ends_with("From: jane@x\nSubject: hi\n\nbody\n"));
1628    }
1629
1630    #[test]
1631    fn smtp_envelope_without_bcc_is_unchanged() {
1632        let text = "To: a@x\nSubject: s\n\nbody\n";
1633        let (rcpts, out) = smtp_envelope(text).unwrap();
1634        assert_eq!(rcpts, vec!["a@x"]);
1635        assert_eq!(out, text);
1636    }
1637
1638    #[test]
1639    fn attach_line_options_round_trip() {
1640        let mut a = Attachment::of(PathBuf::from("/tmp/q2 report.pdf"));
1641        a.mime = Some("application/pdf".into());
1642        a.name = Some("report.pdf".into());
1643        a.inline = true;
1644        a.unlink = true;
1645        a.description = Some("the Q2 numbers".into());
1646        let line = attach_line(&a);
1647        assert_eq!(
1648            line,
1649            "Attach: \"/tmp/q2 report.pdf\" application/pdf @name=\"report.pdf\" @inline @unlink the Q2 numbers"
1650        );
1651        let (_, back) = extract_attachments(&format!("To: x\n{line}\n\nbody"));
1652        assert_eq!(back.len(), 1);
1653        let b = &back[0];
1654        assert_eq!(b.path, a.path);
1655        assert_eq!(b.mime.as_deref(), Some("application/pdf"));
1656        assert_eq!(b.name.as_deref(), Some("report.pdf"));
1657        assert!(b.inline && b.unlink);
1658        assert_eq!(b.description.as_deref(), Some("the Q2 numbers"));
1659        // A line without options reads as before, and a description
1660        // starting with @ is a description.
1661        let (_, plain) = extract_attachments("Attach: /tmp/a.txt text/plain @home notes\n\n");
1662        assert!(!plain[0].inline && plain[0].name.is_none());
1663        assert_eq!(plain[0].description.as_deref(), Some("@home notes"));
1664    }
1665
1666    #[test]
1667    fn mixed_entity_honours_name_disposition_and_rfc822() {
1668        let dir = std::env::temp_dir().join(format!("rmut-attach-opts-{}", std::process::id()));
1669        std::fs::create_dir_all(&dir).unwrap();
1670        let file = dir.join("data.bin");
1671        std::fs::write(&file, b"xyz").unwrap();
1672        let msg = dir.join("1.host:2,S");
1673        std::fs::write(&msg, "From: a@x\nSubject: inner\n\nhello\n").unwrap();
1674        let mut a = Attachment::of(file.clone());
1675        a.name = Some("renamed.bin".into());
1676        a.inline = true;
1677        let mut m = Attachment::of(msg.clone());
1678        m.mime = Some("message/rfc822".into());
1679        let entity = mixed_entity("see attached", &[a, m], None, false, false).unwrap();
1680        assert!(
1681            entity.contains("Content-Disposition: inline; filename=\"renamed.bin\""),
1682            "{entity}"
1683        );
1684        assert!(
1685            entity.contains(
1686                "Content-Type: message/rfc822\r\nContent-Disposition: attachment\r\n\r\nFrom: a@x"
1687            ),
1688            "{entity}"
1689        );
1690        assert!(
1691            !entity.contains("filename=\"1.host"),
1692            "a message has no filename"
1693        );
1694        let _ = std::fs::remove_dir_all(&dir);
1695    }
1696}