From b330745e43ab7c816aff1eb94894d7af33c75168 Mon Sep 17 00:00:00 2001 From: Quentin Dufour Date: Mon, 24 Jul 2023 14:05:47 +0200 Subject: [PATCH] improve example --- README.md | 1 + examples/simple.rs | 13 +++++++++++-- src/part/mod.rs | 26 ++++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f177ba1..5e9a05b 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ This library does not aim at implementing a specific RFC, but to be a swiss-army - Maintainability - modifying the code does not create regression and is possible for someone exterior to the project. - Compatibility - always try to parse something, do not panic or return an error. - Exhaustivity - serve as a common project to encode knowledge about emails (existing mime types, existing headers, etc.). +- Type safe - do not manipulate only strings/bytes but leverage Rust type system instead so you benefit of its safety checks at compile time. [See more about this library goals in the doc/ folder](./doc/goals.md) diff --git a/examples/simple.rs b/examples/simple.rs index ebdca15..ca15fc3 100644 --- a/examples/simple.rs +++ b/examples/simple.rs @@ -9,10 +9,19 @@ Content-Type: text/plain; charset=us-ascii This is the plain text body of the message. Note the blank line between the header information and the body of the message."#; - let email = eml_codec::email(input).unwrap(); + // if you are only interested in email metadata/headers + let header = eml_codec::imf(input).unwrap(); println!( "{} just sent you an email with subject \"{}\"", + header.from[0].to_string(), + header.subject.unwrap().to_string(), + ); + + // if you like to also parse the body/content + let email = eml_codec::email(input).unwrap(); + println!( + "{} raw message is:\n{}", email.imf.from[0].to_string(), - email.imf.subject.unwrap().to_string(), + String::from_utf8_lossy(email.child.as_text().unwrap().body), ); } diff --git a/src/part/mod.rs b/src/part/mod.rs index 05d22d2..12c142a 100644 --- a/src/part/mod.rs +++ b/src/part/mod.rs @@ -29,6 +29,32 @@ pub enum AnyPart<'a> { Txt(Text<'a>), Bin(Binary<'a>), } +impl<'a> AnyPart<'a> { + pub fn as_multipart(&self) -> Option<&Multipart<'a>> { + match self { + Self::Mult(x) => Some(x), + _ => None, + } + } + pub fn as_message(&self) -> Option<&Message<'a>> { + match self { + Self::Msg(x) => Some(x), + _ => None, + } + } + pub fn as_text(&self) -> Option<&Text<'a>> { + match self { + Self::Txt(x) => Some(x), + _ => None, + } + } + pub fn as_binary(&self) -> Option<&Binary<'a>> { + match self { + Self::Bin(x) => Some(x), + _ => None, + } + } +} pub fn to_anypart<'a>(m: AnyMIME<'a>, rpart: &'a [u8]) -> AnyPart<'a> { match m {