//! 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
, pub cc: Vec
, /// Never written into the message: the SMTP envelope only. pub bcc: Vec
, pub subject: String, /// Line endings are `\n`. pub text: String, pub html: Option, pub attachments: Vec, /// Without angle brackets. pub in_reply_to: Option, pub references: Vec, } #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct OutAttachment { pub filename: String, pub content_type: String, pub data: Vec, } impl std::fmt::Debug for Draft { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Draft") .field("to", &self.to.len()) .field("attachments", &self.attachments.len()) .finish_non_exhaustive() } } impl std::fmt::Debug for OutAttachment { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("OutAttachment").field("bytes", &self.data.len()).finish_non_exhaustive() } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum ReplyMode { Sender, All, } /// 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 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 { 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, exclude: &[Address]) -> Vec
{ let mut out: Vec
= 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::>() .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> = 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 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!( "


{}

{}
", 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 list = |l: &[Address]| l.iter().map(Address::display).collect::>().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!( "


---------- Forwarded message ----------
{}

{}", header.iter().map(|h| escape(h)).collect::>().join("
"), 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() } }