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

+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();
}