C12.2: read and write MIME by the tree

The reader walks the MIME tree with its container context: alternative
picks versions, related finds its root by start, attached multiparts
stay whole, digest children are messages. Nesting deeper than 64
levels, counting enclosed messages, is refused, and over-deep parse
results are taken apart iteratively so dropping them cannot overflow
the stack. Composite parts with a Content-ID are cid targets.

The writer keeps attachment parameters and Content-IDs, writes
multipart and message attachments unencoded, and makes its own
Message-ID. SMTP adds BODY=8BITMIME for 8-bit bodies and SMTPUTF8
when any header block at any depth is 8-bit.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
ZacharyZhang-NYandClaude Opus 5.5 committed 2026-10-19 17:35:05 -04:00
1 parent 9f47b94714
commit fe90221c11
23 files changed
+1672 -136

No files matched your search

+4 -1
View File
@@ -7,9 +7,12 @@ license.workspace = true
publish.workspace = true
[dependencies]
imap-proto.workspace = true
base64.workspace = true
getrandom.workspace = true
imap-proto.workspace = true
log.workspace = true
mail-builder.workspace = true
mail-parser.workspace = true
mail-send.workspace = true
nom.workspace = true
rustls.workspace = true
+3
View File
@@ -19,6 +19,8 @@ pub enum Error {
Timeout(&'static str),
/// An address or login the protocol cannot carry.
Invalid(String),
/// A message that cannot be read or written.
Mime(String),
}
impl fmt::Display for Error {
@@ -31,6 +33,7 @@ impl fmt::Display for Error {
Self::Protocol(text) => write!(f, "unreadable reply: {text}"),
Self::Timeout(step) => write!(f, "no answer while {step}"),
Self::Invalid(text) => write!(f, "cannot be sent: {text}"),
Self::Mime(text) => write!(f, "unreadable message: {text}"),
}
}
}
+2
View File
@@ -2,6 +2,7 @@
mod error;
mod imap;
mod mime;
mod net;
mod pop;
mod smtp;
@@ -9,6 +10,7 @@ mod wire;
pub use error::{Error, Result};
pub use imap::Imap;
pub use mime::{Built, Draft, Mail, Mailbox, Part, build, read};
pub use net::{Login, Secret, Security, Server, system_tls};
pub use pop::Pop;
pub use smtp::Smtp;
+274
View File
@@ -0,0 +1,274 @@
use mail_builder::{
MessageBuilder,
headers::{address::Address as Out, content_type::ContentType, message_id::MessageId},
mime::MimePart,
};
use mail_parser::{Address, HeaderValue, MessageParser};
use crate::{Error, Result, smtp::mailbox};
mod walk;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Mailbox {
pub name: Option<String>,
pub email: String,
}
/// An attachment or a `cid:` target.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Part {
pub name: Option<String>,
pub content_type: String,
/// Content-Type parameters, such as charset.
pub params: Vec<(String, String)>,
pub content_id: Option<String>,
/// Transfer-decoded; a multipart keeps its headers.
pub bytes: Vec<u8>,
}
/// A message as read; bodies are the sender's own parts.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Mail {
pub subject: Option<String>,
pub from: Vec<Mailbox>,
pub to: Vec<Mailbox>,
pub cc: Vec<Mailbox>,
/// Seconds since the Unix epoch.
pub date: Option<i64>,
pub message_id: Option<String>,
pub in_reply_to: Vec<String>,
pub references: Vec<String>,
pub text: Option<String>,
pub html: Option<String>,
pub inline: Vec<Part>,
pub attachments: Vec<Part>,
/// The header block as it arrived.
pub headers: String,
}
/// A message to write; Bcc stays in the SMTP envelope.
#[derive(Clone, Debug)]
pub struct Draft {
pub from: Mailbox,
pub to: Vec<Mailbox>,
pub cc: Vec<Mailbox>,
pub subject: String,
pub text: String,
pub html: Option<String>,
pub attachments: Vec<Part>,
pub in_reply_to: Option<String>,
pub references: Vec<String>,
/// Seconds since the Unix epoch.
pub date: i64,
}
pub struct Built {
/// Without angle brackets, as `Mail::message_id` reads it.
pub message_id: String,
pub bytes: Vec<u8>,
}
pub fn read(raw: &[u8]) -> Result<Mail> {
let message = MessageParser::default()
.parse(raw)
.ok_or_else(|| Error::Mime("not a mail message".into()))?;
let problems = message
.parts
.iter()
.filter(|part| part.is_encoding_problem)
.count();
if problems > 0 {
log::warn!("mail: {problems} MIME parts did not decode cleanly");
}
if let Err(err) = walk::depth(&message) {
walk::dispose(message);
return Err(err);
}
let header_end = message.root_part().offset_body as usize;
let shape = walk::shape(&message);
Ok(Mail {
subject: message.subject().map(str::to_owned),
from: mailboxes(message.from().into_iter()),
to: mailboxes(message.all_to()),
cc: mailboxes(message.all_cc()),
date: message.date().map(|date| date.to_timestamp()),
message_id: message.message_id().map(str::to_owned),
in_reply_to: ids(message.in_reply_to()),
references: ids(message.references()),
text: joined(shape.text),
html: joined(shape.html),
inline: shape.inline,
attachments: shape.attachments,
headers: String::from_utf8_lossy(&raw[..header_end.min(raw.len())]).into_owned(),
})
}
/// Whether any header block needs SMTPUTF8.
pub(crate) fn utf8_headers(raw: &[u8]) -> Result<bool> {
let message = MessageParser::default()
.parse(raw)
.ok_or_else(|| Error::Mime("not a mail message".into()))?;
let checked = walk::depth(&message).map(|()| walk::utf8_headers(&message));
walk::dispose(message);
checked
}
pub fn build(draft: &Draft) -> Result<Built> {
let people = [&draft.from].into_iter().chain(&draft.to).chain(&draft.cc);
for person in people {
mailbox(&person.email)?;
line("a name", person.name.as_deref().unwrap_or_default())?;
}
line("the subject", &draft.subject)?;
for id in draft.in_reply_to.iter().chain(&draft.references) {
line("a message ID", id)?;
}
let message_id = message_id(&draft.from.email)?;
let mut builder = MessageBuilder::new()
.message_id(message_id.as_str())
.date(draft.date)
.from(address(&draft.from))
.subject(draft.subject.as_str())
.body(body(draft)?);
if !draft.to.is_empty() {
builder = builder.to(Out::new_list(draft.to.iter().map(address).collect()));
}
if !draft.cc.is_empty() {
builder = builder.cc(Out::new_list(draft.cc.iter().map(address).collect()));
}
if let Some(id) = &draft.in_reply_to {
builder = builder.in_reply_to(id.as_str());
}
if !draft.references.is_empty() {
let ids = draft.references.iter().map(String::as_str);
builder = builder.references(MessageId::new_list(ids));
}
let bytes = builder
.write_to_vec()
.map_err(|err| Error::Mime(err.to_string()))?;
Ok(Built { message_id, bytes })
}
/// Mixed of the alternative bodies and the attachments.
fn body(draft: &Draft) -> Result<MimePart<'_>> {
let text = MimePart::new("text/plain", draft.text.as_str());
let body = match &draft.html {
Some(html) => {
let html = MimePart::new("text/html", html.as_str());
MimePart::new("multipart/alternative", vec![text, html])
}
None => text,
};
if draft.attachments.is_empty() {
return Ok(body);
}
let mut parts = vec![body];
for part in &draft.attachments {
parts.push(attachment(part)?);
}
Ok(MimePart::new("multipart/mixed", parts))
}
fn attachment(part: &Part) -> Result<MimePart<'_>> {
let name = part
.name
.as_deref()
.ok_or_else(|| Error::Invalid("an attachment needs a file name".into()))?;
line("a file name", name)?;
line("a content type", &part.content_type)?;
let mut kind = ContentType::new(part.content_type.as_str());
for (key, value) in &part.params {
line("a content type parameter", key)?;
line("a content type parameter", value)?;
kind = kind.attribute(key.as_str(), value.as_str());
}
let composite = ["multipart/", "message/"]
.iter()
.any(|prefix| part.content_type.starts_with(prefix));
let mut attachment = if composite {
// RFC 2045 §6.4: composites stay unencoded.
let body = composite_body(part)?;
let encoding = if body.is_ascii() { "7bit" } else { "8bit" };
MimePart::new(kind, body).transfer_encoding(encoding)
} else {
MimePart::new(kind, part.bytes.as_slice())
}
.attachment(name);
if let Some(id) = &part.content_id {
line("a content ID", id)?;
attachment = attachment.cid(id.as_str());
}
Ok(attachment)
}
/// A multipart as read carries its headers.
fn composite_body(part: &Part) -> Result<&[u8]> {
if !part.content_type.starts_with("multipart/") {
return Ok(&part.bytes);
}
if !part.params.iter().any(|(key, _)| key == "boundary") {
return Err(Error::Invalid(
"a multipart attachment has no boundary".into(),
));
}
if let Some(body) = part.bytes.strip_prefix(b"\r\n") {
return Ok(body);
}
part.bytes
.windows(4)
.position(|end| end == b"\r\n\r\n")
.map(|at| &part.bytes[at + 4..])
.ok_or_else(|| Error::Invalid("a multipart attachment has no header end".into()))
}
/// A random left side at the sender's domain.
fn message_id(from: &str) -> Result<String> {
let (_, domain) = from
.rsplit_once('@')
.ok_or_else(|| Error::Invalid(format!("not a mail address: {from:?}")))?;
let mut random = [0u8; 16];
getrandom::fill(&mut random).map_err(|err| Error::Mime(err.to_string()))?;
let left: String = random.iter().map(|byte| format!("{byte:02x}")).collect();
Ok(format!("{left}@{domain}"))
}
/// A line break would start a new header.
fn line(what: &str, text: &str) -> Result<()> {
if text.contains(['\r', '\n']) {
return Err(Error::Invalid(format!("{what} has a line break")));
}
Ok(())
}
fn address(mailbox: &Mailbox) -> Out<'_> {
Out::new_address(mailbox.name.as_deref(), mailbox.email.as_str())
}
fn mailboxes<'a>(lists: impl Iterator<Item = &'a Address<'a>>) -> Vec<Mailbox> {
lists
.flat_map(Address::iter)
.filter_map(|addr| {
let Some(email) = addr.address.as_deref() else {
log::warn!("mail: an address without an email was skipped");
return None;
};
Some(Mailbox {
name: addr.name.as_deref().map(str::to_owned),
email: email.to_owned(),
})
})
.collect()
}
fn ids(value: &HeaderValue) -> Vec<String> {
match value {
HeaderValue::Text(id) => vec![id.to_string()],
HeaderValue::TextList(ids) => ids.iter().map(ToString::to_string).collect(),
_ => Vec::new(),
}
}
fn joined(parts: Vec<String>) -> Option<String> {
(!parts.is_empty()).then(|| parts.join("\n"))
}
+267
View File
@@ -0,0 +1,267 @@
use mail_parser::{
Encoding, Message, MessagePart, MimeHeaders, PartType,
decoders::{base64::base64_decode, quoted_printable::quoted_printable_decode},
};
use super::Part;
use crate::{Error, Result};
/// Deeper trees are refused before the walk.
const DEPTH: usize = 64;
/// What a MIME tree shows: bodies, `cid:` targets, attachments.
#[derive(Default)]
pub(super) struct Shape {
pub text: Vec<String>,
pub html: Vec<String>,
pub inline: Vec<Part>,
pub attachments: Vec<Part>,
}
pub(super) fn shape(message: &Message) -> Shape {
let mut shape = Shape::default();
Walk { message }.body(0, &mut shape);
shape
}
/// Iterative, so no tree can exhaust the stack.
pub(super) fn depth(message: &Message) -> Result<()> {
let mut stack = vec![(message, 0, 1)];
while let Some((message, id, level)) = stack.pop() {
if level > DEPTH {
return Err(Error::Mime(format!("MIME parts nest deeper than {DEPTH}")));
}
match &message.parts[id as usize].body {
PartType::Multipart(children) => {
stack.extend(children.iter().map(|&child| (message, child, level + 1)));
}
PartType::Message(inner) => stack.push((inner, 0, level + 1)),
_ => {}
}
}
Ok(())
}
/// Drops a deep tree without recursion.
pub(super) fn dispose(message: Message) {
let mut stack = vec![message];
while let Some(mut message) = stack.pop() {
for part in &mut message.parts {
if let PartType::Message(inner) = std::mem::take(&mut part.body) {
stack.push(inner);
}
}
}
}
/// RFC 6531 §3.4: 8-bit header bytes at any depth.
pub(super) fn utf8_headers(message: &Message) -> bool {
let mut stack = vec![message];
while let Some(message) = stack.pop() {
// Part offsets index the whole buffer.
let raw = message.raw_message.as_ref();
for part in &message.parts {
let header = &raw[part.offset_header as usize..part.offset_body as usize];
if !header.is_ascii() {
return true;
}
// Encoded parts carry no 8-bit bytes.
match &part.body {
PartType::Message(inner) if part.encoding == Encoding::None => stack.push(inner),
_ => {}
}
}
}
false
}
struct Walk<'a, 'x> {
message: &'a Message<'x>,
}
impl Walk<'_, '_> {
fn part(&self, id: u32) -> &MessagePart<'_> {
&self.message.parts[id as usize]
}
fn body(&self, id: u32, out: &mut Shape) {
let part = self.part(id);
// RFC 2183 §2.8, §2.9: the whole entity.
if !inline(part) {
out.attachments.push(self.leaf(part));
return;
}
self.content(id, out, true);
}
/// A related root is no `cid:` target.
fn content(&self, id: u32, out: &mut Shape, target: bool) {
let part = self.part(id);
match &part.body {
PartType::Multipart(children) => {
self.target(part, target, out);
match multipart(part).as_str() {
"alternative" => self.alternative(children, out),
"related" => self.related(part, children, out),
_ => children.iter().for_each(|&child| self.body(child, out)),
}
}
PartType::Text(text) if plain(part) => {
out.text.push(text.to_string());
self.target(part, target, out);
}
PartType::Html(html) => {
out.html.push(html.to_string());
self.target(part, target, out);
}
_ => {
let leaf = self.leaf(part);
let message = matches!(part.body, PartType::Message(_));
match leaf.content_id {
Some(_) if !message => out.inline.push(leaf),
_ => out.attachments.push(leaf),
}
}
}
}
/// RFC 2392: any part with a Content-ID.
fn target(&self, part: &MessagePart, target: bool, out: &mut Shape) {
if target && part.content_id().is_some() {
out.inline.push(self.leaf(part));
}
}
/// RFC 2046 §5.1.4: the last supported version wins.
fn alternative(&self, children: &[u32], out: &mut Shape) {
let versions: Vec<Shape> = children
.iter()
.map(|&child| {
let mut version = Shape::default();
self.body(child, &mut version);
version
})
.collect();
let text = versions.iter().rposition(|v| !v.text.is_empty());
let html = versions.iter().rposition(|v| !v.html.is_empty());
for (at, version) in versions.into_iter().enumerate() {
let bodiless = version.text.is_empty() && version.html.is_empty();
if Some(at) != text && Some(at) != html && !bodiless {
continue;
}
if Some(at) == text {
out.text.extend(version.text);
}
if Some(at) == html {
out.html.extend(version.html);
}
out.inline.extend(version.inline);
out.attachments.extend(version.attachments);
}
}
/// RFC 2387: `start` names the root; §4 voids dispositions.
fn related(&self, part: &MessagePart, children: &[u32], out: &mut Shape) {
let start = part
.content_type()
.and_then(|kind| kind.attribute("start"))
.map(|start| start.trim().trim_start_matches('<').trim_end_matches('>'));
let root = match start {
None => 0,
Some(start) => children
.iter()
.position(|&child| self.part(child).content_id() == Some(start))
.unwrap_or_else(|| {
log::warn!("mail: related start names no part; first part is the root");
0
}),
};
for (at, &child) in children.iter().enumerate() {
if at == root {
self.content(child, out, false);
continue;
}
// RFC 2387 §6.1: a resource is one entity.
let leaf = self.leaf(self.part(child));
match leaf.content_id {
Some(_) => out.inline.push(leaf),
None => out.attachments.push(leaf),
}
}
}
fn leaf(&self, part: &MessagePart) -> Part {
let kind = part.content_type();
let content_type = kind.map_or_else(
// RFC 2046 §5.1.5: digest children are messages.
|| match part.body {
PartType::Message(_) => "message/rfc822".to_owned(),
_ => "text/plain".to_owned(),
},
|kind| match &kind.c_subtype {
Some(subtype) => format!("{}/{subtype}", kind.c_type),
None => kind.c_type.to_string(),
},
);
let params = kind
.and_then(|kind| kind.attributes())
.into_iter()
.flatten()
.filter(|attr| !attr.name.eq_ignore_ascii_case("name"))
.map(|attr| (attr.name.to_ascii_lowercase(), attr.value.to_string()))
.collect();
Part {
name: part.attachment_name().map(str::to_owned),
content_type: content_type.to_ascii_lowercase(),
params,
content_id: part.content_id().map(str::to_owned),
bytes: self.octets(part),
}
}
/// Transfer-decoded bytes; text keeps its own charset.
fn octets(&self, part: &MessagePart) -> Vec<u8> {
let raw = self.message.raw_message();
let body = &raw[part.offset_body as usize..part.offset_end as usize];
match &part.body {
PartType::Binary(bytes) | PartType::InlineBinary(bytes) => bytes.to_vec(),
PartType::Message(message) => message.raw_message().to_vec(),
PartType::Multipart(_) => {
raw[part.offset_header as usize..part.offset_end as usize].to_vec()
}
PartType::Text(_) | PartType::Html(_) => {
let decoded = match part.encoding {
Encoding::None => Some(body.to_vec()),
Encoding::QuotedPrintable => quoted_printable_decode(body),
Encoding::Base64 => base64_decode(body),
};
decoded.unwrap_or_else(|| {
log::warn!("mail: a text attachment kept its encoded bytes");
body.to_vec()
})
}
}
}
}
/// RFC 2183 §2.8: unknown types are attachments.
fn inline(part: &MessagePart) -> bool {
part.content_disposition()
.is_none_or(|disposition| disposition.c_type.eq_ignore_ascii_case("inline"))
}
fn multipart(part: &MessagePart) -> String {
part.content_type()
.and_then(|kind| kind.c_subtype.as_deref())
.unwrap_or_default()
.to_ascii_lowercase()
}
/// RFC 2045 §5.2: no Content-Type is text/plain.
fn plain(part: &MessagePart) -> bool {
part.content_type().is_none_or(|kind| {
kind.c_subtype
.as_deref()
.is_none_or(|subtype| subtype.eq_ignore_ascii_case("plain"))
})
}
+21 -5
View File
@@ -22,6 +22,8 @@ pub struct Smtp {
client: SmtpClient<Stream>,
/// The server takes UTF-8 addresses (SMTPUTF8).
utf8: bool,
/// The server takes 8-bit bodies (8BITMIME).
eight: bool,
}
impl Smtp {
@@ -69,7 +71,12 @@ impl Smtp {
}
log::info!("mail: SMTP login on {}", server.host);
let utf8 = hello.has_capability(smtp_proto::EXT_SMTP_UTF8);
Ok(Self { client, utf8 })
let eight = hello.has_capability(smtp_proto::EXT_8BIT_MIME);
Ok(Self {
client,
utf8,
eight,
})
}
/// Hands one message to the server for these recipients.
@@ -81,12 +88,21 @@ impl Smtp {
mailbox(email)?;
}
let data = data(message)?;
let headers = crate::mime::utf8_headers(message)?;
let mut params = Parameters::new();
let header = message
let body = message
.windows(4)
.position(|end| end == b"\r\n\r\n")
.map_or(message, |at| &message[..at]);
if !from.is_ascii() || to.iter().any(|to| !to.is_ascii()) || !header.is_ascii() {
.map_or(&[][..], |at| &message[at..]);
if !body.is_ascii() {
if !self.eight {
return Err(Error::Invalid(
"the server does not take 8-bit message bodies".into(),
));
}
params.add(("BODY", "8BITMIME"));
}
if !from.is_ascii() || to.iter().any(|to| !to.is_ascii()) || headers {
if !self.utf8 {
return Err(Error::Invalid(
"the server does not take non-ASCII addresses or headers".into(),
@@ -185,7 +201,7 @@ fn data(message: &[u8]) -> Result<Vec<u8>> {
}
/// RFC 5321 §4.1.2 Mailbox, with RFC 6531 UTF-8.
fn mailbox(email: &str) -> Result<()> {
pub(crate) fn mailbox(email: &str) -> Result<()> {
let readable = email.rsplit_once('@').is_some_and(|(local, domain)| {
let local = match local
.strip_prefix('"')
+2
View File
@@ -1,6 +1,8 @@
//! A scripted mail server over real TLS, for protocol tests.
#![allow(dead_code)]
pub mod smtp;
use std::sync::Arc;
use ely_mail_engine::{Login, Secret, Security, Server, TlsConnector};
+45
View File
@@ -0,0 +1,45 @@
use base64::{Engine, engine::general_purpose::STANDARD};
use ely_mail_engine::{Secret, Security, Smtp};
use super::{Step, certs, expect, login, send, serve};
pub async fn logged_in(
ehlo: &str,
steps: Vec<Step>,
) -> (Smtp, tokio::task::JoinHandle<Result<(), String>>) {
let certs = certs();
let mut script = vec![
send("220 mx ready\n"),
expect("EHLO [127.0.0.1]"),
send(ehlo),
expect(&format!(
"AUTH PLAIN {}",
STANDARD.encode("\0ann@example.com\0pw")
)),
send("235 ok\n"),
];
script.extend(steps);
let (server, script) = serve(&certs, Security::Tls, script).await;
let smtp = Smtp::connect(
&server,
&login(Secret::Password("pw".into())),
&certs.trusted,
)
.await
.unwrap();
(smtp, script)
}
/// MAIL, RCPT and DATA with the server agreeing.
pub fn transaction(mail: &str, rcpt: &str, data: &str) -> Vec<Step> {
vec![
expect(mail),
send("250 ok\n"),
expect(rcpt),
send("250 ok\n"),
expect("DATA"),
send("354 go\n"),
Step::Data(data.to_owned()),
send("250 queued\n"),
]
}
+162
View File
@@ -0,0 +1,162 @@
use ely_mail_engine::{Draft, Error, Mail, Mailbox, Part, build, read};
/// The sample as a server sends it: CRLF lines.
fn sample() -> Vec<u8> {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../tests/fixtures/mail/sample.eml"
);
let text = std::fs::read_to_string(path).unwrap();
text.replace("\r\n", "\n")
.replace('\n', "\r\n")
.into_bytes()
}
fn mailbox(name: Option<&str>, email: &str) -> Mailbox {
Mailbox {
name: name.map(str::to_owned),
email: email.to_owned(),
}
}
#[test]
fn the_sample_reads_whole() {
let mail = read(&sample()).unwrap();
assert_eq!(mail.subject.as_deref(), Some("Café report"));
assert_eq!(mail.from, [mailbox(Some("张三"), "zhang@example.com")]);
assert_eq!(
mail.to,
[
mailbox(Some("Bo Smith"), "bo@example.com"),
mailbox(None, "cy@example.org")
]
);
assert_eq!(mail.cc, [mailbox(None, "dee@example.net")]);
assert_eq!(mail.date, Some(1_792_391_400));
assert_eq!(mail.message_id.as_deref(), Some("m1@example.com"));
assert_eq!(mail.in_reply_to, ["m0@example.com"]);
assert_eq!(mail.references, ["r1@example.com", "m0@example.com"]);
assert_eq!(mail.text.as_deref(), Some("Café numbers attached."));
assert_eq!(
mail.html.as_deref(),
Some(r#"<p>Caf&eacute; <img src="cid:logo@example.com"></p>"#)
);
assert_eq!(
mail.inline,
[Part {
name: None,
content_type: "image/png".into(),
params: Vec::new(),
content_id: Some("logo@example.com".into()),
bytes: b"\x89PNG\r\n\x1a\n".to_vec(),
}]
);
assert_eq!(
mail.attachments,
[Part {
name: Some("report.pdf".into()),
content_type: "application/pdf".into(),
params: Vec::new(),
content_id: Some("att@example.com".into()),
bytes: b"%PDF-1.4\n".to_vec(),
}]
);
assert!(
mail.headers
.starts_with("Return-Path: <zhang@example.com>\r\n")
);
assert!(mail.headers.contains("X-Custom: kept as sent\r\n"));
assert!(!mail.headers.contains("--mix"));
}
fn reply_to(mail: &Mail) -> Draft {
let every_byte: Vec<u8> = (0..=255).collect();
let mut attachments = mail.attachments.clone();
attachments.push(Part {
name: Some("bytes.bin".into()),
content_type: "application/octet-stream".into(),
params: Vec::new(),
content_id: None,
bytes: every_byte,
});
Draft {
from: mail.from[0].clone(),
to: mail.to.clone(),
cc: mail.cc.clone(),
subject: format!("Re: {}", mail.subject.as_deref().unwrap()),
text: mail.text.clone().unwrap(),
html: mail.html.clone(),
attachments,
in_reply_to: mail.message_id.clone(),
references: mail.references.clone(),
date: 1_792_400_000,
}
}
#[test]
fn a_reply_built_from_the_sample_reads_back_the_same() {
let mail = read(&sample()).unwrap();
let draft = reply_to(&mail);
let built = build(&draft).unwrap();
let back = read(&built.bytes).unwrap();
assert_eq!(back.subject.as_deref(), Some("Re: Café report"));
assert_eq!(back.from, std::slice::from_ref(&draft.from));
assert_eq!(back.to, draft.to);
assert_eq!(back.cc, draft.cc);
assert_eq!(back.date, Some(draft.date));
assert_eq!(back.text, Some(draft.text.clone()));
assert_eq!(back.html, draft.html);
assert_eq!(back.message_id.as_deref(), Some(built.message_id.as_str()));
assert!(
built.message_id.ends_with("@example.com"),
"{}",
built.message_id
);
assert_eq!(back.in_reply_to, ["m1@example.com"]);
assert_eq!(back.references, ["r1@example.com", "m0@example.com"]);
assert_eq!(back.attachments, draft.attachments);
let bcc = |line: &str| line.to_ascii_lowercase().starts_with("bcc:");
assert!(!back.headers.lines().any(bcc), "{}", back.headers);
let again = build(&draft).unwrap();
assert_ne!(again.message_id, built.message_id);
}
#[test]
fn bodies_are_only_what_the_sender_wrote() {
let html = read(b"Content-Type: text/html\r\n\r\n<p>only html</p>").unwrap();
assert_eq!(html.text, None);
assert_eq!(html.html.as_deref(), Some("<p>only html</p>"));
let mut draft = reply_to(&read(&sample()).unwrap());
draft.html = None;
let plain = read(&build(&draft).unwrap().bytes).unwrap();
assert_eq!(plain.html, None);
assert_eq!(plain.text.as_deref(), Some("Café numbers attached."));
}
#[test]
fn a_line_break_in_a_header_never_leaves() {
let base = reply_to(&read(&sample()).unwrap());
let mut subject = base.clone();
subject.subject = "Hi\r\nBcc: hidden@example.com".into();
let mut name = base.clone();
name.to[0].name = Some("Bo\nBcc: hidden@example.com".into());
let mut file = base.clone();
file.attachments[0].name = Some("a.pdf\r\nX-Evil: 1".into());
let mut email = base.clone();
email.cc[0].email = "dee@example.net>\r\nBcc: <hidden@example.com".into();
let mut nameless = base.clone();
nameless.attachments[0].name = None;
let mut cid = base.clone();
cid.attachments[0].content_id = Some("a@b>\r\nX-Evil: 1".into());
for draft in [subject, name, file, email, nameless, cid] {
let err = build(&draft).err().unwrap();
assert!(matches!(err, Error::Invalid(_)), "{err}");
}
}
#[test]
fn bytes_that_are_no_message_are_an_error() {
let err = read(b"").unwrap_err();
assert!(matches!(err, Error::Mime(_)), "{err}");
}
+71
View File
@@ -0,0 +1,71 @@
use ely_mail_engine::{Error, read};
/// `levels` messages, each enclosing the next.
fn enclosed(levels: usize) -> Vec<u8> {
let mut mail = b"Subject: core\r\n\r\nhi\r\n".to_vec();
for _ in 0..levels {
let mut outer = b"Content-Type: message/rfc822\r\n\r\n".to_vec();
outer.extend_from_slice(&mail);
mail = outer;
}
mail
}
#[test]
fn enclosed_messages_count_toward_the_depth() {
let err = read(&enclosed(128)).unwrap_err();
assert!(
matches!(&err, Error::Mime(text) if text.contains("64")),
"{err}"
);
let shallow = read(&enclosed(8)).unwrap();
assert_eq!(shallow.attachments.len(), 1);
}
#[test]
fn a_very_deep_enclosure_is_refused_without_a_crash() {
let err = read(&enclosed(8192)).unwrap_err();
assert!(
matches!(&err, Error::Mime(text) if text.contains("64")),
"{err}"
);
}
#[test]
fn an_attached_message_is_its_own_bytes() {
let inner = "Subject: inner\r\nContent-Type: text/plain\r\n\r\nhello";
let raw = format!(
"Subject: outer\r\nContent-Type: multipart/mixed; boundary=b\r\n\r\n\
--b\r\nContent-Type: text/plain\r\n\r\nbody\r\n\
--b\r\nContent-Type: message/rfc822\r\n\r\n{inner}\r\n--b--\r\n"
);
let mail = read(raw.as_bytes()).unwrap();
let [message] = mail.attachments.as_slice() else {
panic!("{:?}", mail.attachments)
};
assert_eq!(message.bytes, inner.as_bytes());
}
#[test]
fn a_multipart_with_a_content_id_is_a_cid_target() {
let raw = "Content-Type: multipart/mixed; boundary=m\r\n\r\n\
--m\r\nContent-Type: text/html\r\n\r\n<a href=\"cid:compound@example.com\">x</a>\r\n\
--m\r\nContent-Type: multipart/alternative; boundary=a\r\n\
Content-ID: <compound@example.com>\r\n\
Content-Disposition: inline; filename=compound.mime\r\n\r\n\
--a\r\nContent-Type: text/plain\r\n\r\ninner\r\n--a--\r\n--m--\r\n";
let mail = read(raw.as_bytes()).unwrap();
let [target] = mail.inline.as_slice() else {
panic!("{:?}", mail.inline)
};
assert_eq!(target.content_id.as_deref(), Some("compound@example.com"));
assert_eq!(target.content_type, "multipart/alternative");
assert_eq!(target.name.as_deref(), Some("compound.mime"));
assert!(
target
.bytes
.starts_with(b"Content-Type: multipart/alternative")
);
assert!(target.bytes.ends_with(b"--a--"), "{:?}", target.bytes);
assert!(mail.attachments.is_empty(), "{:?}", mail.attachments);
}
+173
View File
@@ -0,0 +1,173 @@
use ely_mail_engine::{Error, read};
/// Lines joined with CRLF, as servers send them.
fn crlf(lines: &[&str]) -> Vec<u8> {
lines.join("\r\n").into_bytes()
}
/// `levels` multipart/mixed containers around one text part.
fn nested(levels: usize) -> Vec<u8> {
let mut lines = Vec::new();
for level in 0..levels {
lines.push(format!("Content-Type: multipart/mixed; boundary=b{level}"));
lines.push(String::new());
lines.push(format!("--b{level}"));
}
lines.push("Content-Type: text/plain".into());
lines.push(String::new());
lines.push("deep".into());
for level in (0..levels).rev() {
lines.push(format!("--b{level}--"));
}
lines.push(String::new());
lines.join("\r\n").into_bytes()
}
#[test]
fn deep_nesting_is_an_error_not_a_crash() {
let err = read(&nested(2048)).unwrap_err();
assert!(
matches!(&err, Error::Mime(text) if text.contains("deeper than 64")),
"{err}"
);
let mail = read(&nested(63)).unwrap();
assert_eq!(mail.text.as_deref(), Some("deep"));
}
#[test]
fn multibyte_charsets_decode() {
let mail = read(&crlf(&[
"Subject: =?GB2312?B?1tDOxA==?=",
"Content-Type: text/plain; charset=gb2312",
"Content-Transfer-Encoding: base64",
"",
"1tDOxA==",
"",
]))
.unwrap();
assert_eq!(mail.subject.as_deref(), Some("中文"));
assert_eq!(mail.text.as_deref(), Some("中文"));
}
#[test]
fn a_related_root_marked_attachment_is_still_the_body() {
let mail = read(&crlf(&[
"Content-Type: multipart/related; boundary=r; type=\"text/html\"",
"",
"--r",
"Content-Type: text/html",
"Content-Disposition: attachment; filename=body.html",
"",
"<p>root</p>",
"--r",
"Content-Type: image/png",
"Content-ID: <img@example.com>",
"",
"png",
"--r--",
"",
]))
.unwrap();
assert_eq!(mail.html.as_deref(), Some("<p>root</p>"));
assert!(mail.attachments.is_empty());
let ids: Vec<_> = mail
.inline
.iter()
.map(|p| p.content_id.as_deref())
.collect();
assert_eq!(ids, [Some("img@example.com")]);
}
#[test]
fn a_composite_related_resource_keeps_its_entity() {
let mail = read(&crlf(&[
"Content-Type: multipart/related; boundary=r; type=\"text/html\"",
"",
"--r",
"Content-Type: text/html",
"",
"<p>root</p>",
"--r",
"Content-Type: multipart/alternative; boundary=a",
"Content-ID: <entity@example.com>",
"Content-Disposition: inline; filename=entity.mime",
"",
"--a",
"Content-Type: text/plain",
"",
"inner",
"--a--",
"--r--",
"",
]))
.unwrap();
assert_eq!(mail.html.as_deref(), Some("<p>root</p>"));
assert!(mail.attachments.is_empty());
let [entity] = mail.inline.as_slice() else {
panic!("{:?}", mail.inline)
};
assert_eq!(entity.content_id.as_deref(), Some("entity@example.com"));
assert_eq!(entity.name.as_deref(), Some("entity.mime"));
assert_eq!(entity.content_type, "multipart/alternative");
let bytes = String::from_utf8(entity.bytes.clone()).unwrap();
assert!(
bytes.starts_with("Content-Type: multipart/alternative"),
"{bytes}"
);
assert!(bytes.contains("inner"), "{bytes}");
}
#[test]
fn a_text_part_with_a_content_id_is_a_cid_target() {
let mail = read(&crlf(&[
"Content-Type: multipart/mixed; boundary=b",
"",
"--b",
"Content-Type: text/plain",
"",
"body",
"--b",
"Content-Type: text/html; charset=utf-8",
"Content-ID: <frame@example.com>",
"Content-Disposition: inline",
"",
"<p>frame</p>",
"--b--",
"",
]))
.unwrap();
assert_eq!(mail.text.as_deref(), Some("body"));
let [frame] = mail.inline.as_slice() else {
panic!("{:?}", mail.inline)
};
assert_eq!(frame.content_id.as_deref(), Some("frame@example.com"));
assert_eq!(frame.content_type, "text/html");
assert_eq!(frame.params, [("charset".to_owned(), "utf-8".to_owned())]);
assert_eq!(frame.bytes, b"<p>frame</p>");
}
#[test]
fn an_unknown_disposition_is_an_attachment() {
let mail = read(&crlf(&[
"Content-Type: multipart/mixed; boundary=b",
"",
"--b",
"Content-Type: text/plain",
"",
"body",
"--b",
"Content-Type: text/plain",
"Content-Disposition: x-file; filename=file.txt",
"",
"private attachment",
"--b--",
"",
]))
.unwrap();
assert_eq!(mail.text.as_deref(), Some("body"));
let [file] = mail.attachments.as_slice() else {
panic!("{:?}", mail.attachments)
};
assert_eq!(file.name.as_deref(), Some("file.txt"));
assert_eq!(file.bytes, b"private attachment");
}
@@ -0,0 +1,143 @@
use ely_mail_engine::{Draft, Mail, Mailbox, build, read};
use mail_parser::{MessageParser, MimeHeaders, PartType};
/// Lines joined with CRLF, as servers send them.
fn crlf(lines: &[&str]) -> Vec<u8> {
lines.join("\r\n").into_bytes()
}
/// A new message carrying `mail`'s attachments.
fn forward(mail: &Mail) -> Vec<u8> {
let draft = Draft {
from: Mailbox {
name: None,
email: "a@example.com".into(),
},
to: Vec::new(),
cc: Vec::new(),
subject: "fwd".into(),
text: "see attached".into(),
html: None,
attachments: mail.attachments.clone(),
in_reply_to: None,
references: Vec::new(),
date: 0,
};
build(&draft).unwrap().bytes
}
#[test]
fn a_forwarded_text_attachment_keeps_its_charset() {
let mail = read(&crlf(&[
"Content-Type: multipart/mixed; boundary=b",
"",
"--b",
"Content-Type: text/plain",
"",
"body",
"--b",
"Content-Type: text/plain; charset=iso-8859-1",
"Content-Transfer-Encoding: quoted-printable",
"Content-Disposition: attachment; filename=cafe.txt",
"",
"Caf=E9",
"--b--",
"",
]))
.unwrap();
let sent = forward(&mail);
let message = MessageParser::default().parse(&sent).unwrap();
let file = message.attachment(0).unwrap();
assert_eq!(file.text_contents(), Some("Café"));
assert_eq!(read(&sent).unwrap().attachments, mail.attachments);
}
#[test]
fn a_forwarded_multipart_stays_a_multipart() {
let mail = read(&crlf(&[
"Content-Type: multipart/mixed; boundary=b",
"",
"--b",
"Content-Type: text/plain",
"",
"body",
"--b",
"Content-Type: multipart/alternative; boundary=a",
"Content-Disposition: attachment; filename=alt.mime",
"",
"--a",
"Content-Type: text/plain",
"",
"alt plain",
"--a",
"Content-Type: text/html",
"",
"<p>alt html</p>",
"--a--",
"--b--",
"",
]))
.unwrap();
let sent = forward(&mail);
let message = MessageParser::default().parse(&sent).unwrap();
let alt = message
.parts
.iter()
.find(|part| part.content_type().and_then(|t| t.subtype()) == Some("alternative"))
.unwrap();
assert_eq!(alt.attachment_name(), Some("alt.mime"));
assert_eq!(alt.content_transfer_encoding(), Some("7bit"));
let PartType::Multipart(children) = &alt.body else {
panic!("{:?}", alt.body)
};
let texts: Vec<_> = children
.iter()
.map(|&id| message.parts[id as usize].text_contents())
.collect();
assert_eq!(texts, [Some("alt plain"), Some("<p>alt html</p>")]);
let back = read(&sent).unwrap();
assert_eq!(back.text.as_deref(), Some("see attached"));
let [file] = back.attachments.as_slice() else {
panic!("{:?}", back.attachments)
};
assert_eq!(file.content_type, "multipart/alternative");
assert_eq!(file.params, mail.attachments[0].params);
}
#[test]
fn a_forwarded_message_stays_unencoded() {
let mail = read(&crlf(&[
"Content-Type: multipart/mixed; boundary=b",
"",
"--b",
"Content-Type: text/plain",
"",
"body",
"--b",
"Content-Type: message/rfc822",
"Content-Disposition: attachment; filename=old.eml",
"",
"Subject: old",
"Content-Type: text/plain; charset=utf-8",
"Content-Transfer-Encoding: 8bit",
"",
"您好",
"--b--",
"",
]))
.unwrap();
let sent = forward(&mail);
let message = MessageParser::default().parse(&sent).unwrap();
let old = message
.parts
.iter()
.find(|part| matches!(part.body, PartType::Message(_)))
.unwrap();
assert_eq!(old.content_transfer_encoding(), Some("8bit"));
let PartType::Message(inner) = &old.body else {
unreachable!()
};
assert_eq!(inner.subject(), Some("old"));
assert_eq!(inner.body_text(0).as_deref(), Some("您好"));
}
+213
View File
@@ -0,0 +1,213 @@
use ely_mail_engine::{Draft, Mailbox, Part, build, read};
/// Lines joined with CRLF, as servers send them.
fn crlf(lines: &[&str]) -> Vec<u8> {
lines.join("\r\n").into_bytes()
}
fn part(name: Option<&str>, kind: &str, id: Option<&str>, bytes: &[u8]) -> Part {
Part {
name: name.map(str::to_owned),
content_type: kind.to_owned(),
params: Vec::new(),
content_id: id.map(str::to_owned),
bytes: bytes.to_vec(),
}
}
#[test]
fn text_attachments_keep_their_own_bytes() {
let mail = read(&crlf(&[
"Content-Type: multipart/mixed; boundary=b",
"",
"--b",
"Content-Type: text/plain",
"",
"body",
"--b",
"Content-Type: text/plain; charset=iso-8859-1",
"Content-Transfer-Encoding: quoted-printable",
"Content-Disposition: attachment; filename=qp.txt",
"",
"Caf=E9",
"--b",
"Content-Type: text/plain; charset=iso-8859-1",
"Content-Disposition: attachment; filename=raw.txt",
"",
"Caf\u{e9}",
"--b",
"Content-Type: text/plain; charset=iso-8859-1",
"Content-Transfer-Encoding: base64",
"Content-Disposition: attachment; filename=b64.txt",
"",
"Q2Fm6Q==",
"--b--",
"",
]))
.unwrap();
assert_eq!(mail.text.as_deref(), Some("body"));
let bytes: Vec<&[u8]> = mail
.attachments
.iter()
.map(|p| p.bytes.as_slice())
.collect();
assert_eq!(bytes, [b"Caf\xe9", "Caf\u{e9}".as_bytes(), b"Caf\xe9"]);
}
#[test]
fn a_built_latin1_text_attachment_reads_back_as_built() {
let latin1 = part(Some("cafe.txt"), "text/plain", None, b"Caf\xe9\r\n");
let draft = Draft {
from: Mailbox {
name: None,
email: "a@example.com".into(),
},
to: Vec::new(),
cc: Vec::new(),
subject: "s".into(),
text: "t".into(),
html: None,
attachments: vec![latin1.clone()],
in_reply_to: None,
references: Vec::new(),
date: 0,
};
let back = read(&build(&draft).unwrap().bytes).unwrap();
assert_eq!(back.attachments, [latin1]);
}
#[test]
fn a_related_root_named_by_start_can_come_after_its_image() {
let mail = read(&crlf(&[
"Content-Type: multipart/related; boundary=r; type=\"text/html\"; start=\"<root@example.com>\"",
"",
"--r",
"Content-Type: image/png",
"Content-ID: <img@example.com>",
"Content-Transfer-Encoding: base64",
"",
"iVBORw==",
"--r",
"Content-Type: text/html",
"Content-ID: <root@example.com>",
"",
"<img src=\"cid:img@example.com\">",
"--r--",
"",
]))
.unwrap();
assert_eq!(
mail.html.as_deref(),
Some("<img src=\"cid:img@example.com\">")
);
assert_eq!(
mail.inline,
[part(None, "image/png", Some("img@example.com"), b"\x89PNG")]
);
assert!(mail.attachments.is_empty());
}
#[test]
fn a_related_image_marked_attachment_is_still_a_cid_target() {
let mail = read(&crlf(&[
"Content-Type: multipart/related; boundary=r",
"",
"--r",
"Content-Type: text/html",
"",
"<img src=\"cid:img@example.com\">",
"--r",
"Content-Type: image/png",
"Content-ID: <img@example.com>",
"Content-Disposition: attachment; filename=img.png",
"Content-Transfer-Encoding: base64",
"",
"iVBORw==",
"--r--",
"",
]))
.unwrap();
assert_eq!(
mail.inline,
[part(
Some("img.png"),
"image/png",
Some("img@example.com"),
b"\x89PNG"
)]
);
assert!(mail.attachments.is_empty());
}
#[test]
fn an_attached_multipart_is_one_attachment_and_no_body() {
let entity = [
"Content-Type: multipart/alternative; boundary=in",
"Content-Disposition: attachment; filename=alternatives.mime",
"",
"--in",
"Content-Type: text/plain",
"",
"private attachment",
"--in--",
];
let mut lines = vec![
"Content-Type: multipart/mixed; boundary=out",
"",
"--out",
"Content-Type: text/plain",
"",
"body",
"--out",
];
lines.extend(entity);
lines.extend(["--out--", ""]);
let mail = read(&crlf(&lines)).unwrap();
assert_eq!(mail.text.as_deref(), Some("body"));
assert_eq!(mail.attachments.len(), 1);
let attached = &mail.attachments[0];
assert_eq!(attached.name.as_deref(), Some("alternatives.mime"));
assert_eq!(attached.content_type, "multipart/alternative");
assert_eq!(attached.bytes, crlf(&entity));
}
#[test]
fn alternatives_of_one_type_are_chosen_not_joined() {
let mail = read(&crlf(&[
"Content-Type: multipart/alternative; boundary=a",
"",
"--a",
"Content-Type: text/plain; charset=us-ascii",
"",
"Cafe",
"--a",
"Content-Type: text/plain; charset=utf-8",
"",
"Café",
"--a",
"Content-Type: text/calendar",
"",
"BEGIN:VCALENDAR",
"--a--",
"",
]))
.unwrap();
assert_eq!(mail.text.as_deref(), Some("Café"));
assert_eq!(
mail.attachments,
[part(None, "text/calendar", None, b"BEGIN:VCALENDAR")]
);
}
#[test]
fn a_digest_child_without_a_type_is_a_message() {
let enclosed = "From: x@example.com\r\nSubject: inner\r\n\r\nhello";
let mut lines = vec!["Content-Type: multipart/digest; boundary=d", "", "--d", ""];
lines.push(enclosed);
lines.extend(["--d--", ""]);
let mail = read(&crlf(&lines)).unwrap();
assert_eq!(mail.attachments.len(), 1);
assert_eq!(mail.attachments[0].content_type, "message/rfc822");
let inner = read(&mail.attachments[0].bytes).unwrap();
assert_eq!(inner.subject.as_deref(), Some("inner"));
}
+18 -127
View File
@@ -2,7 +2,10 @@ mod fake;
use base64::{Engine, engine::general_purpose::STANDARD};
use ely_mail_engine::{Error, Secret, Security, Smtp};
use fake::{Step, certs, expect, login, send, serve};
use fake::{
Step, certs, expect, login, send, serve,
smtp::{logged_in, transaction},
};
#[tokio::test]
async fn starttls_password_login_sends_one_message() {
@@ -170,7 +173,7 @@ async fn a_refused_recipient_keeps_the_server_words() {
send("250 ok\n"),
expect("DATA"),
send("354 go\n"),
Step::Data("x".into()),
Step::Data("Subject: x\n\nx".into()),
send("250 queued\n"),
],
)
@@ -186,7 +189,7 @@ async fn a_refused_recipient_keeps_the_server_words() {
.send(
"ann@example.com",
&["nobody@example.com".to_owned()],
b"x\r\n",
b"Subject: x\r\n\r\nx\r\n",
)
.await
.unwrap_err();
@@ -194,9 +197,13 @@ async fn a_refused_recipient_keeps_the_server_words() {
matches!(&err, Error::Server(text) if text.contains("550") && text.contains("No such user")),
"{err}"
);
smtp.send("ann@example.com", &["bo@example.com".to_owned()], b"x\r\n")
.await
.unwrap();
smtp.send(
"ann@example.com",
&["bo@example.com".to_owned()],
b"Subject: x\r\n\r\nx\r\n",
)
.await
.unwrap();
script.await.unwrap().unwrap();
}
@@ -280,7 +287,7 @@ async fn an_envelope_with_a_line_break_or_bracket_never_leaves() {
];
for (from, to) in bad {
let err = smtp
.send(from, &[to.to_owned()], b"x\r\n")
.send(from, &[to.to_owned()], b"Subject: x\r\n\r\nx\r\n")
.await
.unwrap_err();
assert!(matches!(&err, Error::Invalid(_)), "{err}");
@@ -301,47 +308,6 @@ async fn an_envelope_with_a_line_break_or_bracket_never_leaves() {
script.await.unwrap().unwrap();
}
async fn logged_in(
ehlo: &str,
steps: Vec<Step>,
) -> (Smtp, tokio::task::JoinHandle<Result<(), String>>) {
let certs = certs();
let mut script = vec![
send("220 mx ready\n"),
expect("EHLO [127.0.0.1]"),
send(ehlo),
expect(&format!(
"AUTH PLAIN {}",
STANDARD.encode("\0ann@example.com\0pw")
)),
send("235 ok\n"),
];
script.extend(steps);
let (server, script) = serve(&certs, Security::Tls, script).await;
let smtp = Smtp::connect(
&server,
&login(Secret::Password("pw".into())),
&certs.trusted,
)
.await
.unwrap();
(smtp, script)
}
/// MAIL, RCPT and DATA with the server agreeing.
fn transaction(mail: &str, rcpt: &str, data: &str) -> Vec<Step> {
vec![
expect(mail),
send("250 ok\n"),
expect(rcpt),
send("250 ok\n"),
expect("DATA"),
send("354 go\n"),
Step::Data(data.to_owned()),
send("250 queued\n"),
]
}
#[tokio::test]
async fn a_quoted_local_part_is_a_mailbox() {
let from = r#""ann \"a\" lee"@example.com"#;
@@ -351,11 +317,13 @@ async fn a_quoted_local_part_is_a_mailbox() {
transaction(
&format!("MAIL FROM:<{from}>"),
&format!("RCPT TO:<{to}>"),
"x",
"Subject: x\n\nx",
),
)
.await;
smtp.send(from, &[to.to_owned()], b"x\r\n").await.unwrap();
smtp.send(from, &[to.to_owned()], b"Subject: x\r\n\r\nx\r\n")
.await
.unwrap();
script.await.unwrap().unwrap();
}
@@ -379,80 +347,3 @@ async fn a_dot_opening_the_first_line_is_stuffed() {
.unwrap();
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_utf8_header_needs_smtputf8() {
let message = "Subject: 您好\r\n\r\nhi\r\n";
let (mut smtp, script) = logged_in(
"250-mx\n250-SMTPUTF8\n250 AUTH PLAIN\n",
transaction(
"MAIL FROM:<ann@example.com> SMTPUTF8",
"RCPT TO:<bo@example.com>",
"Subject: 您好\n\nhi",
),
)
.await;
let to = ["bo@example.com".to_owned()];
smtp.send("ann@example.com", &to, message.as_bytes())
.await
.unwrap();
script.await.unwrap().unwrap();
let (mut smtp, script) = logged_in("250-mx\n250 AUTH PLAIN\n", vec![]).await;
let err = smtp
.send("ann@example.com", &to, message.as_bytes())
.await
.unwrap_err();
assert!(
matches!(&err, Error::Invalid(text) if text.contains("headers")),
"{err}"
);
script.await.unwrap().unwrap();
let (mut smtp, script) = logged_in(
"250-mx\n250 AUTH PLAIN\n",
transaction(
"MAIL FROM:<ann@example.com>",
"RCPT TO:<bo@example.com>",
"Subject: hi\n\n您好",
),
)
.await;
smtp.send(
"ann@example.com",
&to,
"Subject: hi\r\n\r\n您好\r\n".as_bytes(),
)
.await
.unwrap();
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_utf8_address_needs_smtputf8() {
let to = "用户@例子.广告";
let (mut smtp, script) = logged_in(
"250-mx\n250-SMTPUTF8\n250 AUTH PLAIN\n",
transaction(
"MAIL FROM:<ann@example.com> SMTPUTF8",
&format!("RCPT TO:<{to}>"),
"x",
),
)
.await;
smtp.send("ann@example.com", &[to.to_owned()], b"x\r\n")
.await
.unwrap();
script.await.unwrap().unwrap();
let (mut smtp, script) = logged_in("250-mx\n250 AUTH PLAIN\n", vec![]).await;
let err = smtp
.send("ann@example.com", &[to.to_owned()], b"x\r\n")
.await
.unwrap_err();
assert!(
matches!(&err, Error::Invalid(text) if text.contains("non-ASCII")),
"{err}"
);
script.await.unwrap().unwrap();
}
+155
View File
@@ -0,0 +1,155 @@
mod fake;
use ely_mail_engine::{Draft, Error, Mailbox, Part, build};
use fake::smtp::{logged_in, transaction};
#[tokio::test]
async fn a_utf8_header_needs_smtputf8() {
let message = "Subject: 您好\r\n\r\nhi\r\n";
let (mut smtp, script) = logged_in(
"250-mx\n250-SMTPUTF8\n250 AUTH PLAIN\n",
transaction(
"MAIL FROM:<ann@example.com> SMTPUTF8",
"RCPT TO:<bo@example.com>",
"Subject: 您好\n\nhi",
),
)
.await;
let to = ["bo@example.com".to_owned()];
smtp.send("ann@example.com", &to, message.as_bytes())
.await
.unwrap();
script.await.unwrap().unwrap();
let (mut smtp, script) = logged_in("250-mx\n250 AUTH PLAIN\n", vec![]).await;
let err = smtp
.send("ann@example.com", &to, message.as_bytes())
.await
.unwrap_err();
assert!(
matches!(&err, Error::Invalid(text) if text.contains("headers")),
"{err}"
);
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn an_8bit_body_needs_8bitmime() {
let message = "Subject: hi\r\n\r\n您好\r\n".as_bytes();
let to = ["bo@example.com".to_owned()];
let (mut smtp, script) = logged_in(
"250-mx\n250-8BITMIME\n250 AUTH PLAIN\n",
transaction(
"MAIL FROM:<ann@example.com> BODY=8BITMIME",
"RCPT TO:<bo@example.com>",
"Subject: hi\n\n您好",
),
)
.await;
smtp.send("ann@example.com", &to, message).await.unwrap();
script.await.unwrap().unwrap();
let (mut smtp, script) = logged_in("250-mx\n250 AUTH PLAIN\n", vec![]).await;
let err = smtp
.send("ann@example.com", &to, message)
.await
.unwrap_err();
assert!(
matches!(&err, Error::Invalid(text) if text.contains("8-bit")),
"{err}"
);
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_utf8_address_needs_smtputf8() {
let to = "用户@例子.广告";
let (mut smtp, script) = logged_in(
"250-mx\n250-SMTPUTF8\n250 AUTH PLAIN\n",
transaction(
"MAIL FROM:<ann@example.com> SMTPUTF8",
&format!("RCPT TO:<{to}>"),
"Subject: x\n\nx",
),
)
.await;
smtp.send(
"ann@example.com",
&[to.to_owned()],
b"Subject: x\r\n\r\nx\r\n",
)
.await
.unwrap();
script.await.unwrap().unwrap();
let (mut smtp, script) = logged_in("250-mx\n250 AUTH PLAIN\n", vec![]).await;
let err = smtp
.send(
"ann@example.com",
&[to.to_owned()],
b"Subject: x\r\n\r\nx\r\n",
)
.await
.unwrap_err();
assert!(
matches!(&err, Error::Invalid(text) if text.contains("non-ASCII")),
"{err}"
);
script.await.unwrap().unwrap();
}
/// A forwarded message/global under ASCII outer headers.
fn forwarded() -> Vec<u8> {
let enclosed = Part {
name: Some("old.eml".into()),
content_type: "message/global".into(),
params: Vec::new(),
content_id: None,
bytes: "Subject: 您好\r\n\r\nhi\r\n".as_bytes().to_vec(),
};
let draft = Draft {
from: Mailbox {
name: None,
email: "ann@example.com".into(),
},
to: Vec::new(),
cc: Vec::new(),
subject: "fwd".into(),
text: "see attached".into(),
html: None,
attachments: vec![enclosed],
in_reply_to: None,
references: Vec::new(),
date: 0,
};
build(&draft).unwrap().bytes
}
#[tokio::test]
async fn an_enclosed_utf8_header_needs_smtputf8() {
let to = ["bo@example.com".to_owned()];
let built = forwarded();
let (mut smtp, script) = logged_in("250-mx\n250-8BITMIME\n250 AUTH PLAIN\n", vec![]).await;
let err = smtp.send("ann@example.com", &to, &built).await.unwrap_err();
assert!(
matches!(&err, Error::Invalid(text) if text.contains("headers")),
"{err}"
);
script.await.unwrap().unwrap();
let message = "Content-Type: multipart/mixed; boundary=b\r\n\r\n--b\r\n\
Content-Type: message/global\r\n\r\nSubject: 您好\r\n\r\nhi\r\n--b--\r\n";
let (mut smtp, script) = logged_in(
"250-mx\n250-8BITMIME\n250-SMTPUTF8\n250 AUTH PLAIN\n",
transaction(
"MAIL FROM:<ann@example.com> BODY=8BITMIME SMTPUTF8",
"RCPT TO:<bo@example.com>",
message.replace("\r\n", "\n").trim_end(),
),
)
.await;
smtp.send("ann@example.com", &to, message.as_bytes())
.await
.unwrap();
script.await.unwrap().unwrap();
}