himalaya 2.2.1

CLI to manage emails
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
//! # Message builder
//!
//! The MIME assembly behind the `compose`, `reply` and `forward`
//! commands, which collapse into one set of fields once the source
//! message, if there is one, has been fetched.
//!
//! An RFC 5322 message comes out, headers derived from the source with
//! mail-parser and the whole assembled with mail-builder.

use std::{
    io::{IsTerminal, Read as _, stdin},
    path::{Path, PathBuf},
};

use anyhow::{Result, anyhow, bail};
use clap::ValueEnum;
use mail_builder::{
    MessageBuilder,
    headers::{address::Address, raw::Raw},
};
use mail_parser::{HeaderValue, MessageParser, parsers::MessageStream};

/// Where a quoted source body sits relative to the written one.
#[derive(Clone, Copy, Debug, ValueEnum)]
#[clap(rename_all = "kebab-case")]
pub enum PostingStyle {
    /// The written body above the quoted source body.
    Top,
    /// The quoted source body above the written body.
    Bottom,
    /// The written body alone, the source left unquoted, for a writer
    /// who already laid the quote out.
    None,
}

/// Everything the MIME assembler needs, which each command fills in from
/// its own clap struct.
pub struct BuilderArgs<'a> {
    /// Address the `From` header carries.
    ///
    /// A value spelling out a display name is split back apart rather
    /// than taken for one long address.
    pub from: Option<&'a str>,
    /// Name that address goes by, kept apart from it so mail-builder
    /// encodes it: a name holding a comma or a quote wants no rule here.
    pub from_name: Option<&'a str>,
    /// Addresses the `To` header carries.
    pub to: &'a [String],
    /// Addresses the `Cc` header carries.
    pub cc: &'a [String],
    /// Addresses the `Bcc` header carries.
    pub bcc: &'a [String],
    /// The `Subject` header.
    pub subject: Option<&'a str>,
    /// The text body, when it was given inline.
    pub body: Option<&'a str>,
    /// The file the text body is read from instead.
    pub body_file: Option<&'a Path>,
    /// The files to attach.
    pub attach: &'a [PathBuf],
    /// The signature, `None` when `signature_file` names the file holding
    /// it.
    pub signature: Option<&'a str>,
    /// The file the signature is read from instead.
    pub signature_file: Option<&'a Path>,
    /// Separator written before the signature, verbatim.
    pub signature_delim: &'a str,
}

/// The source message a reply or a forward is derived from.
pub struct SourceArgs<'a> {
    /// The raw RFC 5322 bytes of the source.
    pub raw: &'a [u8],
    /// Whether it is being replied to or forwarded.
    pub mode: SourceMode,
    /// Where its quoted body sits relative to the written one.
    pub posting_style: PostingStyle,
    /// The headline placed before its quoted body.
    pub quote_headline: &'a str,
}

/// Whether the source message is being replied to or forwarded.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SourceMode {
    /// The reply derives `In-Reply-To`, `References` and a `Re:` subject.
    Reply,
    /// The forward derives `References` and a `Fwd:` subject.
    Forward,
}

