### Using Kernel for scanning Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/scan.md Example of using `Kernel::best()` to get the fastest back end, then calling `dash_line` and `field_end` to scan byte slices. Also iterates over all available kernels. ```rust let kernel = Kernel::best(); println!("scanning with {}", kernel.name()); // "avx2"/"sse2"/"neon"/"memchr" let dash = kernel.dash_line(b"x\n--outer", 0); // Some(1) let end = kernel.field_end(b"a\n b\nend", 0); // Some(4): the \n after a space is not a field end for candidate in Kernel::available() { println!("{}", candidate.name()); } ``` -------------------------------- ### HeaderForm parsing examples Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/header_form.md Shows how to parse different header value forms using HeaderForm::parse. Includes examples for addresses, text with encoded words, dates, and message identifiers. ```rust // Addresses let parsed = HeaderForm::Addresses.parse(b" Ann , team: bob@example.com;\r\n"); let list = parsed.value().as_address().expect("addresses"); for mailbox in list.mailboxes() { println!("{:?} <{:?}>", mailbox.name(), mailbox.address()); } // Text with encoded words let subject = HeaderForm::Text.parse(b" =?utf-8?q?caf=C3=A9?= au lait\r\n"); println!("{}", subject.value().as_text().unwrap_or_default()); // "café au lait" // Date let date = HeaderForm::Date.parse(b" Sat, 20 Nov 2021 14:22:01 -0800\r\n"); println!("{}", date.value().as_datetime().expect("a date").to_timestamp()); // Message identifiers let ids = HeaderForm::MessageIds.parse(b" \r\n \r\n"); if let Some(ids) = ids.value().as_text_list() { for id in ids.iter() { println!("{id}"); } } ``` -------------------------------- ### Individual benchmark steps Source: https://github.com/stalwartlabs/mail-parser/blob/main/benches/compare/README.md Commands to build the release binaries, run the equivalence check, run a specific workload, measure a single run, and generate the summary. Includes examples of filtering by benchmark id and using measure.sh. ```sh cargo build --release --bins ``` ```sh cargo bench --no-run > target/bench-build.log 2>&1 ``` ```sh target/release/check --out results/check.md ``` ```sh target/release/check --corpus enron-crlf --workload full --examples 10 ``` ```sh ./measure.sh 1 ``` ```sh ./measure.sh 1 full-a full-b ``` ```sh cargo bench --bench compare -- '^headers/testsuite-crlf/' ``` ```sh target/release/summary target/compare-runs/r*/criterion --out results/summary.md ``` -------------------------------- ### MessageParser::new with builder methods Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/messageparser.md Creates a parser with default settings and then configures it using builder methods. The example sets specific header forms, ignores unknown headers, and adjusts the parsing limits for depth, parts, and encoded nesting. ```rust let parser = MessageParser::new() .header(HeaderName::Received, HeaderForm::Raw) .header("X-Sender", HeaderForm::Addresses) .unknown_headers(HeaderForm::Ignore) .max_depth(16) .max_parts(500) .max_encoded_nesting(1); ``` -------------------------------- ### parse error handling example Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/messageparser.md Matches on the Option returned by parse to handle the only failure mode: no headers, or input >= 4 GiB. ```rust match MessageParser::new().parse(possibly_empty) { Some(message) => process(message), None => println!("not a message: no headers, or input >= 4 GiB"), } ``` -------------------------------- ### DateTime usage examples Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/datetime.md Shows how to extract a date from a message, format it in RFC 3339 and RFC 822, convert to a timestamp, parse an RFC 822 string, convert to UTC, and shift timezones. The output comments show expected results. ```rust // From a message if let Some(date) = message.date() { println!("{}", date.to_rfc3339()); // "2021-11-20T14:22:01-08:00" println!("{}", date.to_rfc822()); // "Sat, 20 Nov 2021 14:22:01 -0800" println!("{}", date.to_timestamp()); // 1637446921 } // Standalone parsing let date = DateTime::parse_rfc822("Sat, 20 Nov 2021 14:22:01 -0800").expect("a date"); let utc = DateTime::from_timestamp(date.to_timestamp()); println!("{}", utc.to_rfc3339()); // "2021-11-20T22:22:01Z" let zone = date.to_timezone(3600); // one hour east of UTC println!("{}", zone.to_rfc3339()); // "2021-11-20T23:22:01+01:00" ``` -------------------------------- ### Usage examples for address parser functions Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/address.md Shows the expected return values for each parser function with sample inputs. Note that `parse_address_local_part` returns the full local part including subaddress tags, while `parse_address_user_part` and `parse_address_detail_part` extract the user and detail components respectively. ```rust parse_address_local_part("user+tag@example.com"); // Some("user+tag") parse_address_user_part("user+tag@example.com"); // Some("user") parse_address_detail_part("user+tag@example.com"); // Some("tag") parse_address_domain("u@example.com"); // Some("example.com") parse_address_local_part("no-at-sign"); // None ``` -------------------------------- ### parse_with usage example Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/messageparser.md Iterates over an mbox, reusing buffers across messages to avoid allocations. The buffers are returned via into_buffers for the next iteration. ```rust let parser = MessageParser::new(); let mut buffers = MessageBuffers::new(); for entry in MessageIterator::new(&mbox[..]) { let entry = entry.expect("readable mbox"); if let Some(message) = parser.parse_with(entry.contents(), &mut buffers) { println!("{:?}", message.subject()); buffers = message.into_buffers(); } } ``` -------------------------------- ### Re-parsing a raw header with Header::parse_as Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/header_form.md Shows how to re-parse a header that was kept raw using Header::parse_as with a specific HeaderForm. The example retrieves a Received header and parses it as a Received trace. ```rust let received = message.headers().get(HeaderName::Received).expect("a Received field"); let parsed = received.parse_as(HeaderForm::Received); if let Some(trace) = parsed.value().as_received() { println!("{:?} {:?} {:?}", trace.from(), trace.by(), trace.with()); } ``` -------------------------------- ### parse usage example Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/messageparser.md Parses a raw RFC 5322 message using MessageParser::parse and prints the subject. The raw bytes are borrowed for the lifetime of the message. ```rust let raw = b"From: Ann \r\nSubject: Hi\r\n\r\nHello!\r\n"; let message = MessageParser::new().parse(raw).expect("message"); println!("{}", message.subject().unwrap_or_default()); // "Hi" ``` -------------------------------- ### Iterate TextList items and check keywords Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/headers.md Iterate over message references and check if keywords contain a specific text. The example prints each reference ID and checks for the keyword 'urgent'. ```rust if let Some(references) = message.references() { for id in references.iter() { println!("references {id}"); } } if message.keywords().is_some_and(|keywords| keywords.contains("urgent")) { println!("urgent message"); } ``` -------------------------------- ### Read header fields with mail_parser Source: https://github.com/stalwartlabs/mail-parser/blob/main/README.md Parses a raw email message and demonstrates accessing headers via the `headers()` method, including `get`, `all`, `contains`, and iteration. Shows how to match on `HeaderValue` variants like `Text` and `Received`. ```rust use mail_parser::{HeaderName, HeaderValue, MessageParser}; let raw = b"Received: from mx.example.com by mail.example.org; Sat, 20 Nov 2021 14:22:05 -0800\r\n\ Message-ID: <1234@example.com>\r\n\ X-Priority: 1\r\n\ X-Custom: first\r\n\ X-Custom: second\r\n\ Subject: Status report\r\n\ \r\n\ Body\r\n"; let message = MessageParser::new().parse(raw).expect("a message"); let headers = message.headers(); assert_eq!(message.message_id(), Some("1234@example.com")); assert_eq!(headers.get("x-custom").map(|header| header.raw_value()), Some(&b" second\r\n"[..])); assert_eq!(headers.all("X-Custom").count(), 2); assert!(headers.contains(HeaderName::XPriority)); for header in headers { match header.value() { HeaderValue::Text(text) => println!("{}: {text}", header.raw_name()), HeaderValue::Received(received) => println!("received by {:?}", received.by()), other => println!("{}: {other:?}", header.raw_name()), } } ``` -------------------------------- ### Parse a message with MessageParser and inspect headers, body, and attachments Source: https://github.com/stalwartlabs/mail-parser/blob/main/README.md Parses a raw email message using MessageParser::default().parse() and demonstrates accessing the sender, recipients, subject, HTML/text bodies, and nested attachments. The example asserts the parsed values, including a nested message's subject and body, and shows how to retrieve attachment metadata and decoded length. ```rust use mail_parser::{Address, MessageParser, PartKind}; let input = br#"From: Art Vandelay (Vandelay Industries) To: "Colleagues": "James Smythe" ; Friends: jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= ; Date: Sat, 20 Nov 2021 14:22:01 -0800 Subject: Why not both importing AND exporting? =?utf-8?b?4pi6?= Content-Type: multipart/mixed; boundary="festivus"; --festivus Content-Type: text/html; charset="us-ascii" Content-Transfer-Encoding: base64 PGh0bWw+PHA+SSB3YXMgdGhpbmtpbmcgYWJvdXQgcXVpdHRpbmcgdGhlICZsZHF1bztle HBvcnRpbmcmcmRxdW87IHRvIGZvY3VzIGp1c3Qgb24gdGhlICZsZHF1bztpbXBvcnRpbm cmcmRxdW87LDwvcD48cD5idXQgdGhlbiBJIHRob3VnaHQsIHdoeSBub3QgZG8gYm90aD8 gJiN4MjYzQTs8L3A+PC9odG1sPg== --festivus Content-Type: message/rfc822 From: "Cosmo Kramer" Subject: Exporting my book about coffee tables Content-Type: multipart/mixed; boundary="giddyup"; --giddyup Content-Type: text/plain; charset="utf-16" Content-Transfer-Encoding: quoted-printable =FF=FE=0C!5=D8"=DD5=D8=DD5=D8-=DD =005=D8*=DD5=D8"=DD =005=D8"= =DD5=D85=DD5=D8-=DD5=D8,=DD5=D8/=DD5=D81=DD =005=D8*=DD5=D86=DD = =005=D8=1F=DD5=D8,=DD5=D8,=DD5=D8(=DD =005=D8-=DD5=D8)=DD5=D8"= =DD5=D8=1E=DD5=D80=DD5=D8"=DD!=00 --giddyup Content-Type: image/gif; name*1="about "; name*0="Book "; name*2*=utf-8''%e2%98%95 tables.gif Content-Transfer-Encoding: Base64 Content-Disposition: attachment R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7 --giddyup-- --festivus-- "#; let message = MessageParser::default().parse(input).expect("a message"); let sender = message.from().and_then(|from| from.first()).expect("a sender"); assert_eq!(sender.name(), Some("Art Vandelay (Vandelay Industries)")); assert_eq!(sender.address(), Some("art@vandelay.com")); let to = message.to().expect("recipients"); let addresses: Vec<_> = to.mailboxes().filter_map(|mailbox| mailbox.address()).collect(); assert_eq!(addresses, ["james@vandelay.com", "jane@example.com", "john@example.com"]); let Some(Address::Group(friends)) = to.iter().nth(1) else { panic!("the second item is a group"); }; assert_eq!(friends.name(), Some("Friends")); assert_eq!(friends.mailboxes().nth(1).and_then(|mailbox| mailbox.name()), Some("John Smîth")); assert_eq!(message.date().expect("a date").to_rfc3339(), "2021-11-20T14:22:01-08:00"); assert_eq!(message.subject(), Some("Why not both importing AND exporting? ☺")); assert_eq!( message.body_html(0).as_deref(), Some(concat!( "

