[core] V0.1: parse, compose, reply/forward, safe names, threading, rules + Sieve, sanitiser, search (55 tests green)
This commit is contained in:
+214
-8
@@ -1,13 +1,25 @@
|
||||
//! Composing outgoing mail (mail-builder), and the drafts for reply, reply all and forward.
|
||||
//!
|
||||
//! Pure: the caller gives the Message-ID and the date. MIME boundaries are derived from the Message-ID, so the
|
||||
//! same draft always gives the same bytes.
|
||||
|
||||
use crate::sanitize::{InlineImage, SanitizeOptions, sanitize, text_to_html};
|
||||
use crate::{Address, Parsed};
|
||||
use mail_builder::MessageBuilder;
|
||||
use mail_builder::headers::address::Address as MbAddress;
|
||||
use mail_builder::headers::content_type::ContentType;
|
||||
use mail_builder::headers::message_id::MessageId;
|
||||
use mail_builder::mime::MimePart;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub struct Draft {
|
||||
pub from: Address,
|
||||
pub to: Vec<Address>,
|
||||
pub cc: Vec<Address>,
|
||||
/// Never written into the message: the SMTP envelope only.
|
||||
pub bcc: Vec<Address>,
|
||||
pub subject: String,
|
||||
/// Line endings are `\n`.
|
||||
@@ -49,22 +61,216 @@ pub enum ReplyMode {
|
||||
|
||||
/// A Message-ID from 16 random bytes the caller supplies and the sender's domain, without brackets.
|
||||
pub fn message_id(random: [u8; 16], domain: &str) -> String {
|
||||
let _ = (random, domain);
|
||||
todo!()
|
||||
let hex: String = random.iter().map(|b| format!("{b:02x}")).collect();
|
||||
let domain: String = domain.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')).collect();
|
||||
let domain = domain.trim_matches(['.', '-']);
|
||||
format!("{hex}@{}", if domain.is_empty() { "localhost" } else { domain })
|
||||
}
|
||||
|
||||
fn crlf(s: &str) -> String {
|
||||
crate::mime::normalize_newlines(s).replace('\n', "\r\n")
|
||||
}
|
||||
|
||||
fn mb_address(a: &Address) -> MbAddress<'_> {
|
||||
MbAddress::new_address(a.name.as_deref(), a.email.as_str())
|
||||
}
|
||||
|
||||
fn mb_list(list: &[Address]) -> MbAddress<'_> {
|
||||
MbAddress::new_list(list.iter().map(mb_address).collect())
|
||||
}
|
||||
|
||||
fn boundary(message_id: &str, kind: &str) -> String {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
message_id.hash(&mut h);
|
||||
kind.hash(&mut h);
|
||||
// `=_` never occurs in base64 or quoted-printable output, so the boundary cannot collide with a body.
|
||||
format!("=_ep_{kind}_{:016x}", h.finish())
|
||||
}
|
||||
|
||||
/// The RFC 5322 bytes of `draft`, with the given Message-ID (no brackets) and Date (Unix seconds).
|
||||
pub fn compose(draft: &Draft, message_id: &str, date: i64) -> Vec<u8> {
|
||||
let _ = (draft, message_id, date);
|
||||
todo!()
|
||||
let text = crlf(&draft.text);
|
||||
let html = draft.html.as_deref().map(crlf);
|
||||
|
||||
let mut builder = MessageBuilder::new()
|
||||
.from(mb_address(&draft.from))
|
||||
.subject(draft.subject.as_str())
|
||||
.message_id(message_id)
|
||||
.date(date);
|
||||
if !draft.to.is_empty() {
|
||||
builder = builder.to(mb_list(&draft.to));
|
||||
}
|
||||
if !draft.cc.is_empty() {
|
||||
builder = builder.cc(mb_list(&draft.cc));
|
||||
}
|
||||
if let Some(parent) = draft.in_reply_to.as_deref() {
|
||||
builder = builder.in_reply_to(parent);
|
||||
}
|
||||
if !draft.references.is_empty() {
|
||||
builder = builder.references(MessageId::new_list(draft.references.iter().map(String::as_str)));
|
||||
}
|
||||
|
||||
let text_part = MimePart::new("text/plain", text);
|
||||
let body = match html {
|
||||
Some(html) => MimePart::new(
|
||||
ContentType::new("multipart/alternative").attribute("boundary", boundary(message_id, "alt")),
|
||||
vec![text_part, MimePart::new("text/html", html)],
|
||||
),
|
||||
None => text_part,
|
||||
};
|
||||
let body = if draft.attachments.is_empty() {
|
||||
body
|
||||
} else {
|
||||
let mut parts = vec![body];
|
||||
for a in &draft.attachments {
|
||||
parts.push(
|
||||
MimePart::new(ContentType::new(a.content_type.as_str()), a.data.as_slice())
|
||||
.attachment(a.filename.as_str()),
|
||||
);
|
||||
}
|
||||
MimePart::new(ContentType::new("multipart/mixed").attribute("boundary", boundary(message_id, "mixed")), parts)
|
||||
};
|
||||
|
||||
builder.body(body).write_to_vec().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Leading `Re:` / `Fwd:` prefixes of `subject` removed, then one `prefix` added.
|
||||
fn prefixed(prefix: &str, subject: &str) -> String {
|
||||
let rest = crate::thread::strip_prefixes(subject).0.trim();
|
||||
format!("{prefix} {rest}").trim_end().to_string()
|
||||
}
|
||||
|
||||
fn dedupe(list: impl IntoIterator<Item = Address>, exclude: &[Address]) -> Vec<Address> {
|
||||
let mut out: Vec<Address> = Vec::new();
|
||||
for a in list {
|
||||
if !exclude.iter().any(|e| e.same_mailbox(&a)) && !out.iter().any(|o| o.same_mailbox(&a)) {
|
||||
out.push(a);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn sender_line(original: &Parsed) -> String {
|
||||
original.from.first().map(Address::display).unwrap_or_else(|| "Unknown sender".to_string())
|
||||
}
|
||||
|
||||
fn quote_text(text: &str) -> String {
|
||||
text.trim_end()
|
||||
.split('\n')
|
||||
.map(|line| if line.is_empty() { ">".to_string() } else { format!("> {line}") })
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn escape(s: &str) -> String {
|
||||
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)
|
||||
}
|
||||
|
||||
/// The original's HTML (or text) made safe for the composer, inline images embedded.
|
||||
fn original_html(original: &Parsed) -> String {
|
||||
let inline_images: HashMap<String, InlineImage<'_>> = original
|
||||
.attachments
|
||||
.iter()
|
||||
.filter_map(|a| {
|
||||
a.content_id.clone().map(|cid| (cid, InlineImage { content_type: &a.content_type, data: &a.data }))
|
||||
})
|
||||
.collect();
|
||||
match &original.html {
|
||||
Some(html) => sanitize(html, &SanitizeOptions { load_remote_images: false, inline_images }).html,
|
||||
None => text_to_html(original.text.as_deref().unwrap_or("")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reply(original: &Parsed, me: &Address, mode: ReplyMode) -> Draft {
|
||||
let _ = (original, me, mode);
|
||||
todo!()
|
||||
let mine = original.from.iter().any(|a| a.same_mailbox(me));
|
||||
let primary = if mine {
|
||||
original.to.clone()
|
||||
} else if !original.reply_to.is_empty() {
|
||||
original.reply_to.clone()
|
||||
} else {
|
||||
original.from.clone()
|
||||
};
|
||||
let to = dedupe(primary, if mine { &[] } else { std::slice::from_ref(me) });
|
||||
let cc = match mode {
|
||||
ReplyMode::Sender => Vec::new(),
|
||||
ReplyMode::All => {
|
||||
let mut exclude = to.clone();
|
||||
exclude.push(me.clone());
|
||||
dedupe(original.to.iter().chain(original.cc.iter()).cloned(), &exclude)
|
||||
}
|
||||
};
|
||||
|
||||
let attribution = match &original.date_text {
|
||||
Some(date) => format!("On {date}, {} wrote:", sender_line(original)),
|
||||
None => format!("{} wrote:", sender_line(original)),
|
||||
};
|
||||
let text = format!("\n\n{attribution}\n{}\n", quote_text(original.text.as_deref().unwrap_or("")));
|
||||
let html = format!(
|
||||
"<p><br></p><p>{}</p><blockquote style=\"margin: 0 0 0 0.8ex; border-left: 2px solid #888; padding-left: 1ex\">{}</blockquote>",
|
||||
escape(&attribution),
|
||||
original_html(original)
|
||||
);
|
||||
|
||||
let mut references = original.references.clone();
|
||||
if let Some(id) = &original.message_id {
|
||||
if !references.contains(id) {
|
||||
references.push(id.clone());
|
||||
}
|
||||
}
|
||||
|
||||
Draft {
|
||||
from: me.clone(),
|
||||
to,
|
||||
cc,
|
||||
bcc: Vec::new(),
|
||||
subject: prefixed("Re:", &original.subject),
|
||||
text,
|
||||
html: Some(html),
|
||||
attachments: Vec::new(),
|
||||
in_reply_to: original.message_id.clone(),
|
||||
references,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn forward(original: &Parsed, me: &Address) -> Draft {
|
||||
let _ = (original, me);
|
||||
todo!()
|
||||
let list = |l: &[Address]| l.iter().map(Address::display).collect::<Vec<_>>().join(", ");
|
||||
let mut header = vec![format!("From: {}", sender_line(original))];
|
||||
if let Some(date) = &original.date_text {
|
||||
header.push(format!("Date: {date}"));
|
||||
}
|
||||
header.push(format!("Subject: {}", original.subject));
|
||||
if !original.to.is_empty() {
|
||||
header.push(format!("To: {}", list(&original.to)));
|
||||
}
|
||||
if !original.cc.is_empty() {
|
||||
header.push(format!("Cc: {}", list(&original.cc)));
|
||||
}
|
||||
|
||||
let text = format!(
|
||||
"\n\n---------- Forwarded message ----------\n{}\n\n{}\n",
|
||||
header.join("\n"),
|
||||
original.text.as_deref().unwrap_or("").trim_end()
|
||||
);
|
||||
let html = format!(
|
||||
"<p><br></p><p>---------- Forwarded message ----------<br>{}</p>{}",
|
||||
header.iter().map(|h| escape(h)).collect::<Vec<_>>().join("<br>"),
|
||||
original_html(original)
|
||||
);
|
||||
|
||||
Draft {
|
||||
from: me.clone(),
|
||||
subject: prefixed("Fwd:", &original.subject),
|
||||
text,
|
||||
html: Some(html),
|
||||
attachments: original
|
||||
.attachments
|
||||
.iter()
|
||||
.map(|a| OutAttachment {
|
||||
filename: a.filename.clone(),
|
||||
content_type: a.content_type.clone(),
|
||||
data: a.data.clone(),
|
||||
})
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user