/// Assembles the raw RFC 5322 bytes of a message, deriving the reply or
/// forward headers when a source is given.
pub fn build(args: BuilderArgs<'_>, source: Option<SourceArgs<'_>>) -> Result<Vec<u8>> {
    let mut builder = MessageBuilder::new();

    if let Some(from) = args.from {
        let (parsed_name, address) = parse_mailboxes(from)?.remove(0);
        let name = args.from_name.map(str::to_owned).or(parsed_name);
        builder = builder.from(Address::new_address(name, address));
    }
    if !args.to.is_empty() {
        builder = builder.to(addresses(args.to)?);
    }
    if !args.cc.is_empty() {
        builder = builder.cc(addresses(args.cc)?);
    }
    if !args.bcc.is_empty() {
        builder = builder.bcc(addresses(args.bcc)?);
    }

    let parsed_source = source
        .as_ref()
        .and_then(|s| MessageParser::new().parse(s.raw));

    let mut subject = args.subject.map(str::to_owned);
    let mut source_text = String::new();

    if let (Some(source), Some(parsed)) = (source.as_ref(), parsed_source.as_ref()) {
        let prefix = match source.mode {
            SourceMode::Reply => "Re: ",
            SourceMode::Forward => "Fwd: ",
        };
        let src_subject = parsed.subject().unwrap_or("");
        if subject.is_none() {
            subject = Some(if has_prefix(src_subject, prefix) {
                src_subject.to_string()
            } else {
                format!("{prefix}{src_subject}")
            });
        }

        if source.mode == SourceMode::Reply
            && args.to.is_empty()
            && let Some(addrs) = reply_recipients(parsed)
        {
            builder = builder.to(addrs);
        }

        if let Some(message_id) = parsed.message_id() {
            if source.mode == SourceMode::Reply {
                builder = builder.in_reply_to(vec![message_id.to_string()]);
            }
            let refs = compute_references(parsed, message_id);
            if !refs.is_empty() {
                builder = builder.header("References", Raw::new(refs));
            }
        }

        source_text = parsed
            .body_text(0)
            .map(|c| c.into_owned())
            .unwrap_or_default();
    }

    if let Some(s) = subject {
        builder = builder.subject(s);
    }

    let user_body = read_body(args.body, args.body_file)?;
    let signature = read_signature(args.signature, args.signature_file)?;
    let (style, headline) = match source.as_ref() {
        Some(s) => (s.posting_style, s.quote_headline),
        None => (PostingStyle::Top, ""),
    };
    let body = compose_body(
        &user_body,
        &source_text,
        headline,
        signature.as_deref().unwrap_or(""),
        args.signature_delim,
        style,
    );
    builder = builder.text_body(body);

    for path in args.attach {
        let bytes = std::fs::read(path)
            .map_err(|err| anyhow!("read attachment {}: {err}", path.display()))?;
        let file_name = path
            .file_name()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_else(|| "attachment".to_string());
        let mime = mime_for(path);
        builder = builder.attachment(mime, file_name, bytes);
    }

    builder
        .write_to_vec()
        .map_err(|err| anyhow!("serialize composed message: {err}"))
}

/// Splits an address list into its mailboxes, each with its display
/// name, when it carries one, and its address.
///
/// Handing mail-builder the whole `Alice <alice@example.org>` as an
/// address would emit a `To: <Alice <alice@example.org>>` no SMTP
/// server accepts. A comma inside a quoted display name does not split
/// the list. The returned list is never empty.
fn parse_mailboxes(value: &str) -> Result<Vec<(Option<String>, String)>> {
    use mail_parser::Address as ParserAddress;

    // NOTE: the header parser flushes its last token on the
    // terminating newline, which a bare address, unlike one closed by
    // a `>`, does not otherwise carry.
    let header = format!("{value}\n");
    let parsed = MessageStream::new(header.as_bytes()).parse_address();

    let mailboxes: Vec<_> = match &parsed {
        HeaderValue::Address(ParserAddress::List(list)) => list.iter().collect(),
        HeaderValue::Address(ParserAddress::Group(groups)) => groups
            .iter()
            .flat_map(|group| group.addresses.iter())
            .collect(),
        _ => Vec::new(),
    };

    if mailboxes.is_empty() {
        bail!("Could not parse address `{value}`");
    }

    mailboxes
        .into_iter()
        .map(|mailbox| {
            let address = mailbox
                .address
                .as_ref()
                .ok_or_else(|| anyhow!("Address `{value}` has no email"))?
                .to_string();
            let name = mailbox.name.as_ref().map(|name| name.to_string());

            Ok((name, address))
        })
        .collect()
}

/// Builds one address list out of every mailbox the values carry.
fn addresses(values: &[String]) -> Result<Address<'static>> {
    let mut list = Vec::new();

    for value in values {
        for (name, address) in parse_mailboxes(value)? {
            list.push(Address::new_address(name, address));
        }
    }

    Ok(Address::new_list(list))
}

/// Reads the text body from the flag, the file it names, or piped
/// standard input.
fn read_body(body: Option<&str>, body_file: Option<&Path>) -> Result<String> {
    if let Some(body) = body {
        return Ok(body.to_owned());
    }

    if let Some(path) = body_file {
        return std::fs::read_to_string(path)
            .map_err(|err| anyhow!("read body file {}: {err}", path.display()));
    }

    if !stdin().is_terminal() {
        let mut buf = String::new();
        stdin().read_to_string(&mut buf)?;
        return Ok(buf);
    }

    Ok(String::new())
}