I was thinking about quitting the “exporting” to ", "focus just on the “importing”,

but then I thought,", " why not do both? ☺

" )) ); assert_eq!( message.body_text(0).as_deref(), Some(concat!( "I was thinking about quitting the “exporting” to focus just on the", " “importing”,\nbut then I thought, why not do both? ☺\n" )) ); let nested = message .attachments() .find_map(|part| part.nested()) .expect("a nested message"); assert_eq!(nested.subject(), Some("Exporting my book about coffee tables")); assert_eq!(nested.body_text(0).as_deref(), Some("ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!")); assert_eq!( nested.body_html(0).as_deref(), Some("ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!") ); let image = nested.attachments().next().expect("an attachment"); assert_eq!(image.attachment_name(), Some("Book about ☕ tables.gif")); assert!(matches!(image.kind(), PartKind::Binary)); assert_eq!(image.decoded_len(), 42); ``` -------------------------------- ### Reproduce comparison with other parsers Source: https://github.com/stalwartlabs/mail-parser/blob/main/README.md Builds and runs the comparison benchmarks against other parsers. Requires a C/C++ toolchain, GLib, and cmake. The commands fetch corpora, build the vendor, and run the comparison script. ```bash $ scripts/fetch-corpora.sh enron stalwart $ cd benches/compare $ vendor/build.sh $ ./run.sh ``` -------------------------------- ### Build, check, and measure the benchmark Source: https://github.com/stalwartlabs/mail-parser/blob/main/benches/compare/README.md Builds the crate and benchmark, runs the equivalence check, measures three runs of the whole matrix (231 benchmarks, about 20 minutes per run), and writes the median to results/summary.md. Use RUNS=1 to measure once. ```sh ./run.sh ``` -------------------------------- ### MessageRef<'m> Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/message.md Documentation for the MessageRef struct, including owned accessors, body lists, body text/HTML access methods, and an example. ```APIDOC ## `MessageRef<'m>` ### Description A message inside a `Message`: the root message, or a message nested in a `message/rfc822` (or `message/global`) part. Each message has its own root part, header fields and body lists. ### Owned accessors | Method | Signature | Description | |---|---|---| | `id` | `pub fn id(&self) -> MessageId` | 0 for the root, then nested messages in document order. | | `root_part` | `pub fn root_part(&self) -> MessagePart<'m>` | The header block of this message and its body. | | `container` | `pub fn container(&self) -> Option>` | The `message/rfc822` part holding this message; `None` for the root message. | | `source` | `pub fn source(&self) -> Source` | The buffer this message's offsets refer to. | | `source_bytes` | `pub fn source_bytes(&self) -> &'m [u8]` | The bytes of that buffer. | | `raw` | `pub fn raw(&self) -> &'m [u8]` | The bytes of this message, from its first header to its end. | | `headers` | `pub fn headers(&self) -> Headers<'m>` | The header fields of this message: those of its root part. | | `parts` | `pub fn parts(&self) -> impl Iterator> + use<'m>` | The parts of this message (nested messages excluded), in document order. | ### Body lists (RFC 8621 §4.1.4) | Method | Signature | Description | |---|---|---| | `text_body` | `pub fn text_body(&self) -> impl ExactSizeIterator> + use<'m>` | `textBody`: text parts, HTML parts standing in for a missing text version, and inline media, in reading order. | | `html_body` | `pub fn html_body(&self) -> impl ExactSizeIterator> + use<'m>` | `htmlBody`: HTML parts, text stand-ins, inline media, in reading order. | | `attachments` | `pub fn attachments(&self) -> impl ExactSizeIterator> + use<'m>` | `attachments`: leaf parts (nested messages included) not shown as body, plus inline media shown in only one of the two bodies. | | `has_attachments` | `pub fn has_attachments(&self) -> bool` | `hasAttachment`: true when `attachments()` holds a part without `Content-Disposition: inline`. Images referenced by `cid:` count unless marked inline; the RFC's optional embedded-image exception is not applied. | | `other_parts` | `pub fn other_parts(&self) -> impl Iterator> + use<'m>` | Parts in no list (issue #107): containers and nested messages excluded. | ### Body text/HTML access | Method | Signature | Description | |---|---|---| | `text_bodies` | `pub fn text_bodies(&self) -> impl Iterator> + use<'m>` | Text body as text; HTML parts converted, non-text parts skipped. | | `html_bodies` | `pub fn html_bodies(&self) -> impl Iterator> + use<'m>` | HTML body as HTML; text parts converted, non-text parts skipped. | | `body_text` | `pub fn body_text(&self, index: usize) -> Option>` | The text of the `index`-th part of the text body. | | `body_html` | `pub fn body_html(&self, index: usize) -> Option>` | The HTML of the `index`-th part of the HTML body. | | `body_preview` | `pub fn body_preview(&self, max_len: usize) -> Option>` | A preview of at most `max_len` bytes of the first text body, else of the first HTML body, without carriage returns; see `preview_text`. | ### Forwarded methods `content_type()`, `content_disposition()`, `attachment_name()`, `is_content_type(type_, subtype)` forward to `root_part()`; the full header getter set from the table above is also present on `MessageRef` (lifetime `'m`, iterator captures `+ use<'m>`). ### Example ```rust let nested = message .attachments() .find_map(|part| part.nested()) .expect("a nested message"); println!("nested message {} inside part {:?}", nested.id(), nested.container().map(|part| part.id())); println!("{}", nested.subject().unwrap_or_default()); let source = nested.source(); // Source::Decoded(part_id) when transfer-encoded println!("{} bytes in source buffer", nested.source_bytes().len()); ``` ``` -------------------------------- ### Access Received fields and iterate all hops Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/received.md Shows how to get the last Received field and iterate over all Received fields, printing details. ```rust let trace = message.received().expect("a Received field"); println!( "from {:?} by {:?}, with {:?}, id {:?}, date {:?}", trace.from(), trace.by(), trace.with(), trace.id(), trace.date().map(|date| date.to_rfc3339()) ); // Walk all hops, oldest first for trace in message.all_received() { println!("{:?}", trace.from()); } ``` -------------------------------- ### Build C/C++ libraries into vendor/prefix Source: https://github.com/stalwartlabs/mail-parser/blob/main/benches/compare/README.md Downloads, verifies, and builds the C/C++ libraries into vendor/prefix/. Checks SHA-256 of each source archive and stops on mismatch. Takes all (default), gmime, vmime, libetpan, or dovecot. ```sh vendor/build.sh ``` -------------------------------- ### Rust: Using preview_text, preview_html, and body_preview Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/decoders.md Shows how to generate a text preview from a message body, an HTML excerpt, and a lazy preview through the parse tree. The preview functions cut at character boundaries and count the ellipsis toward the maximum length. ```rust let preview = preview_text(message.body_text(0).unwrap_or_default(), 60); println!("{preview}"); let excerpt = preview_html(message.body_html(0).unwrap_or_default(), 200); // Body previews through the parse tree do this per part, decoding lazily: let from_message = message.body_preview(200).unwrap_or_default(); ``` -------------------------------- ### parse_owned usage example Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/messageparser.md Parses owned bytes into a 'static message that can be moved to another task. The message is sent to a spawned thread to access the subject. ```rust let raw = b"Subject: moved\r\n\r\nbody".to_vec(); let message: Message<'static> = MessageParser::new().parse_owned(raw).expect("a message"); std::thread::spawn(move || message.subject().map(str::to_string)); ``` -------------------------------- ### parse_headers usage example Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/messageparser.md Parses only the header block and prints the number of header fields and the byte offset of the body. Useful for DKIM verification or header indexing. ```rust let headers_only = MessageParser::new() .parse_headers(MESSAGE) .expect("the header block parses"); println!( "{} header fields, body at byte {}", headers_only.headers().len(), headers_only.root_part().offset_body() ); ``` -------------------------------- ### Run test suite with all features Source: https://github.com/stalwartlabs/mail-parser/blob/main/README.md Runs the full test suite including comparisons of every message under resources/eml/ with expected JSON. Use when you need to verify all optional features are exercised. ```bash $ cargo test --all-features ``` -------------------------------- ### Using Charset methods for decoding Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/decoders.md Demonstrates how to resolve a charset from a label, decode bytes into text, check for malformed sequences, and append decoded text to an existing string. ```rust let charset = Charset::from_label(b"ISO-8859-1").expect("known label"); println!("{}", charset.decode(b"caf\xe9")); // "café" println!("{}", Charset::from_label(b"x-unknown")); // None let (text, malformed) = Charset::Utf16Le.decode_checked(b"a\x00b\x00"); println!("{text} malformed={malformed}"); let mut out = String::new(); Charset::from_label(b"windows-1251").unwrap_or_default() .decode_append(b"\xcf\xf0\xe8\xe2\xe5\xf2", &mut out); ``` -------------------------------- ### Error handling with HeaderForm::parse Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/header_form.md Shows that parsing a value with an incompatible form does not fail but yields an empty value. The example attempts to parse a non-date string as a date. ```rust let parsed = HeaderForm::Date.parse(b" not a date\r\n"); if let Some(date) = parsed.value().as_datetime() { println!("{}", date.to_rfc3339()); } else { println!("the field did not parse as a date"); } ``` -------------------------------- ### Download corpora and run micro-benchmarks Source: https://github.com/stalwartlabs/mail-parser/blob/main/README.md Downloads the Enron and Stalwart SMTP test corpora into target/corpora (or MAIL_PARSER_CORPORA) and runs the micro-benchmarks for SIMD kernels and string resolution. A missing corpus is skipped with a warning. ```bash $ scripts/fetch-corpora.sh enron stalwart $ cargo bench --bench kernels $ cargo bench --bench resolve ``` -------------------------------- ### Typical MessageBuffers usage loop Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/configuration.md Shows the recommended pattern: create a parser and buffers, iterate over mbox entries, parse each message, print its subject, then reuse the buffers and shrink them to 1 MiB. The buffers never shrink on their own; dropping them frees their memory. ```rust let parser = MessageParser::new(); let mut buffers = MessageBuffers::new(); for entry in MessageIterator::new(&mbox[..]) { let entry = entry.expect("readable mbox"); if let Some(message) = parser.parse_with(entry.contents(), &mut buffers) { println!("{:?}", message.subject()); buffers = message.into_buffers(); buffers.shrink_to(1 << 20); } } ``` -------------------------------- ### DOW and MONTH constants Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/datetime.md Declares the DOW and MONTH static arrays. DOW holds three-letter day names starting with Sunday; MONTH holds abbreviated month names from January to December. ```rust pub static DOW: &[&str] // three-letter day names, Sunday first, indexed by day_of_week() pub static MONTH: &[&str] // "Jan"…"Dec", January first ``` -------------------------------- ### Iterate headers with HeaderIter and NamedHeaders Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/headers.md Use HeaderIter and NamedHeaders to count headers by name and access the last header. The example shows counting Subject headers and retrieving the last header via next_back(). ```rust let count = headers.all(HeaderName::Subject).count(); let last_subject = headers.iter().next_back().expect("a header"); ``` -------------------------------- ### Using HeaderKey with Headers::get_key and all_key Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/header_name.md Create a HeaderKey from a HeaderName and use it to retrieve headers by key. ```rust let key = HeaderName::Received.key(); let header = message.headers().get_key(key).expect("a Received field"); let all: Vec<_> = message.headers().all_key(key).collect(); ``` -------------------------------- ### Import mbox and maildir modules Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/mailbox.md Import the mbox and maildir mailbox readers and their associated types. ```rust use mail_parser::mailbox::mbox::{Message, MessageIterator}; use mail_parser::mailbox::maildir::{Flag, FolderIterator, Message, MessageIterator}; ``` -------------------------------- ### Import HeaderName and HeaderKey Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/header_name.md Import the HeaderName and HeaderKey types from the mail_parser crate. ```rust use mail_parser::{HeaderName, HeaderKey}; ``` -------------------------------- ### Run test suite without optional features Source: https://github.com/stalwartlabs/mail-parser/blob/main/README.md Runs the test suite without any optional features enabled. Use to verify the crate works with default (no) features. ```bash $ cargo test ``` -------------------------------- ### Recovering from a None parse result with match Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/errors.md Shows how to handle a None return from MessageParser::parse in consumer code. The match arm for None prints a message indicating the input is not a valid message (no header or too large). This is the only code example on the page. ```rust match parser.parse(raw) { Some(message) => process(message), None => println!("input is not a message (no headers, or >= 4 GiB)"), } ``` -------------------------------- ### Kernel::best Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/scan.md Returns the fastest backend supported by the running CPU. This is the default kernel used by MessageParser::new(). ```APIDOC ## Kernel::best ### Description Returns the fastest backend supported by the running CPU. This is the kernel configured by default in `MessageParser::new()`. ### Method `pub fn best() -> Self` ### Parameters None. ### Returns - `Kernel` - The fastest backend for the current CPU. ### Example ```rust let kernel = Kernel::best(); println!("scanning with {}", kernel.name()); ``` ``` -------------------------------- ### Kernel::available Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/scan.md Returns an iterator over every backend the running CPU supports, with the scalar reference first. ```APIDOC ## Kernel::available ### Description Returns an iterator over every backend the running CPU supports, with the scalar reference first. ### Method `pub fn available() -> impl Iterator` ### Parameters None. ### Returns - `impl Iterator` - An iterator over supported backends. ### Example ```rust for candidate in Kernel::available() { println!("{}", candidate.name()); } ``` ``` -------------------------------- ### Get attachment name with RFC 2231 decoding Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/content_type.md Retrieves the attachment name from a message part, demonstrating that encoded continuations (name*0, name*1, name*2*) resolve to a single decoded value. Use when you need the decoded filename of an attachment. ```rust let image = nested.attachments().next().expect("an attachment"); let name = image.attachment_name().unwrap_or_default(); println!("saved as: {name}"); // "Book ☕ tables.gif" ``` -------------------------------- ### Walk the MIME structure with mail_parser Source: https://github.com/stalwartlabs/mail-parser/blob/main/README.md Parses a multipart message with nested parts and demonstrates navigating the MIME tree using `part_by_boundary`, `children`, `nested`, and `container`. Shows how to access raw bodies and forwarded messages. ```rust use mail_parser::{MessageParser, Source}; let raw = concat!( "Content-Type: multipart/mixed; boundary=\"outer\"\r\n", "\r\n", "--outer\r\n", "Content-Type: multipart/alternative; boundary=\"inner\"\r\n", "\r\n", "--inner\r\n", "Content-Type: text/plain\r\n", "\r\n", "Hello\r\n", "--inner\r\n", "Content-Type: text/html\r\n", "\r\n", "

