1use std::path::{Path, PathBuf};
4
5use anyhow::{Context, Result, ensure};
6use chrono::{Local, TimeZone};
7
8use crate::pattern::Me;
9
10pub struct DraftHeaders {
11 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
22pub 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
49pub const DEFAULT_ATTRIBUTION: &str = "On %d, %n wrote:";
51
52pub const DEFAULT_FORWARD_FORMAT: &str = "[%a: %s]";
54
55pub const DEFAULT_INDENT: &str = "> ";
57
58pub struct Quoted<'a> {
61 pub from: &'a str,
63 pub subject: &'a str,
64 pub message_id: Option<&'a str>,
65 pub date: i64,
67}
68
69impl Quoted<'_> {
70 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
89pub fn render_quoted(fmt: &str, m: &Quoted) -> String {
94 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
113fn 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
139pub const REPLY_REGEXP: &str = r"^(re)(\[[0-9]+\])*:[ \t]*";
142
143pub 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
159pub fn reply_subject(orig: &str, re: ®ex_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
171pub 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
185pub fn attribution(fmt: &str, m: &Quoted) -> String {
187 render_quoted(fmt, m)
188}
189
190pub 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
200pub 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
226pub 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
250pub fn with_signature(body: &str, signature: &str, dashes: bool) -> String {
253 with_signature_at(body, signature, dashes, false)
254}
255
256pub 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
300pub fn user_agent_header() -> String {
303 format!("User-Agent: rmut/{}", env!("CARGO_PKG_VERSION"))
304}
305
306pub fn finalize(draft: &str, from: &str, msg_id: &str, date: &str) -> Result<String> {
308 finalize_with(draft, from, msg_id, date, false)
309}
310
311pub 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
343pub struct Attachment {
345 pub path: PathBuf,
346 pub mime: Option<String>,
349 pub description: Option<String>,
350 pub name: Option<String>,
353 pub inline: bool,
356 pub unlink: bool,
359}
360
361impl Attachment {
362 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 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
388fn 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
399pub 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 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
428pub 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 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; }
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
508pub 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
531fn 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
542pub 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
561pub 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
581pub 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 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
651pub 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
660pub 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
680pub 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
720pub 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
753pub 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
803pub 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
863pub fn from_address(text: &str) -> Option<String> {
865 let mail = mailparse::parse_mail(text.as_bytes()).ok()?;
866 bare_address(&crate::rfc2047::first(&mail.get_headers(), "From")?)
867}
868
869fn field_addresses(value: &str, out: &mut Vec<String>) {
870 let Ok(list) = mailparse::addrparse(value) else {
871 return;
872 };
873 for addr in list.iter() {
874 match addr {
875 mailparse::MailAddr::Single(single) => out.push(single.addr.clone()),
876 mailparse::MailAddr::Group(group) => {
877 out.extend(group.addrs.iter().map(|a| a.addr.clone()));
878 }
879 }
880 }
881}
882
883pub fn addresses(field: &str) -> Vec<String> {
885 let mut out = Vec::new();
886 field_addresses(field, &mut out);
887 out
888}
889
890pub fn reverse_from(orig_to: &str, orig_cc: &str, me: Me, realname: bool) -> Option<String> {
894 let mine = |single: &mailparse::SingleInfo| -> Option<String> {
895 if !me.is_me(&single.addr) {
896 return None;
897 }
898 Some(match &single.display_name {
899 Some(name) if realname && !name.trim().is_empty() => {
902 format!("{name} <{}>", single.addr)
903 }
904 _ => single.addr.clone(),
905 })
906 };
907 for field in [orig_to, orig_cc] {
908 let Ok(list) = mailparse::addrparse(field) else {
909 continue;
910 };
911 for addr in list.iter() {
912 match addr {
913 mailparse::MailAddr::Single(single) => {
914 if let Some(from) = mine(single) {
915 return Some(from);
916 }
917 }
918 mailparse::MailAddr::Group(group) => {
919 if let Some(from) = group.addrs.iter().find_map(&mine) {
920 return Some(from);
921 }
922 }
923 }
924 }
925 }
926 None
927}
928
929pub fn smtp_envelope(text: &str) -> Result<(Vec<String>, String)> {
932 let mail = mailparse::parse_mail(text.as_bytes())?;
933 let mut rcpts = Vec::new();
934 for header in &mail.headers {
935 let key = header.get_key();
936 if ["to", "cc", "bcc"].contains(&key.to_lowercase().as_str()) {
937 field_addresses(&crate::rfc2047::value(header), &mut rcpts);
938 }
939 }
940 rcpts.dedup();
941 let (head, body) = text.split_once("\n\n").unwrap_or((text.trim_end(), ""));
942 let mut out = String::new();
943 let mut skipping = false;
944 for line in head.lines() {
945 if line.starts_with(' ') || line.starts_with('\t') {
946 if skipping {
948 continue;
949 }
950 } else {
951 skipping = line
952 .split_once(':')
953 .is_some_and(|(k, _)| k.trim().eq_ignore_ascii_case("bcc"));
954 }
955 if !skipping {
956 out.push_str(line);
957 out.push('\n');
958 }
959 }
960 out.push('\n');
961 out.push_str(body);
962 Ok((rcpts, out))
963}
964
965#[cfg(test)]
966mod tests {
967 use super::*;
968
969 #[test]
970 fn a_forward_can_come_in_quoted() {
971 let plain = forward_body("Ann <ann@x>", 0, "hi", "one\ntwo\n", None);
972 assert!(plain.contains("\none\ntwo\n"), "{plain}");
973 let quoted = forward_body("Ann <ann@x>", 0, "hi", "one\ntwo\n", Some("> "));
974 assert!(quoted.contains("\n> one\n> two\n"), "{quoted}");
975 assert!(quoted.starts_with("----- Forwarded message from Ann <ann@x> -----"));
977 assert!(quoted.ends_with("----- End forwarded message -----\n"));
978 }
979
980 #[test]
981 fn the_signature_sits_under_a_dashes_line() {
982 let body = with_signature("hello\n", "Ann\nx.example", true);
983 assert_eq!(body, "hello\n\n-- \nAnn\nx.example\n");
984 assert_eq!(with_signature("hello\n", "Ann", false), "hello\n\nAnn\n");
986 assert_eq!(with_signature("", "Ann", true), "\n-- \nAnn\n");
988 }
989
990 #[test]
991 fn a_signature_comes_from_a_file_or_a_command() {
992 let dir = std::env::temp_dir().join(format!("rmut-sig-{}", std::process::id()));
993 std::fs::create_dir_all(&dir).unwrap();
994 let file = dir.join("signature");
995 std::fs::write(&file, "Ann\n\n\n").unwrap();
996 assert_eq!(
998 signature_text(file.to_str().unwrap()).as_deref(),
999 Some("Ann")
1000 );
1001 assert_eq!(signature_text("echo hello|").as_deref(), Some("hello"));
1002 assert_eq!(signature_text(dir.join("gone").to_str().unwrap()), None);
1004 assert_eq!(signature_text(" "), None);
1005 assert_eq!(signature_text("true|"), None);
1006 std::fs::remove_dir_all(&dir).unwrap();
1007 }
1008
1009 #[test]
1010 fn list_post_addresses() {
1011 assert_eq!(
1012 list_post_address("<mailto:dev@example.com>").as_deref(),
1013 Some("dev@example.com")
1014 );
1015 assert_eq!(
1016 list_post_address("<mailto:dev@example.com?subject=help>").as_deref(),
1017 Some("dev@example.com")
1018 );
1019 assert_eq!(
1020 list_post_address("NOTE: <mailto:dev@example.com>, <http://x/post>").as_deref(),
1021 Some("dev@example.com")
1022 );
1023 assert_eq!(list_post_address("NO"), None);
1025 assert_eq!(list_post_address("<http://example.com/post>"), None);
1026 }
1027
1028 #[test]
1029 fn followup_to_drops_me_only_when_subscribed() {
1030 let addrs = vec!["alex@example.com".to_string()];
1031 let me = Me::addresses(&addrs);
1032 let subscribed = followup_to(
1033 "dev@example.com, Alex <alex@example.com>",
1034 "",
1035 me,
1036 true,
1037 "Alex <alex@example.com>",
1038 );
1039 assert_eq!(subscribed, "dev@example.com");
1040 let unsubscribed = followup_to(
1041 "dev@example.com",
1042 "petr@example.com",
1043 me,
1044 false,
1045 "Alex <alex@example.com>",
1046 );
1047 assert_eq!(
1048 unsubscribed,
1049 "dev@example.com, petr@example.com, Alex <alex@example.com>"
1050 );
1051 let once = followup_to(
1053 "dev@example.com, alex@example.com",
1054 "",
1055 me,
1056 false,
1057 "Alex <alex@example.com>",
1058 );
1059 assert_eq!(once, "dev@example.com, alex@example.com");
1060 }
1061
1062 #[test]
1063 fn group_reply_drops_me_and_the_sender() {
1064 let addrs = vec!["alex@example.com".to_string()];
1065 let alternates = vec![crate::pattern::Matcher::new("^jp@old\\.example\\.com$")];
1066 let me = Me::new(&addrs, &alternates);
1067 let cc = group_recipients(
1068 "Team <team@example.com>, Alex <alex@example.com>, jp@old.example.com",
1069 "boss@example.com, team@example.com",
1070 "Petr <petr@example.com>",
1071 me,
1072 false,
1073 );
1074 assert_eq!(cc, "Team <team@example.com>, boss@example.com");
1077 let cc = group_recipients(
1079 "team@example.com, alex@example.com",
1080 "",
1081 "petr@example.com",
1082 me,
1083 true,
1084 );
1085 assert_eq!(cc, "team@example.com, alex@example.com");
1086 }
1087
1088 #[test]
1089 fn text_flowed_declares_and_stuffs_the_body() {
1090 let entity = text_entity("plain\n>looks quoted\n", true);
1091 assert!(
1092 entity.starts_with("Content-Type: text/plain; charset=utf-8; format=flowed\r\n"),
1093 "{entity}"
1094 );
1095 assert!(
1096 entity.ends_with("plain\r\n >looks quoted\r\n"),
1097 "{entity:?}"
1098 );
1099 let plain = text_entity("plain\n>looks quoted\n", false);
1101 assert!(plain.starts_with("Content-Type: text/plain; charset=utf-8\r\n"));
1102 assert!(plain.ends_with("plain\r\n>looks quoted\r\n"), "{plain:?}");
1103 }
1104
1105 #[test]
1106 fn flow_plain_declares_an_unwrapped_draft() {
1107 let draft = "From: a@x\nTo: b@x\nSubject: s\n\n>quoted line\n";
1108 let out = flow_plain(draft);
1109 assert!(out.contains("Content-Type: text/plain; charset=utf-8; format=flowed\n"));
1110 assert!(out.ends_with("\n\n >quoted line\n"), "{out:?}");
1111 let typed = "From: a@x\nContent-Type: text/x-diff\n\nbody\n";
1113 assert_eq!(flow_plain(typed), typed);
1114 }
1115
1116 #[test]
1117 fn draft_envelope_reads_the_header_block() {
1118 let draft = "From: Jane Doe <jane@example.com>\n\
1119 To: Bob <BOB@work.example.com>, team@x\n\
1120 Cc: boss@x\n\
1121 Bcc: archive@x\n\
1122 Subject: quarterly\n\n\
1123 two\nlines\n";
1124 let env = draft_envelope(draft, std::path::Path::new("/tmp/draft"));
1125 assert_eq!(env.subject, "quarterly");
1126 assert_eq!(env.from_full, "Jane Doe <jane@example.com>");
1127 assert_eq!(env.to, ["bob@work.example.com", "team@x"]);
1128 assert_eq!(env.cc, ["boss@x", "archive@x"]);
1130 assert_eq!(env.lines, Some(2));
1131 let hit = |p: &str| {
1132 crate::pattern::matches_in(
1133 &crate::pattern::parse(p).unwrap(),
1134 &env,
1135 crate::pattern::Scope::default(),
1136 None,
1137 )
1138 };
1139 assert!(hit("~t @work\\.example\\.com"));
1140 assert!(hit("~c archive@"));
1141 assert!(hit("~A"));
1142 assert!(!hit("~t nobody@"));
1143 }
1144
1145 #[test]
1146 fn my_hdr_merges_into_the_draft_head() {
1147 let draft = "From: jane@example.com\nTo: bob@x\nSubject: s\n\nbody\n";
1148 let merged = apply_my_hdr(
1149 draft,
1150 &[
1151 "Organization: Acme".to_string(),
1152 "From: Jane <jane@work.example.com>".into(),
1153 "Bcc: jane@example.com".into(),
1154 "To: archive@x".into(),
1155 "bogus".into(),
1156 ],
1157 );
1158 assert_eq!(
1159 merged,
1160 "From: Jane <jane@work.example.com>\n\
1161 To: bob@x, archive@x\n\
1162 Subject: s\n\
1163 Organization: Acme\n\
1164 Bcc: jane@example.com\n\
1165 \nbody\n"
1166 );
1167 assert_eq!(apply_my_hdr(draft, &[]), draft);
1169 }
1170
1171 fn quoted() -> Quoted<'static> {
1173 Quoted {
1174 from: "Jane Doe <jane@example.com>",
1175 subject: "Lunch",
1176 message_id: Some("<m1@example.com>"),
1177 date: 1_710_151_200,
1179 }
1180 }
1181
1182 #[test]
1183 fn subjects_do_not_stack_prefixes() {
1184 let re = default_reply_regexp();
1185 assert_eq!(reply_subject("Lunch", &re), "Re: Lunch");
1186 assert_eq!(reply_subject("RE: Lunch", &re), "Re: Lunch");
1187 assert_eq!(reply_subject("Re[2]: Lunch", &re), "Re: Lunch");
1188 let aw = reply_regexp("^(re|aw|sv):[ \t]*").unwrap();
1191 assert_eq!(reply_subject("AW: Lunch", &aw), "Re: Lunch");
1192 let exact = reply_regexp("^(Re):[ \t]*").unwrap();
1193 assert_eq!(reply_subject("RE: Lunch", &exact), "Re: RE: Lunch");
1194 assert_eq!(
1195 forward_subject(DEFAULT_FORWARD_FORMAT, "ed()),
1196 "[jane@example.com: Lunch]"
1197 );
1198 }
1199
1200 #[test]
1201 fn quote_prefixes_every_line_with_the_indent_string() {
1202 assert_eq!(
1203 quote("On X, Y wrote:", DEFAULT_INDENT, "a\nb"),
1204 "On X, Y wrote:\n> a\n> b\n"
1205 );
1206 assert_eq!(quote("head", "| ", "a"), "head\n| a\n");
1207 }
1208
1209 #[test]
1210 fn an_attribution_says_who_and_when() {
1211 let m = quoted();
1212 let line = attribution(DEFAULT_ATTRIBUTION, &m);
1214 assert!(line.starts_with("On "), "{line}");
1215 assert!(line.ends_with(", Jane Doe wrote:"), "{line}");
1216 assert_eq!(render_quoted("%a", &m), "jane@example.com");
1218 assert_eq!(render_quoted("%n", &m), "Jane Doe");
1219 assert_eq!(render_quoted("%f", &m), "Jane Doe <jane@example.com>");
1220 assert_eq!(render_quoted("%s", &m), "Lunch");
1221 assert_eq!(render_quoted("%i", &m), "m1@example.com");
1222 assert_eq!(render_quoted("100%%", &m), "100%");
1223 assert_eq!(render_quoted("%q", &m), "%q");
1224 assert_eq!(render_quoted("%{%Y}", &m), "2024");
1226 assert_eq!(render_quoted("[%{%Y}] %s", &m), "[2024] Lunch");
1227 }
1228
1229 #[test]
1230 fn a_name_falls_back_to_the_address() {
1231 let m = Quoted {
1232 from: "bare@example.com",
1233 subject: "x",
1234 message_id: None,
1235 date: 0,
1236 };
1237 assert_eq!(render_quoted("%n", &m), "bare@example.com");
1238 assert_eq!(render_quoted("%i", &m), "");
1239 }
1240
1241 #[test]
1242 fn draft_text_skips_empty_optional_headers() {
1243 let text = draft_text(
1244 &DraftHeaders {
1245 from: None,
1246 to: "a@x".into(),
1247 cc: Some("".into()),
1248 subject: "s".into(),
1249 in_reply_to: None,
1250 references: None,
1251 },
1252 "hi",
1253 );
1254 assert_eq!(text, "To: a@x\nSubject: s\n\nhi\n");
1255 let text = draft_text(
1256 &DraftHeaders {
1257 from: Some("Jane Work <jane@work.example.com>".into()),
1258 to: "a@x".into(),
1259 cc: None,
1260 subject: "s".into(),
1261 in_reply_to: None,
1262 references: None,
1263 },
1264 "hi",
1265 );
1266 assert!(text.starts_with("From: Jane Work <jane@work.example.com>\nTo: a@x\n"));
1267 }
1268
1269 #[test]
1270 fn reverse_from_finds_my_address_as_it_appeared() {
1271 let addrs = vec!["jane@example.com".to_string(), "old@example.com".into()];
1272 let me = Me::addresses(&addrs);
1273 assert_eq!(
1275 reverse_from("Boss Me <Jane@example.com>, bob@y", "", me, true).as_deref(),
1276 Some("Boss Me <Jane@example.com>")
1277 );
1278 assert_eq!(
1280 reverse_from("Boss Me <Jane@example.com>, bob@y", "", me, false).as_deref(),
1281 Some("Jane@example.com")
1282 );
1283 assert_eq!(
1285 reverse_from("bob@y", "old@example.com", me, true).as_deref(),
1286 Some("old@example.com")
1287 );
1288 assert_eq!(reverse_from("bob@y, eve@z", "", me, true), None);
1289 assert_eq!(reverse_from("", "", me, true), None);
1290 }
1291
1292 #[test]
1293 fn finalize_adds_missing_headers_once() {
1294 let draft = "To: a@x\nSubject: s\n\nbody\n";
1295 let out = finalize(draft, "me@host", "<id@host>", "DATE").unwrap();
1296 assert!(out.contains("From: me@host"));
1297 assert!(out.contains("Message-ID: <id@host>"));
1298 assert!(out.contains("Date: DATE"));
1299 assert!(out.ends_with("\n\nbody\n"));
1300 let draft2 = "To: a@x\nFrom: custom@x\n\nbody\n";
1302 let out2 = finalize(draft2, "me@host", "<i>", "D").unwrap();
1303 assert!(out2.contains("From: custom@x"));
1304 assert!(!out2.contains("me@host"));
1305 }
1306
1307 #[test]
1308 fn user_agent_and_signature_placement() {
1309 let draft = "To: a@b\n\nhi";
1310 let plain = finalize_with(draft, "me@x", "<id@h>", "Mon", false).unwrap();
1311 assert!(!plain.contains("User-Agent"));
1312 let ua = finalize_with(draft, "me@x", "<id@h>", "Mon", true).unwrap();
1313 assert!(ua.contains(&user_agent_header()), "{ua}");
1314 let own = finalize_with(
1316 "To: a@b\nUser-Agent: mine\n\nhi",
1317 "me@x",
1318 "<id@h>",
1319 "Mon",
1320 true,
1321 )
1322 .unwrap();
1323 assert_eq!(own.matches("User-Agent").count(), 1, "{own}");
1324 let below = with_signature_at("the reply", "Jane", true, false);
1326 assert!(below.trim_end().ends_with("Jane"), "{below}");
1327 let above = with_signature_at("the reply", "Jane", true, true);
1328 assert!(above.starts_with("-- \nJane\n"), "{above}");
1329 assert!(above.trim_end().ends_with("the reply"), "{above}");
1330 }
1331
1332 #[test]
1333 fn finalize_rejects_missing_recipients() {
1334 assert!(finalize("Subject: s\n\nbody", "f", "<i>", "d").is_err());
1335 assert!(finalize("To: \nSubject: s\n\nbody", "f", "<i>", "d").is_err());
1336 assert!(finalize("Bcc: a@x\n\nbody", "f", "<i>", "d").is_ok());
1337 }
1338
1339 #[test]
1340 fn bare_address_drops_display_name() {
1341 assert_eq!(
1342 bare_address("Jane <jane@x.org>").as_deref(),
1343 Some("jane@x.org")
1344 );
1345 assert_eq!(bare_address("jane@x.org").as_deref(), Some("jane@x.org"));
1346 assert_eq!(bare_address(""), None);
1347 }
1348
1349 #[test]
1350 fn smtp_envelope_collects_rcpts_and_strips_bcc() {
1351 let text =
1352 "To: Alice <a@x>, b@y\nCc: c@z\nBcc: hidden@q,\n also-hidden@q\nSubject: s\n\nbody\n";
1353 let (rcpts, out) = smtp_envelope(text).unwrap();
1354 assert_eq!(
1355 rcpts,
1356 vec!["a@x", "b@y", "c@z", "hidden@q", "also-hidden@q"]
1357 );
1358 assert!(!out.to_lowercase().contains("bcc"));
1359 assert!(!out.contains("hidden@q"));
1360 assert!(out.contains("To: Alice <a@x>, b@y\n"));
1361 assert!(out.ends_with("\n\nbody\n"));
1362 }
1363
1364 #[test]
1365 fn extract_attachments_takes_the_pseudo_headers_out() {
1366 let draft = "To: a@x\nAttach: /tmp/report.pdf the Q2 numbers\n\
1367 attach: \"/tmp/two words.png\"\nAttach:\nSubject: s\n\nbody\n";
1368 let (out, files) = extract_attachments(draft);
1369 assert_eq!(out, "To: a@x\nSubject: s\n\nbody\n");
1370 assert_eq!(files.len(), 2);
1371 assert_eq!(files[0].path, PathBuf::from("/tmp/report.pdf"));
1372 assert_eq!(files[0].description.as_deref(), Some("the Q2 numbers"));
1373 assert_eq!(files[1].path, PathBuf::from("/tmp/two words.png"));
1374 assert_eq!(files[1].description, None);
1375 }
1376
1377 #[test]
1378 fn attach_lines_carry_a_type_override() {
1379 let draft = "Attach: /tmp/x.bin application/x-custom raw dump\n\
1380 Attach: /tmp/y.txt see notes\n\n";
1381 let (_, files) = extract_attachments(draft);
1382 assert_eq!(files[0].mime.as_deref(), Some("application/x-custom"));
1383 assert_eq!(files[0].description.as_deref(), Some("raw dump"));
1384 assert_eq!(files[1].mime, None);
1386 assert_eq!(files[1].description.as_deref(), Some("see notes"));
1387 let line = attach_line(&files[0]);
1389 assert_eq!(line, "Attach: /tmp/x.bin application/x-custom raw dump");
1390 let (_, roundtrip) = extract_attachments(&format!("{line}\n\n"));
1391 assert_eq!(roundtrip[0].mime.as_deref(), Some("application/x-custom"));
1392 let spaced = Attachment {
1394 path: PathBuf::from("/tmp/two words.png"),
1395 mime: Some("image/png".into()),
1396 description: None,
1397 name: None,
1398 inline: false,
1399 unlink: false,
1400 };
1401 let (_, files) = extract_attachments(&format!("{}\n\n", attach_line(&spaced)));
1402 assert_eq!(files[0].path, PathBuf::from("/tmp/two words.png"));
1403 assert_eq!(files[0].mime.as_deref(), Some("image/png"));
1404 }
1405
1406 #[test]
1407 fn extract_attachments_leaves_plain_drafts_alone() {
1408 let draft = "To: a@x\nSubject: s\n\nAttach: not a header, body text\n";
1409 let (out, files) = extract_attachments(draft);
1410 assert_eq!(out, draft);
1411 assert!(files.is_empty());
1412 }
1413
1414 #[test]
1415 fn mixed_entity_encodes_files_and_original() {
1416 use mailparse::MailHeaderMap;
1417 let dir = std::env::temp_dir().join(format!("rmut-attach-test-{}", std::process::id()));
1418 std::fs::create_dir_all(&dir).unwrap();
1419 let blob: Vec<u8> = (0..=255u8).collect();
1420 std::fs::write(dir.join("blob.bin"), &blob).unwrap();
1421 let files = [Attachment {
1422 path: dir.join("blob.bin"),
1423 mime: None,
1424 description: Some("raw bytes".into()),
1425 name: None,
1426 inline: false,
1427 unlink: false,
1428 }];
1429 let orig = b"From: jane@x\r\nSubject: hi\r\n\r\noriginal body\r\n";
1430 let entity = mixed_entity("see attached", &files, Some(orig), false).unwrap();
1431 let mail = mailparse::parse_mail(entity.as_bytes()).unwrap();
1432 assert_eq!(mail.ctype.mimetype, "multipart/mixed");
1433 assert_eq!(mail.subparts.len(), 3);
1434 assert_eq!(mail.subparts[0].get_body().unwrap().trim(), "see attached");
1435 let file = &mail.subparts[1];
1436 assert_eq!(file.ctype.mimetype, "application/octet-stream");
1437 assert_eq!(file.get_body_raw().unwrap(), blob);
1438 let disp = file.get_headers().get_first_value("Content-Disposition");
1439 assert!(disp.unwrap().contains("filename=\"blob.bin\""));
1440 assert_eq!(
1441 file.get_headers()
1442 .get_first_value("Content-Description")
1443 .as_deref(),
1444 Some("raw bytes")
1445 );
1446 assert_eq!(mail.subparts[2].ctype.mimetype, "message/rfc822");
1447 assert!(
1448 mail.subparts[2]
1449 .get_body()
1450 .unwrap()
1451 .contains("original body")
1452 );
1453 std::fs::remove_dir_all(&dir).unwrap();
1454 }
1455
1456 #[test]
1457 fn mixed_entity_reports_a_missing_file() {
1458 let files = [Attachment {
1459 path: PathBuf::from("/nonexistent/nope.pdf"),
1460 mime: None,
1461 description: None,
1462 name: None,
1463 inline: false,
1464 unlink: false,
1465 }];
1466 let err = mixed_entity("hi", &files, None, false).unwrap_err();
1467 assert!(err.to_string().contains("/nonexistent/nope.pdf"));
1468 }
1469
1470 #[test]
1471 fn bounce_text_prepends_resent_headers() {
1472 let orig = b"From: jane@x\nSubject: hi\n\nbody\n";
1473 let out = bounce_text(orig, "Me <me@x>", "bob@y", "DATE", "<id@x>");
1474 assert!(out.starts_with("Resent-From: Me <me@x>\r\n"));
1475 assert!(out.contains("Resent-Date: DATE\r\n"));
1476 assert!(out.contains("Resent-To: bob@y\r\n"));
1477 assert!(out.ends_with("From: jane@x\nSubject: hi\n\nbody\n"));
1478 }
1479
1480 #[test]
1481 fn smtp_envelope_without_bcc_is_unchanged() {
1482 let text = "To: a@x\nSubject: s\n\nbody\n";
1483 let (rcpts, out) = smtp_envelope(text).unwrap();
1484 assert_eq!(rcpts, vec!["a@x"]);
1485 assert_eq!(out, text);
1486 }
1487
1488 #[test]
1489 fn attach_line_options_round_trip() {
1490 let mut a = Attachment::of(PathBuf::from("/tmp/q2 report.pdf"));
1491 a.mime = Some("application/pdf".into());
1492 a.name = Some("report.pdf".into());
1493 a.inline = true;
1494 a.unlink = true;
1495 a.description = Some("the Q2 numbers".into());
1496 let line = attach_line(&a);
1497 assert_eq!(
1498 line,
1499 "Attach: \"/tmp/q2 report.pdf\" application/pdf @name=\"report.pdf\" @inline @unlink the Q2 numbers"
1500 );
1501 let (_, back) = extract_attachments(&format!("To: x\n{line}\n\nbody"));
1502 assert_eq!(back.len(), 1);
1503 let b = &back[0];
1504 assert_eq!(b.path, a.path);
1505 assert_eq!(b.mime.as_deref(), Some("application/pdf"));
1506 assert_eq!(b.name.as_deref(), Some("report.pdf"));
1507 assert!(b.inline && b.unlink);
1508 assert_eq!(b.description.as_deref(), Some("the Q2 numbers"));
1509 let (_, plain) = extract_attachments("Attach: /tmp/a.txt text/plain @home notes\n\n");
1512 assert!(!plain[0].inline && plain[0].name.is_none());
1513 assert_eq!(plain[0].description.as_deref(), Some("@home notes"));
1514 }
1515
1516 #[test]
1517 fn mixed_entity_honours_name_disposition_and_rfc822() {
1518 let dir = std::env::temp_dir().join(format!("rmut-attach-opts-{}", std::process::id()));
1519 std::fs::create_dir_all(&dir).unwrap();
1520 let file = dir.join("data.bin");
1521 std::fs::write(&file, b"xyz").unwrap();
1522 let msg = dir.join("1.host:2,S");
1523 std::fs::write(&msg, "From: a@x\nSubject: inner\n\nhello\n").unwrap();
1524 let mut a = Attachment::of(file.clone());
1525 a.name = Some("renamed.bin".into());
1526 a.inline = true;
1527 let mut m = Attachment::of(msg.clone());
1528 m.mime = Some("message/rfc822".into());
1529 let entity = mixed_entity("see attached", &[a, m], None, false).unwrap();
1530 assert!(
1531 entity.contains("Content-Disposition: inline; filename=\"renamed.bin\""),
1532 "{entity}"
1533 );
1534 assert!(
1535 entity.contains(
1536 "Content-Type: message/rfc822\r\nContent-Disposition: attachment\r\n\r\nFrom: a@x"
1537 ),
1538 "{entity}"
1539 );
1540 assert!(
1541 !entity.contains("filename=\"1.host"),
1542 "a message has no filename"
1543 );
1544 let _ = std::fs::remove_dir_all(&dir);
1545 }
1546}