/// Reads the signature from the flag or the file it names.
fn read_signature(
    signature: Option<&str>,
    signature_file: Option<&Path>,
) -> Result<Option<String>> {
    if let Some(sig) = signature {
        return Ok(Some(sig.to_owned()));
    }

    if let Some(path) = signature_file {
        let s = std::fs::read_to_string(path)
            .map_err(|err| anyhow!("read signature file {}: {err}", path.display()))?;
        return Ok(Some(s));
    }

    Ok(None)
}

/// Lays out the final text body: the written text, the quoted source
/// under its headline, and the signature after its separator.
fn compose_body(
    user_body: &str,
    source_text: &str,
    headline: &str,
    signature: &str,
    signature_delim: &str,
    style: PostingStyle,
) -> String {
    let user_body = user_body.trim_end_matches('\n');
    let source_text = source_text.trim();

    let quote = if source_text.is_empty() {
        String::new()
    } else {
        let mut buf = String::new();
        if !headline.is_empty() {
            buf.push_str(headline.trim_end_matches('\n'));
            buf.push('\n');
        }
        for line in source_text.lines() {
            buf.push('>');
            if !line.starts_with('>') {
                buf.push(' ');
            }
            buf.push_str(line);
            buf.push('\n');
        }
        buf.pop();
        buf
    };

    let mut body = match (style, quote.is_empty()) {
        (PostingStyle::None, _) | (_, true) => user_body.to_string(),
        (PostingStyle::Top, false) => {
            if user_body.is_empty() {
                quote
            } else {
                format!("{user_body}\n\n{quote}")
            }
        }
        (PostingStyle::Bottom, false) => {
            if user_body.is_empty() {
                quote
            } else {
                format!("{quote}\n\n{user_body}")
            }
        }
    };

    // NOTE: the separator is written verbatim, its own trailing
    // newline included, so a delimiter meant to stand on its own line
    // says so rather than relying on a rule here.
    if !signature.trim().is_empty() {
        body.push_str("\n\n");
        body.push_str(signature_delim);
        body.push_str(signature.trim_end_matches('\n'));
    }

    body
}

/// Whether a subject already carries a `Re:` or `Fwd:` prefix.
fn has_prefix(subject: &str, prefix: &str) -> bool {
    let s = subject.trim_start();
    // NOTE: the colon is part of the comparison, letters alone reading
    // "Ready to ship" as already `Re:`-prefixed.
    let p = prefix.trim();
    s.len() >= p.len() && s.get(..p.len()).map(|h| h.eq_ignore_ascii_case(p)) == Some(true)
}

/// Derives the recipients of a reply from the source's `Reply-To`, or
/// from its `From` when it names none.
fn reply_recipients(msg: &mail_parser::Message<'_>) -> Option<Address<'static>> {
    use mail_parser::Address as ParserAddress;

    let header = msg
        .header("Reply-To")
        .or_else(|| msg.header("From"))
        .cloned();

    let HeaderValue::Address(addr) = header? else {
        return None;
    };

    let collected: Vec<Address<'static>> = match addr {
        ParserAddress::List(list) => list
            .into_iter()
            .filter_map(|a| {
                let email = a.address?.into_owned();
                let name = a.name.map(|s| s.into_owned());
                Some(Address::new_address(name, email))
            })
            .collect(),
        ParserAddress::Group(groups) => groups
            .into_iter()
            .flat_map(|g| g.addresses.into_iter())
            .filter_map(|a| {
                let email = a.address?.into_owned();
                let name = a.name.map(|s| s.into_owned());
                Some(Address::new_address(name, email))
            })
            .collect(),
    };

    if collected.is_empty() {
        None
    } else {
        Some(Address::new_list(collected))
    }
}