Hello

\r\n", "--inner--\r\n", "--outer\r\n", "Content-Type: message/rfc822\r\n", "Content-Transfer-Encoding: base64\r\n", "\r\n", "U3ViamVjdDogRm9yd2FyZGVkDQoNCkJvZHkNCg==\r\n", "--outer--\r\n", ); let message = MessageParser::new().parse(raw).expect("a message"); let alternative = message.part_by_boundary("inner").expect("a multipart"); assert_eq!(alternative.id(), 1); assert_eq!(alternative.delimiter(), Some("outer")); let html = alternative.children().nth(1).expect("the HTML part"); assert_eq!(html.delimiter(), Some("inner")); assert_eq!(html.raw_body(), b"

Hello

"); let forwarded = message.parts().find_map(|part| part.nested()).expect("a nested message"); assert_eq!(forwarded.subject(), Some("Forwarded")); assert_eq!(forwarded.container().map(|part| part.id()), Some(4)); assert_eq!(forwarded.source(), Source::Decoded(4)); assert_eq!(forwarded.body_text(0).as_deref(), Some("Body\r\n")); assert_eq!(message.parts().len(), 6); ``` -------------------------------- ### Check PartFlags for damage with intersects Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/errors.md Use this snippet to test whether a message part is damaged by checking for the LIMIT_REACHED or UNTERMINATED flags. It retrieves the flags from a part, calls intersects with the two flags, and prints the part id and the names of all set flags when damaged. The example also works for DecodeProblems. ```rust let flags = part.flags(); if flags.intersects(PartFlags::LIMIT_REACHED | PartFlags::UNTERMINATED) { println!("part {} is damaged: {:?}", part.id(), flags.names().collect()); } ``` -------------------------------- ### Convert HTML to text and text to HTML with html_to_text and text_to_html Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/decoders.md Shows how to convert an HTML string to plain text with html_to_text, and how to convert plain text to HTML with text_to_html. The text_to_html output wraps the result in tags and converts line breaks to
. ```rust println!("{}", html_to_text("

Hello world & co

")); println!("{}", text_to_html("line 1\nline 2")); // "line 1
line 2" let rewritten = strip_charset_meta(""); println!("{}", rewritten); ``` -------------------------------- ### Kernel::name Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/scan.md Returns the short name of the backend as a static string. ```APIDOC ## Kernel::name ### Description Returns the short name of the backend as a static string. ### Method `pub fn name(self) -> &'static str` ### Parameters - `self` - The kernel instance. ### Returns - `&'static str` - One of `"scalar"`, `"memchr"`, `"neon"`, `"sse2"`, or `"avx2"`. ### Example ```rust let kernel = Kernel::best(); println!("scanning with {}", kernel.name()); ``` ``` -------------------------------- ### Greeting as_str method Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/received.md Declares the as_str method for Greeting. ```rust pub fn as_str(&self) -> &'static str // src/view/received.rs:267 ``` -------------------------------- ### Header<'m> Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/headers.md Documentation for the Header struct and its methods. ```APIDOC ## `Header<'m>` ### Description Represents a single header field: its name, parsed value, and location in the message source buffer. ### Methods #### `pub fn name(&self) -> HeaderName<'m>` Returns a known variant, or `Other` with the original spelling. #### `pub fn raw_name(&self) -> &'m str` Returns the name as written, original case kept. #### `pub fn value(&self) -> HeaderValue<'m>` Returns the value, parsed with the form the parser used for this name. #### `pub fn raw_value(&self) -> &'m [u8]` Returns the bytes after the colon up to the end of the field, final line break included. #### `pub fn parse_as(&self, form: HeaderForm) -> ParsedValue<'m>` Parses the raw value again with another form, for names the parser kept raw or parsed differently. #### `pub fn offset_field(&self) -> u32` Returns the offset of the first byte of the name. #### `pub fn offset_start(&self) -> u32` Returns the offset of the byte after the colon. #### `pub fn offset_end(&self) -> u32` Returns the offset of the byte after the final line break of the field. ### Example ```rust let received = message .headers() .get(HeaderName::Received) .expect("a Received field"); let parsed = received.parse_as(HeaderForm::Received); if let Some(trace) = parsed.value().as_received() { println!("from {:?} by {:?} with {:?}", trace.from(), trace.by(), trace.with()); } ``` ``` -------------------------------- ### Importing decoder modules Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/decoders.md Shows the necessary imports for using Charset and various HTML/text processing functions from the mail_parser crate. ```rust use mail_parser::{Charset, add_html_token, html_to_text, preview_html, preview_text, strip_charset_meta, text_to_html, truncate_html, truncate_text}; // not re-exported at the root: use mail_parser::decoders::charsets::{charset_decoder, decode, decode_append}; ``` -------------------------------- ### Import MessagePart and related types Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/messagepart.md Import the MessagePart, PartKind, PartRole, PartFlags, DecodeProblems, and Encoding types from the mail_parser crate. ```rust use mail_parser::{MessagePart, PartKind, PartRole, PartFlags, DecodeProblems, Encoding}; ``` -------------------------------- ### MessageParser::new Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/messageparser.md Creates a new MessageParser with default configuration: nesting depth 64, 10,000 parts, 3 levels of transfer-encoded nested messages, Raw form for unknown headers, and the best scanning kernel for the running CPU. ```APIDOC ## MessageParser::new ### Description Creates a new MessageParser with default configuration: nesting depth 64, 10,000 parts, 3 levels of transfer-encoded nested messages, Raw form for unknown headers, and the best scanning kernel for the running CPU. ### Method new ### Endpoint MessageParser::new ### Parameters None ### Request Example ```rust let parser = MessageParser::new(); ``` ### Response #### Success Response Returns a configured `MessageParser`. #### Response Example ```rust MessageParser { /* ... */ } ``` ``` -------------------------------- ### Parsing and accessing message parts and headers Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/message.md Shows how to parse raw bytes with MessageParser, iterate over nested messages and parts, access a part by boundary or index, and retrieve text bodies and a preview. Also demonstrates using header getters like date() and from() to print header values. ```rust let message = MessageParser::new().parse(raw).expect("a message"); // Owned accessors println!("bytes: {}", message.raw().len()); for nested in message.messages() { println!("message {}", nested.id()); } for part in message.parts() { println!("part {}", part.id()); } let multipart = message.part_by_boundary("inner").expect("a multipart"); if let Some(message) = message.part(3) { println!("part 3: {:?}", message.kind()); } // Body/root accessors for text in message.text_bodies() { println!("{text}"); } let preview = message.body_preview(60).unwrap_or_default(); let owned: Message<'static> = message.into_owned(); // raw bytes copied // Header getters if let Some(date) = message.date() { println!("{}", date.to_rfc3339()); } for mailbox in message.from().map(|from| from.mailboxes()).into_iter().flatten() { println!("{:?} <{:?}>", mailbox.name(), mailbox.address()); } ``` -------------------------------- ### preview_html Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/decoders.md Generates a text preview of an HTML document by converting it to text and then truncating it. ```APIDOC ## Function: preview_html ### Description Returns a text preview of an HTML document. The document is converted to text using `html_to_text` and then truncated like `preview_text`. Only the needed part of the document is converted for efficiency. ### Signature ```rust pub fn preview_html(html: &str, max_len: usize) -> String ``` ### Parameters - **html** (`&str`) - The HTML document to preview. - **max_len** (`usize`) - The maximum number of bytes for the preview. ### Returns - `String` - The text preview of the HTML document. ### Example ```rust let excerpt = preview_html(message.body_html(0).unwrap_or_default(), 200); ``` ``` -------------------------------- ### Import Message, MessageRef, Source Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/message.md Import the main types from the mail-parser crate, re-exported at the crate root. ```rust use mail_parser::{Message, MessageRef, Source}; ``` -------------------------------- ### Run Miri unit tests for charsets, scan, and parser Source: https://github.com/stalwartlabs/mail-parser/blob/main/README.md Runs the unit tests under Miri for the span resolver, charset decoders, SIMD kernels, and parser. The commands use MIRIFLAGS to disable isolation and target specific test filters. The last command sets RUSTFLAGS to use the scalar encodify path. ```bash $ MIRIFLAGS=-Zmiri-disable-isolation cargo +nightly miri test --lib -- store:: decoders::charsets:: ``` ```bash $ MIRIFLAGS=-Zmiri-disable-isolation cargo +nightly miri test --lib -- scan:: ``` ```bash $ MIRIFLAGS=-Zmiri-disable-isolation cargo +nightly miri test --lib --target x86_64-unknown-linux-gnu -- scan:: ``` ```bash $ MIRIFLAGS=-Zmiri-disable-isolation RUSTFLAGS="-Ctarget-feature=+avx2" cargo +nightly miri test --lib --target x86_64-unknown-linux-gnu -- scan:: ``` ```bash $ MIRIFLAGS=-Zmiri-disable-isolation RUSTFLAGS="--cfg encodify_scalar" cargo +nightly miri test --lib -- parser:: --skip truncated_inputs_never_panic --skip mutated_inputs_never_panic ``` -------------------------------- ### Write attachment and read text part (Rust) Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/messagepart.md Shows how to write an attachment's decoded bytes to disk, check for decoding problems with decoded_checked(), and print the text of a text part. Uses the attachment_name(), decoded_len(), decoded(), decoded_checked(), text(), and text_prefix() methods. ```rust let file = message.attachments().next().expect("an attachment"); println!("{} ({} bytes)", file.attachment_name().unwrap_or_default(), file.decoded_len()); std::fs::write(&path, file.decoded())?; let (decoded, problems) = file.decoded_checked(); if !problems.is_empty() { println!("best-effort decode, problems: {:?}", problems.names().collect()); } let text = message.text_body().next().expect("a text part"); println!("{}", text.text().unwrap_or_default()); println!("prefix: {}", text.text_prefix(4).unwrap_or_default()); ``` -------------------------------- ### Using HeaderName and HeaderKey for repeated lookups Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/header_name.md Parse a header name, convert to a key, and use it to efficiently look up headers across multiple parts. ```rust let name = HeaderName::parse("content-type").expect("a valid name"); println!("{}", name.as_str()); // "Content-Type" let custom = HeaderName::from("X-Custom"); // From<&str>, never fails println!("other: {}", custom.is_other()); // true println!("{}", custom.as_str()); // "X-Custom" // Repeated lookups across many parts: resolve once, then use the key let key = HeaderName::from("x-tag").key(); for part in message.parts() { let headers = part.headers(); if let Some(header) = headers.get_key(key) { println!("x-tag: {:?}", header.raw_value()); } } ``` -------------------------------- ### Import DateTime, DOW, MONTH Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/datetime.md Imports the DateTime type and the DOW and MONTH constants from the mail_parser crate. ```rust use mail_parser::{DateTime, DOW, MONTH}; ``` -------------------------------- ### FolderIterator::new Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/mailbox.md Creates a FolderIterator to iterate over Maildir folders. ```APIDOC ## FolderIterator::new ### Description Creates a new FolderIterator that iterates over the folders in a Maildir or Maildir++ mailbox. ### Method new ### Endpoint FolderIterator::new(path: impl Into, sub_folder_prefix: Option<&str>) -> io::Result> ### Parameters - **path** (impl Into) - Required - Root of the Maildir tree. - **sub_folder_prefix** (Option<&str>) - Required - For Maildir++ mailboxes use `Some(".")`; for Dovecot Maildir with LAYOUT=fs use `None` (no prefix). ### Response Returns an `io::Result` that yields `io::Result` items, one per sub-folder (INBOX first, then sub-folders in directory order). `cur`, `new`, `tmp` directories are skipped as folder names; names strip `sub_folder_prefix`, and the full folder name is available from `MessageIterator::name()` and joins the stack with `.` (Maildir++) or `/` when `prefix` is `None`. ``` -------------------------------- ### Import address types Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/address.md Import the address-related types from the mail-parser crate. ```rust use mail_parser::{Address, AddressList, AddressRun, Group, Mailbox}; ``` -------------------------------- ### Import Kernel module Source: https://github.com/stalwartlabs/mail-parser/blob/main/_autodocs/api-reference/scan.md Import the `Kernel` type from the `mail_parser::scan` module. The module is `#[doc(hidden)]` but public. ```rust use mail_parser::scan::Kernel; // module is #[doc(hidden)] but public ```