/// Builds the `References` header of a reply: the source's own chain,
/// or its `In-Reply-To`, with the source id appended.
fn compute_references(msg: &mail_parser::Message<'_>, source_message_id: &str) -> String {
    let mut out = String::new();

    if let Some(header) = msg.header("References") {
        if let HeaderValue::TextList(items) = header {
            for r in items {
                push_msg_id(&mut out, r);
            }
        } else if let HeaderValue::Text(s) = header {
            for r in s.split_whitespace() {
                push_msg_id(&mut out, r);
            }
        }
    } else if let Some(header) = msg.header("In-Reply-To") {
        if let HeaderValue::TextList(items) = header {
            for r in items {
                push_msg_id(&mut out, r);
            }
        } else if let HeaderValue::Text(s) = header {
            for r in s.split_whitespace() {
                push_msg_id(&mut out, r);
            }
        }
    }

    push_msg_id(&mut out, source_message_id);
    out
}

/// Appends one message id to a `References` chain, wrapped in angle
/// brackets.
fn push_msg_id(out: &mut String, id: &str) {
    let id = id.trim();
    if id.is_empty() {
        return;
    }
    if !out.is_empty() {
        out.push(' ');
    }
    if id.starts_with('<') {
        out.push_str(id);
    } else {
        out.push('<');
        out.push_str(id);
        out.push('>');
    }
}

/// Guesses the MIME type of an attachment from its path.
fn mime_for(path: &Path) -> String {
    mime_guess::from_path(path)
        .first_or_octet_stream()
        .essence_str()
        .to_owned()
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A raw source message for the reply and forward tests, carrying a
    /// `References` header so threading can be asserted.
    const SOURCE: &[u8] = b"From: Alice <alice@example.com>\r\n\
To: Bob <bob@example.com>\r\n\
Subject: Project update\r\n\
Message-ID: <orig-2@example.com>\r\n\
References: <orig-0@example.com> <orig-1@example.com>\r\n\
\r\n\
Original body line.\r\n";

    fn parse(raw: &[u8]) -> mail_parser::Message<'_> {
        MessageParser::new()
            .parse(raw)
            .expect("parse built message")
    }

    fn source(mode: SourceMode) -> SourceArgs<'static> {
        SourceArgs {
            raw: SOURCE,
            mode,
            posting_style: PostingStyle::Top,
            quote_headline: "On a day, Alice wrote:",
        }
    }

    fn args<'a>(
        from: &'a str,
        to: &'a [String],
        subject: Option<&'a str>,
        body: &'a str,
    ) -> BuilderArgs<'a> {
        BuilderArgs {
            from: Some(from),
            from_name: None,
            to,
            cc: &[],
            bcc: &[],
            subject,
            body: Some(body),
            body_file: None,
            attach: &[],
            signature: None,
            signature_file: None,
            signature_delim: "-- \n",
        }
    }

    #[test]
    fn compose_populates_headers_and_body() {
        let to = vec!["bob@example.com".to_string()];
        let cc = vec!["carol@example.com".to_string()];
        let mut a = args("alice@example.com", &to, Some("Hello"), "Hi Bob");
        a.cc = &cc;

        let raw = build(a, None).unwrap();
        let msg = parse(&raw);
        let text = String::from_utf8(raw.clone()).unwrap();

        assert_eq!(msg.subject(), Some("Hello"));
        assert!(msg.body_text(0).unwrap().contains("Hi Bob"));
        assert!(text.contains("alice@example.com"));
        assert!(text.contains("bob@example.com"));
        assert!(text.contains("carol@example.com"));
        assert!(!text.contains("In-Reply-To"));
    }

    #[test]
    fn compose_names_the_from_address() {
        let to = vec!["bob@example.com".to_string()];
        let mut a = args("alice@example.com", &to, Some("Hello"), "Hi Bob");
        // NOTE: a comma is what an unquoted display name breaks on, the
        // header then reading as two addresses.
        a.from_name = Some("Doe, Alice");

        let raw = build(a, None).unwrap();
        let text = String::from_utf8(raw).unwrap();

        assert!(text.contains("From: \"Doe, Alice\" <alice@example.com>"));
    }

    #[test]
    fn reply_sets_subject_recipients_and_threading() {
        let empty: Vec<String> = Vec::new();
        let a = args("bob@example.com", &empty, None, "My reply");

        let raw = build(a, Some(source(SourceMode::Reply))).unwrap();
        let msg = parse(&raw);
        let text = String::from_utf8(raw.clone()).unwrap();

        assert_eq!(msg.subject(), Some("Re: Project update"));
        assert!(text.contains("alice@example.com"));
        assert!(text.contains("In-Reply-To:"));
        assert!(text.contains("orig-2@example.com"));
        let body = msg.body_text(0).unwrap();
        assert!(body.contains("My reply"));
        assert!(body.contains("On a day, Alice wrote:"));
        assert!(body.contains("> Original body line."));
    }

    #[test]
    fn reply_keeps_existing_re_prefix() {
        let raw = b"Subject: Re: Already replied\r\nMessage-ID: <x@e>\r\n\r\nbody";
        let src = SourceArgs {
            raw,
            mode: SourceMode::Reply,
            posting_style: PostingStyle::Top,
            quote_headline: "",
        };
        let empty: Vec<String> = Vec::new();
        let built = build(args("b@e", &empty, None, "r"), Some(src)).unwrap();
        assert_eq!(parse(&built).subject(), Some("Re: Already replied"));
    }

    #[test]
    fn reply_prefixes_subject_that_merely_starts_with_re_letters() {
        let raw = b"Subject: Ready to ship\r\nMessage-ID: <x@e>\r\n\r\nbody";
        let src = SourceArgs {
            raw,
            mode: SourceMode::Reply,
            posting_style: PostingStyle::Top,
            quote_headline: "",
        };
        let empty: Vec<String> = Vec::new();
        let built = build(args("b@e", &empty, None, "r"), Some(src)).unwrap();
        assert_eq!(parse(&built).subject(), Some("Re: Ready to ship"));
    }

    #[test]
    fn reply_explicit_to_overrides_source_from() {
        let to = vec!["dave@example.com".to_string()];
        let raw = build(
            args("bob@example.com", &to, None, "r"),
            Some(source(SourceMode::Reply)),
        )
        .unwrap();
        let text = String::from_utf8(raw).unwrap();
        assert!(text.contains("dave@example.com"));
        assert!(!text.contains("alice@example.com"));
    }

    #[test]
    fn forward_prefixes_subject_and_omits_in_reply_to() {
        let to = vec!["dave@example.com".to_string()];
        let raw = build(
            args("bob@example.com", &to, None, "FYI"),
            Some(source(SourceMode::Forward)),
        )
        .unwrap();
        let msg = parse(&raw);
        let text = String::from_utf8(raw.clone()).unwrap();

        assert_eq!(msg.subject(), Some("Fwd: Project update"));
        assert!(!text.contains("In-Reply-To"));
        assert!(msg.body_text(0).unwrap().contains("> Original body line."));
    }

    #[test]
    fn has_prefix_requires_the_colon_case_insensitively() {
        assert!(has_prefix("Re: x", "Re: "));
        assert!(has_prefix("re:x", "Re: "));
        assert!(has_prefix("RE: x", "Re: "));
        assert!(has_prefix("Fwd: x", "Fwd: "));
        assert!(!has_prefix("Ready to ship", "Re: "));
        assert!(!has_prefix("Review", "Re: "));
        assert!(!has_prefix("Forwarding note", "Fwd: "));
    }

    #[test]
    fn compute_references_appends_source_id() {
        let msg = parse(SOURCE);
        assert_eq!(
            compute_references(&msg, "orig-2@example.com"),
            "<orig-0@example.com> <orig-1@example.com> <orig-2@example.com>",
        );

        let raw = b"In-Reply-To: <a@e>\r\nMessage-ID: <b@e>\r\n\r\nx";
        let msg = parse(raw);
        assert_eq!(compute_references(&msg, "b@e"), "<a@e> <b@e>");

        let raw = b"Message-ID: <b@e>\r\n\r\nx";
        let msg = parse(raw);
        assert_eq!(compute_references(&msg, "b@e"), "<b@e>");
    }

    #[test]
    fn push_msg_id_wraps_and_separates() {
        let mut out = String::new();
        push_msg_id(&mut out, "a@e");
        push_msg_id(&mut out, "<b@e>");
        push_msg_id(&mut out, "  ");
        push_msg_id(&mut out, "c@e");
        assert_eq!(out, "<a@e> <b@e> <c@e>");
    }

    #[test]
    fn parse_mailboxes_splits_name_and_address() {
        let alice =
            |name: Option<&str>| vec![(name.map(str::to_owned), "alice@example.org".into())];

        let mailboxes = parse_mailboxes("Alice <alice@example.org>").unwrap();
        assert_eq!(mailboxes, alice(Some("Alice")));

        let mailboxes = parse_mailboxes("alice@example.org").unwrap();
        assert_eq!(mailboxes, alice(None));

        let mailboxes = parse_mailboxes("\"Doe, Alice\" <alice@example.org>").unwrap();
        assert_eq!(mailboxes, alice(Some("Doe, Alice")));

        let mailboxes = parse_mailboxes("=?utf-8?B?QWxpY2U=?= <alice@example.org>").unwrap();
        assert_eq!(mailboxes, alice(Some("Alice")));

        let mailboxes = parse_mailboxes("alice@example.org, Bob <bob@example.org>").unwrap();
        assert_eq!(mailboxes[0], (None, "alice@example.org".into()));
        assert_eq!(mailboxes[1], (Some("Bob".into()), "bob@example.org".into()));

        assert!(parse_mailboxes("not-an-address").is_err());
        assert!(parse_mailboxes("").is_err());
    }

    #[test]
    fn compose_from_keeps_a_spelled_out_display_name_apart() {
        let empty: Vec<String> = Vec::new();
        let raw = build(args("Alice <alice@example.org>", &empty, None, "hi"), None).unwrap();
        let text = String::from_utf8(raw.clone()).unwrap();

        assert!(!text.contains("<Alice <alice@example.org>>"));

        let msg = parse(&raw);
        let from = msg.from().unwrap().first().unwrap();
        assert_eq!(from.name(), Some("Alice"));
        assert_eq!(from.address(), Some("alice@example.org"));
    }

    #[test]
    fn compose_to_keeps_a_spelled_out_display_name_apart() {
        let to = vec!["Alice <alice@example.org>".to_string()];
        let raw = build(args("sender@example.org", &to, None, "hi"), None).unwrap();
        let text = String::from_utf8(raw.clone()).unwrap();

        // regression: the whole value used to land inside the brackets
        assert!(!text.contains("<Alice <alice@example.org>>"));

        let msg = parse(&raw);
        let to_addr = msg.to().unwrap().first().unwrap();
        assert_eq!(to_addr.name(), Some("Alice"));
        assert_eq!(to_addr.address(), Some("alice@example.org"));
    }

    #[test]
    fn compose_to_keeps_every_mailbox_of_every_value() {
        let to = vec![
            "\"Doe, Alice\" <alice@example.org>, bob@example.org".to_string(),
            "carol@example.org".to_string(),
        ];
        let raw = build(args("sender@example.org", &to, None, "hi"), None).unwrap();

        let msg = parse(&raw);
        let to: Vec<_> = msg.to().unwrap().iter().collect();
        assert_eq!(to.len(), 3);
        assert_eq!(to[0].name(), Some("Doe, Alice"));
        assert_eq!(to[0].address(), Some("alice@example.org"));
        assert_eq!(to[1].address(), Some("bob@example.org"));
        assert_eq!(to[2].address(), Some("carol@example.org"));
    }

    #[test]
    fn compose_body_honours_posting_style_and_signature() {
        let top = compose_body("mine", "theirs", "wrote:", "", "-- \n", PostingStyle::Top);
        assert_eq!(top, "mine\n\nwrote:\n> theirs");

        let bottom = compose_body(
            "mine",
            "theirs",
            "wrote:",
            "",
            "-- \n",
            PostingStyle::Bottom,
        );
        assert_eq!(bottom, "wrote:\n> theirs\n\nmine");

        let unquoted = compose_body("mine", "theirs", "wrote:", "", "-- \n", PostingStyle::None);
        assert_eq!(unquoted, "mine");

        let signed = compose_body("mine", "", "", "Alice", "-- \n", PostingStyle::Top);
        assert_eq!(signed, "mine\n\n-- \nAlice");
    }

    #[test]
    fn compose_body_writes_the_signature_delimiter_verbatim() {
        // NOTE: a delimiter meant to stand on its own line carries its own
        // newline; one that does not, does not.
        let custom = compose_body("mine", "", "", "Alice", "~~~\n", PostingStyle::Top);
        assert_eq!(custom, "mine\n\n~~~\nAlice");

        let inline = compose_body("mine", "", "", "Alice", "", PostingStyle::Top);
        assert_eq!(inline, "mine\n\nAlice");
    }
}