mail-parser
Project website: spamscope.ai/en/mail-parser/
mail-parser is a production-grade, RFC-compliant email parsing library that goes far beyond a simple wrapper for Python's email module. It turns a raw email into structured Python objects, draws its structure, and reports every defect it finds, so that malformed mail becomes evidence instead of a silent misread.
mail-parser is the battle-tested foundation of SpamScope, an email security and threat analysis platform, and has proven itself in production environments where accuracy and security matter most.
Table of contents
- Why mail-parser
- Installation
- Quick start
- The parsed mail
- Message structure
- Defects
- Forensic recovery
- Command line
- Exception hierarchy
- Reporting security issues
- Docker deployment
- mail-parser in the ecosystem
- Support mail-parser
- License and authors
- Working with coding agents
Why mail-parser
- Security-first design. Built for email security analysis and digital forensics: it detects malformed structures, hidden content and RFC non-compliance that can hide a payload from a filter or a gateway.
- Everything is extracted. Headers, plain-text and HTML bodies, attachments with their metadata, the delivery path hop by hop, dates with timezones, custom headers.
- Three views of every value. Python object, raw header text and JSON, for any workflow.
- Defects are data. Every RFC violation, malformed boundary or recovered value is reported with its evidence, never dropped and never silently normalized.
- The structure is visible. One flat list describes the MIME tree, and a text drawing shows headers, delivery path and tree at a glance.
- Outlook support.
.msgfiles are parsed alongside standard.emlmessages. - Production-ready. Python 3.9 and later, extensive test suite, security reviews on every change (SECURITY.md).
Installation
Use the latest patch release of your Python series. mail-parser parses with Python's email
package, and older patch releases take quadratic time on a header with many parameters: an 80 KB
Content-Type value takes more than a second on Python 3.9.6, 3.11.11, 3.12.8 and 3.13.2, and
under 0.1 seconds on 3.10.22, 3.12.16, 3.13.18, 3.14.10 and 3.15.2.
Quick install
pip install mail-parser
Outlook .msg support
Outlook .msg files are converted to .eml before parsing. Two backends exist:
extract-msg(recommended, pure Python):pip install mail-parser[outlook].msgconvert(deprecated, external Perl tool): thelibemail-outlook-message-perlsystem package (apt-get install libemail-outlook-message-perlon Debian-based systems).
When extract-msg is installed it is used first; only when it is not available does mail-parser
fall back to msgconvert, logging a deprecation warning. With neither backend,
parse_from_file_msg() raises MailParserOSError. A malformed .msg (not OLE, truncated,
corrupt) read with extract-msg raises MailParserOutlookError, with the library's exception as
__cause__.
⚠️ Deprecated: the
msgconvertbackend will be removed in a future release. Migrate withpip install mail-parser[outlook].
💥 Breaking change: the default .msg backend changed. The two converters produce different
intermediate .eml output, so some parsed fields (header ordering, encoding edge cases, attachment
naming) can differ from the previous msgconvert-only behaviour. Downstream code asserting on exact
.msg-derived output may need updating.
Development installation
git clone https://github.com/SpamScope/mail-parser.git
cd mail-parser
uv sync
AGENTS.md holds the commands, the architecture notes and the review requirements.
Quick start
import mailparser
mail = mailparser.parse_from_file("example_mail")
mail.from_ # [('Sender Name', 'sender@example.com')]
mail.to # [('Recipient', 'recipient@example.com')]
mail.subject # 'Invoice'
mail.date # datetime with timezone
mail.attachments # [{'filename': 'invoice.pdf', 'payload': '...base64...', ...}]
mail.received # one dict per hop, first hop first
mail.mime_tree # one dict per MIME part
mail.has_defects # True when anything needed recovery or broke a rule
mail.defects_categories # {'AddressHeaderDefect', ...}
mail.mail_json # the whole parsed mail as JSON
print(mailparser.render_structure(mail)) # headers, delivery path and MIME tree as text
From the command line:
mail-parser -f example_mail -j # parsed mail as JSON
mail-parser -f example_mail -st # draw the structure
mail-parser -f example_mail -j --mime-tree # JSON of the mail, then JSON of the MIME tree
The parsed mail
Parsing functions and input handling
import mailparser
mail = mailparser.parse_from_bytes(byte_mail) # bytes
mail = mailparser.parse_from_file(f) # file path, read as bytes
mail = mailparser.parse_from_file_obj(fp) # file object
mail = mailparser.parse_from_string(raw_mail) # text already decoded by the caller
mail = mailparser.parse_from_file_msg(outlook_mail) # Outlook .msg
mail = mailparser.MailParser(message) # an email.message.Message the caller parsed
- Bytes are the forensic input. File paths are read as bytes, so undecodable octets and the
original MIME line endings are preserved just like
parse_from_bytes(). Declared charsets apply to the body; UTF-8 recovery applies when the declared decode fails, not by guessing which valid interpretation the sender intended. Undecodable header octets appear as Python'ssurrogateescapecode points (\udcffis the byteFF). - Strings are text.
parse_from_string()accepts text the caller decoded. It may hold lone surrogates, which are reported as evidence rather than failing the parse. - A caller's message is never changed.
MailParser(message)reads a message parsed with theemailpackage under any policy;message_as_stringand the attached containers are flattened through a copy. One limit lies in theemailpackage itself: with the defaultcompat32policy,email.message_from_string()raisesUnicodeEncodeErrorbefore mail-parser is involved whenContent-TypeorContent-Transfer-Encodingholds a lone surrogate. Pass the text toparse_from_string()instead.
Properties
Every parsed element is available in three forms:
mail.to: the Python object (list, dict, string or datetime);mail.to_json: the same value as JSON;mail.to_raw: the original header text, exactly as it appears in the message.
Standard headers are properties: bcc, cc, date, delivered_to, from_ (from is a
Python keyword), message_id, received, reply_to, subject, to. Address headers return a
list of (display_name, address) tuples.
Any other header is reached by replacing hyphens with underscores: mail.X_MSMail_Priority
reads X-MSMail-Priority. This convenience, and the _json / _raw suffixes, apply only to
attribute access written by you. Names read out of a message, the keys of mail and headers, are
looked up literally: a header genuinely named X_Spam_Flag or Subject_json keeps its own name
and its own value, and a header named like a method (Parse, Headers_json) is still a header.
Attribute names beginning with an underscore are not headers and raise AttributeError.
Computed components:
| Property | Content |
|---|---|
body |
The text parts (text_plain, then text_html, then text_not_managed) joined with --- mail_boundary --- lines. |
text_plain, text_html |
Lists of the plain-text and HTML body parts. HTML is returned as text, never rendered. |
text_not_managed |
Text parts of other subtypes. |
headers |
One key per header name as written, with its decoded value: address headers as (name, address) tuples (first occurrence), the others as a string, or a list when the header repeats. |
attachments |
One dict per attachment, see Attachments. |
received |
One dict per hop, see Delivery path. |
get_server_ipaddress(trust) |
The sender's IP as seen by the first Received header that contains trust, or None. Never falls back to older, forgeable hops. |
to_domains |
The recipient domains. |
timezone |
The offset of date from UTC in hours, as text ('+1.0'); 0 without a date. |
mime_tree |
One dict per MIME part, see Message structure. |
has_defects, defects, defects_categories |
The defect summary, see Defects. |
address_header_defects, received_header_defects, date_header_defects, header_decoding_defects, resource_limit_defects, parser_error_defects |
The structured diagnostics, always lists. |
mail, mail_json |
Everything above in one dict / JSON document (the structured diagnostics only when nonempty). |
mail_partial |
The same with the main headers only. |
message, message_as_string |
The underlying email.message.Message and the message flattened back to text. |
mail.subject removes folding CRLF followed by a space or tab
(RFC 5322 section 2.2.3) before
decoding encoded words; LF-only folds are accepted too. mail.subject_raw and mail.message
keep the original folding. If an encoded word cannot be decoded, the complete literal Subject is
kept and header_decoding_defects says why.
Attachments
Each entry of mail.attachments is a dict:
| Key | Content |
|---|---|
filename |
The decoded name as the sender wrote it. Untrusted: never use it to build a filesystem path. |
safe_filename |
The name reduced to a basename that fits the filesystem limit, or None when no usable basename exists. |
payload |
For a file: base64 of the bytes the recipient received, whatever encoding it was sent with. For an attached container (message/rfc822, multipart/*): the flattened message text, or its base64 when that text holds octets that are not UTF-8. |
binary |
True for a file (kept as bytes, text files included); False for an attached container published as text. |
mail_content_type |
The MIME type. |
content_transfer_encoding |
base64 for a file: a part sent with another encoding is re-encoded, so the payload always matches the encoding it declares. The declared encoding for a container. |
content-disposition |
attachment, inline, or the declared value. |
content-id, charset |
The declared Content-ID and charset. |
Write them to disk with mail.write_attachments(base_path). It validates containment, rejects
symlink destinations and deduplicates names within the batch (case-insensitively, because APFS,
exFAT and SMB collapse Invoice.pdf and invoice.pdf). A single unusable attachment never costs
the rest of the batch: a name that cannot be sanitized, a payload that cannot be decoded or a failed
write is logged and skipped. A containment failure raises MailParserPathError and stops the batch.
Delivery path
mail.received lists the Received headers as hops, first hop first. Each hop has hop, the
clauses the header holds (from, by, via, with, id, for, envelope_from,
envelope_sender), date, date_utc and delay (seconds since the previous hop). A header that
cannot be interpreted keeps hop, delay and raw, the header as written, and
received_header_defects says why.
get_server_ipaddress(trust) returns the IP of the sender as seen by the first Received header
that contains the string trust (the name of your own mail server). Only the from clause of that
hop is searched, the sender-supplied HELO name is excluded, and the result is None when the hop
names no public IP. Attribution never falls back to older Received headers, which the sender is
free to forge.
Message structure
The MIME tree
mail.mime_tree describes the MIME tree as a flat list: one entry per part in wire order,
containers included. Entry i is part i, the number every defect message quotes as part N,
and each entry names its enclosing part in parent, so the list stays flat however deeply a
sender nests the message.
for part in mail.mime_tree:
print(" " * part["depth"], part["index"], part["content_type"], part["roles"])
| Key | Meaning |
|---|---|
index, parent, depth |
Position in the list, position of the enclosing part (None for the root), nesting level. |
content_type |
The type the parser acted on. Absent or unusable headers get the RFC 2045/2046 default. |
content_type_raw |
The literal Content-Type value, None when the part has none. |
content_transfer_encoding |
Declared encoding, None when absent. |
charset, boundary |
Declared parameters. |
content_disposition |
Declared disposition type. |
filename, content_id |
Declared file name (decoded) and Content-ID. |
size |
Octets of a leaf after transfer decoding; None for a container. |
roles |
How the part was classified: any of container, body, attachment. |
attachment |
Position of the matching entry in mail.attachments. |
defects |
Defect categories recorded against this part. |
recovered |
True for a part recovered from an epilogue. |
embedded_headers |
Literal from, subject and date of a message enclosed in a message/* part. |
The tree is the structure on the wire annotated with the parser's interpretation, so the two can
be compared: named inline text has the roles attachment and body, an attached multipart has
container and attachment, and a leaf with no role was exposed neither as body text nor as an
attachment. Values are the ones the message declares; apart from content_type, an absent header
is None, never a default. A part whose container representation was omitted for the
resource limit keeps the attachment role, has attachment set to None and
carries ResourceLimitDefect.
mail.mime_tree_json is the same list as JSON. The tree is not part of mail.mail or
mail.mail_json; it is a computed name, so a wire header called Mime-Tree stays readable through
mail.headers. It is built the first time it is read, with one entry per part, and the number of
parts is chosen by the sender: about 400 bytes of JSON per entry, so a 2.7 MiB message made of
400,000 empty parts yields a 159 MiB tree. Bound the input size, or the number of entries you keep,
when the tree of untrusted mail is stored or sent on.
The drawing
mailparser.render_structure(mail) draws the message as text, in three sections: the main
headers, the delivery path and the MIME tree. The command line prints it with -st.
MESSAGE
From: meteo@regione.vda.it
Reply-To: meteo@regione.vda.it
Return-Path: <meteo@regione.vda.it>
To: echo@tu-berlin.de, Porcile, M. <mporcile@server_mail.it>
Subject: Bollettino Meteorologico del 29/11/2015
Date: Sun, 29 Nov 2015 09:45:18 +0100
Message-ID: <4516257BC5774408ADC1263EEBBBB73F@ad.regione.vda.it>
Defects: CharsetDecodeDefect
DELIVERY PATH
1 2015-11-29T08:45:17+00:00 WWWGESTIONE3 ([172.30.104.243]) ──▶ aspam2-ravda.regione.vda.it Microsoft SMTPSVC(6.0.37…
│ -3s
2 2015-11-29T08:45:14+00:00 aspam2-ravda.regione.vda.it (unknown… ──▶ Websense Email Security Gateway ESMTP
│ +48s
3 2015-11-29T08:46:02+00:00 smtp2.regione.vda.it (217.76.210.112… ──▶ smtp.customers.net SMTP
│ +0s
4 2015-11-29T08:46:02+00:00 (no from or by clause)
MIME TREE
0 multipart/mixed [container]
├─ 1 multipart/related [container]
│ ├─ 2 multipart/alternative [container]
│ │ ├─ 3 text/plain quoted-printable iso-8859-1 2.2 KB [body]
│ │ └─ 4 text/html 8bit 4.0 KB [body]
│ │ ⚠ CharsetDecodeDefect
│ ├─ 5 image/jpeg base64 9.7 KB [attachment] disposition:inline "intestazione.jpg"
│ └─ 6 image/jpeg base64 7.1 KB [attachment] disposition:inline "logometeo.jpg"
└─ 7 application/octet-stream base64 1.0 MB [attachment] disposition:attachment "Bollettino.pdf"
A warning mark means a defect the parser recorded for that hop or part; a delay is printed as a
number and never judged. Parts nested deeper than 32 levels are counted on one line instead of being
drawn. Pass ascii_only=True for ASCII connectors.
The drawing is safe to print: text taken from the message is cut to a bounded width, and control
characters, ANSI escapes, bidirectional and zero-width formatting characters, and characters that
draw nothing, are shown as visible escapes such as \x1b. Letters of different scripts that merely
look alike are not detected. The values in mime_tree, headers and received are not
escaped: they are untrusted text chosen by the sender, so escape them before putting them in HTML,
a terminal or a diagram language.
Defects
What a defect is
A defect is a parsing anomaly, an inconsistent value, or a recovery or ambiguity diagnostic. It
does not by itself establish malicious intent or an RFC violation, and has_defects=False only
means the implemented checks found no anomalies, not that the email passed a complete RFC
validation. What a defect does establish is that a parser had to make a choice: the message can
be read in more than one way, and a filter, a gateway and a mail client may not read it alike. That
difference is what an attacker exploits to hide a payload or a misleading name, and it is what
mail-parser makes visible.
Three rules hold for every defect:
- Nothing is dropped. The recovered value is what the properties return; the original stays in
mail.message, in the*_rawproperties and in therawfield of the diagnostic. - Recovery is not compliance.
recovered=Truemeans a value was recovered, not that the input was valid; the defect stays. - Neighbours survive. A malformed address, hop, date or part never changes how the valid ones next to it are read.
Where defects appear
| Property | Content |
|---|---|
has_defects |
True when anything below is nonempty. |
defects_categories |
The set of category names (a list in JSON), for example {"AddressHeaderDefect", "StartBoundaryNotFoundDefect"}. |
defects |
A list of dicts mapping a content type (multipart/mixed) or a group (address-headers, received-headers, date-headers, header-decoding, mime-headers, mime-resources, parser-errors) to lists of textual descriptions. Inspect every entry, not only defects[0]. |
address_header_defects |
Structured entries: reason, raw, recovered, candidates, header, occurrence. |
received_header_defects |
reason, raw, recovered, header, occurrence. |
date_header_defects |
reason, raw, recovered, the selected ISO value or None, header, occurrence. |
header_decoding_defects |
reason, raw, header, occurrence, part, recovered. |
resource_limit_defects |
reason, part, filename, recovered. |
parser_error_defects |
reason, unit, header, occurrence, part, raw, truncated, recovered, exception, detail. |
mime_tree[i]["defects"] |
The categories recorded against part i. |
occurrence is zero-based and counts repeated headers of the same name; every occurrence is
examined, while the address properties and mail.date keep the first one. The structured lists
always exist, are empty when there is nothing to report, and appear in mail, mail_partial and
their JSON only when nonempty. Standard-library defects and CharsetDecodeDefect,
MimeHeaderDefect, PayloadEncodingDefect have textual entries in defects only.
Catalogue of defects
| Category | Found in | Reasons and meaning |
|---|---|---|
AddressHeaderDefect |
address_header_defects, group address-headers |
invalid-display-name (text that looks like an address before <...>), invalid-or-ambiguous-address, structural-recovery (the standard library's reading could not be used), unclosed-delimiter, unmatched-delimiter, unclosed-group, unmatched-group, unmatched-angle, nested-angle, ambiguous-angle-address, invalid-angle-address, invalid-group-name, invalid-group-boundary, invalid-utf8, invalid-encoded-word, overlong-encoded-word, undelimited-encoded-word, control-characters-in-encoded-word, encoded-word-in-quoted-string. |
ReceivedHeaderDefect |
received_header_defects, group received-headers |
unclosed-comment, unclosed-quoted-string, unclosed-domain-literal, unclosed-angle-address, nested-angle-address, unexpected-comment-close, misplaced-date-separator, ambiguous-date-separators, nested-envelope-address, unclosed-envelope-address. |
DateHeaderDefect |
date_header_defects, group date-headers |
invalid-date-syntax, invalid-calendar-date (31 February), invalid-time (25:00), invalid-zone, weekday-mismatch (the date is kept), date-out-of-range, invalid-utf8. Covers Date, Resent-Date and the timestamp of every Received hop. |
HeaderDecodeDefect |
header_decoding_defects, group header-decoding |
invalid-encoded-word (with a detail: LookupError for an unknown charset, invalid-charset-name, punycode-charset, a malformed payload), undelimited-encoded-word, control-characters-in-encoded-word, invalid-utf8. The whole header stays literal. |
MimeHeaderDefect |
group mime-headers, mime_tree[i]["defects"] |
invalid-boundary-parameter (empty, missing, characters outside bchars, more than 70 characters, trailing space, matches the delimiter of part N, a value its charset cannot decode), invalid-parameter-continuation (RFC 2231 sections), invalid-filename-charset, invalid-charset-parameter, damaged filename bytes. |
CharsetDecodeDefect |
defects, keyed by the part's content type |
The declared body charset failed; the text is UTF-8 or replacement characters, the bytes stay in the part. |
PayloadEncodingDefect |
defects, keyed by the part's content type |
A payload held octets that are not UTF-8, or text the email package had to rewrite; the attachment is binary base64 of the wire octets. |
ResourceLimitDefect |
resource_limit_defects, group mime-resources |
container-serialization-limit: the textual copy of an attached container exceeded the per-message budget and was omitted. |
ParserErrorDefect |
parser_error_defects, group parser-errors |
unexpected-parser-error in one unit (address-header, date-header, received-header, header-decoding, mime-part, epilogue-recovery). A parser bug: see below. |
Standard library (NoBoundaryInMultipartDefect, StartBoundaryNotFoundDefect, CloseBoundaryNotFoundDefect, MultipartInvariantViolationDefect, MissingHeaderBodySeparatorDefect, ...) |
defects, keyed by the part's content type |
The structure defects of Python's email.errors. StartBoundaryNotFoundDefect means content sits outside the declared MIME structure and triggers the epilogue recovery. |
Using defects in a pipeline
The JSON of mail.mail_json carries has_defects, defects, defects_categories and every
nonempty structured list, so a downstream system needs no Python to act on them; mail-parser -j
prints the same document. In Python, a triage step reads the categories and the structured entries:
import mailparser
PARSER_BUGS = {"ParserErrorDefect"}
NEEDS_REVIEW = {
"AddressHeaderDefect", # a name or mailbox needed recovery
"StartBoundaryNotFoundDefect", # content outside the declared MIME structure
"MimeHeaderDefect", # a boundary, filename or charset outside its grammar
}
MISLEADING_NAMES = {"invalid-display-name", "encoded-word-in-quoted-string"}
def triage(mail):
"""Return what a filter needs to know about one parsed mail."""
names = [
candidate["display_name"]
for defect in mail.address_header_defects
if defect["reason"] in MISLEADING_NAMES
for candidate in defect["candidates"]
]
return {
"review": bool(mail.defects_categories & NEEDS_REVIEW),
"parser_bug": bool(mail.defects_categories & PARSER_BUGS),
"misleading_names": names,
"hidden_parts": [p["index"] for p in mail.mime_tree if p["recovered"]],
"unparsed_hops": [h["raw"] for h in mail.received if "by" not in h],
}
mail = mailparser.parse_from_string(
"From: billing@trusted.example <billing@vendor.example>\r\n"
'Content-Type: multipart/mixed; boundary="b"\r\n\r\n'
'--b\r\nContent-Type: multipart/alternative; boundary="b"\r\n\r\n'
"--b\r\nContent-Type: text/plain\r\n\r\nHello\r\n--b--\r\n"
'--b\r\nContent-Type: application/octet-stream; name="evidence.txt"\r\n'
'Content-Disposition: attachment; filename="evidence.txt"\r\n'
"Content-Transfer-Encoding: base64\r\n\r\nSGVsbG8=\r\n--b--\r\n"
)
result = triage(mail)
assert result["review"] is True
assert result["parser_bug"] is False
assert result["misleading_names"] == ["billing@trusted.example"]
assert result["hidden_parts"] == [3]
assert mail.attachments[0]["filename"] == "evidence.txt"
Things to keep in mind when you build on defects:
- Read
defects_categoriesfor routing and the structured lists for the evidence; the textualdefectsentries are for humans and logs. - An empty address list does not prove the header held no address: check
address_header_defectsbefore attributing or filtering on the sender. - A
recoveredpart inmime_treeis content another parser may not show; treat the attachments it holds as hidden. - Escape every value you print or render:
headers,received,mime_treeand the diagnostics hold the sender's text unescaped. - Bound the input size and the size of what you store: the number of parts, hops and headers is chosen by the sender.
Examples
Each block below is an assertion that holds; run them to see the shape of every reporting family.
import base64
import json
import mailparser
# 1. Recovered address: all four diagnostic views describe the same problem.
mail = mailparser.parse_from_string(
"From: billing@trusted.example < billing@vendor.example >\r\n\r\n"
)
assert mail.from_ == [("billing@trusted.example", "billing@vendor.example")]
assert mail.has_defects is True
assert "AddressHeaderDefect" in mail.defects_categories
assert mail.defects == [
{"address-headers": ["AddressHeaderDefect: from[0]: invalid-display-name"]}
]
assert mail.address_header_defects == [
{
"reason": "invalid-display-name",
"raw": "billing@trusted.example < billing@vendor.example >",
"recovered": True,
"candidates": [
{
"display_name": "billing@trusted.example",
"address": "billing@vendor.example",
}
],
"header": "from",
"occurrence": 0,
}
]
assert json.loads(mail.mail_json)["address_header_defects"] == (
mail.address_header_defects
)
# 2. Incomplete address: no selected mailbox; a valid neighbouring field survives.
mail = mailparser.parse_from_string(
"From: Alice <alice@example.com\r\nTo: Bob <bob@example.com>\r\n\r\n"
)
assert mail.from_ == []
assert mail.to == [("Bob", "bob@example.com")]
assert mail.address_header_defects[0]["reason"] == "unclosed-delimiter"
assert mail.address_header_defects[0]["recovered"] is False
# 3. Repeated headers: diagnostics also cover occurrences after the first.
mail = mailparser.parse_from_string(
"From: Alice <alice@example.com>\r\n"
"From: billing@trusted.example <billing@vendor.example>\r\n\r\n"
)
assert mail.from_ == [("Alice", "alice@example.com")]
assert mail.address_header_defects[0]["occurrence"] == 1
# 4. Received: ambiguous trace syntax stays raw, with structured diagnostics.
trace = (
"from sender.example (unclosed; by mx.example; 1 Jan 2024 12:00:00 +0000"
)
mail = mailparser.parse_from_string(f"Received: {trace}\r\n\r\n")
assert "ReceivedHeaderDefect" in mail.defects_categories
assert mail.received_header_defects[0]["reason"] == "unclosed-comment"
assert mail.received_header_defects[0]["recovered"] is False
assert mail.received[0]["raw"] == trace
assert "received-headers" in mail.defects[0]
trace = (
"from sender.example by mx.example with ESMTP id token; "
"for <bob@example.com>; 1 Jan 2024 12:00:00 +0000"
)
mail = mailparser.parse_from_string(f"Received: {trace}\r\n\r\n")
assert mail.received_header_defects[0]["reason"] == "misplaced-date-separator"
assert mail.received_header_defects[0]["recovered"] is True
assert mail.received[0]["for"] == "<bob@example.com>"
# 5. Dates: an impossible date is not selected; a wrong weekday is recoverable.
mail = mailparser.parse_from_string("Date: 31 Feb 2024 12:00:00 +0000\r\n\r\n")
assert "DateHeaderDefect" in mail.defects_categories
assert mail.date is None
assert mail.date_header_defects[0]["reason"] == "invalid-calendar-date"
assert mail.date_header_defects[0]["recovered"] is False
assert "date-headers" in mail.defects[0]
mail = mailparser.parse_from_string(
"Date: Tue, 1 Jan 2024 12:00:00 +0000\r\n\r\n"
)
assert mail.date.isoformat() == "2024-01-01T12:00:00+00:00"
assert mail.date_header_defects[0]["reason"] == "weekday-mismatch"
assert mail.date_header_defects[0]["recovered"] is True
# Date diagnostics also cover Resent-Date and timestamps inside Received.
mail = mailparser.parse_from_string(
"Resent-Date: 31 Feb 2024 12:00:00 +0000\r\n"
"Received: from sender.example by mx.example; "
"1 Jan 2024 25:00:00 +0000\r\n\r\n"
)
assert {d["header"] for d in mail.date_header_defects} == {
"resent-date",
"received",
}
# 6. Charset: failed declared decoding, then readable UTF-8 or replacement text.
for payload, expected in [(b"caf\xc3\xa9", "café"), (b"a\xffb", "a�b")]:
mail = mailparser.parse_from_bytes(
b"Content-Type: text/plain; charset=ascii\r\n\r\n" + payload
)
assert "CharsetDecodeDefect" in mail.defects_categories
assert expected in mail.body
assert "CharsetDecodeDefect:" in mail.defects[0]["text/plain"][0]
assert mail.message.get_payload(decode=True) == payload
# 7. MIME metadata: damaged filename bytes are retained in textual evidence.
mail = mailparser.parse_from_bytes(
b"Content-Type: application/octet-stream\r\n"
b'Content-Disposition: attachment; filename="a\xffb.bin"\r\n'
b"Content-Transfer-Encoding: base64\r\n\r\nSGVsbG8="
)
assert "MimeHeaderDefect" in mail.defects_categories
assert any(
"\\xff" in text
for entry in mail.defects
for text in entry.get("mime-headers", [])
)
assert base64.b64decode(mail.attachments[0]["payload"]) == b"Hello"
# 8. Standard-library structure defects: missing parameter/start/closing boundary.
for raw, category in [
(
"Content-Type: multipart/mixed\r\n\r\nHello",
"NoBoundaryInMultipartDefect",
),
(
'Content-Type: multipart/mixed; boundary="b"\r\n\r\nHello',
"StartBoundaryNotFoundDefect",
),
(
'Content-Type: multipart/mixed; boundary="b"\r\n\r\n'
"--b\r\nContent-Type: text/plain\r\n\r\nHello\r\n",
"CloseBoundaryNotFoundDefect",
),
(
"Subject: example\r\ninvalid header line\r\n\r\nHello",
"MissingHeaderBodySeparatorDefect",
),
]:
mail = mailparser.parse_from_string(raw)
assert mail.has_defects
assert category in mail.defects_categories
assert any(
category in text
for entry in mail.defects
for texts in entry.values()
for text in texts
)
# 9. Bad epilogue: reusing the parent's boundary corrupts nested MIME structure.
# The attachment after the first closing boundary lands in the outer epilogue.
raw = (
'MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary="b"\r\n\r\n'
'--b\r\nContent-Type: multipart/alternative; boundary="b"\r\n\r\n'
"--b\r\nContent-Type: text/plain\r\n\r\nHello\r\n--b--\r\n"
'--b\r\nContent-Type: application/octet-stream; name="evidence.txt"\r\n'
'Content-Disposition: attachment; filename="evidence.txt"\r\n'
"Content-Transfer-Encoding: base64\r\n\r\nSGVsbG8=\r\n--b--\r\n"
)
mail = mailparser.parse_from_string(raw)
assert mail.has_defects
assert "StartBoundaryNotFoundDefect" in mail.defects_categories
assert "multipart/alternative" in mail.defects[0]
assert "evidence.txt" in mail.message.epilogue
assert mail.attachments[0]["filename"] == "evidence.txt"
assert base64.b64decode(mail.attachments[0]["payload"]) == b"Hello"
# 10. Multiple families coexist; inspect every entry rather than only defects[0].
mail = mailparser.parse_from_string(
"From: billing@trusted.example <billing@vendor.example>\r\n"
"Date: 31 Feb 2024 12:00:00 +0000\r\n\r\n"
)
assert {"AddressHeaderDefect", "DateHeaderDefect"} <= mail.defects_categories
assert mail.address_header_defects and mail.date_header_defects
# 11. Valid controls: obsolete date syntax and an ordinary epilogue are accepted.
for raw in [
"From: Alice <alice@example.com>\r\n"
"Date: 1 Jan 24 12:00:00 GMT\r\n\r\nHello",
'Content-Type: multipart/mixed; boundary="b"\r\n\r\n'
"--b\r\nContent-Type: text/plain\r\n\r\nHello\r\n"
"--b--\r\nOrdinary epilogue\r\n",
]:
mail = mailparser.parse_from_string(raw)
assert mail.has_defects is False
assert mail.defects_categories == set()
assert mail.defects == []
assert mail.address_header_defects == []
assert mail.received_header_defects == []
assert mail.date_header_defects == []
When the parser reports its own failure
Two artifacts mean a bug in mail-parser, not a property of the message:
MailParserUnexpectedError, raised when an exception the parser did not expect escapes while parsing one message or reading one of its properties. It names the class of the original exception, carries a bounded copy of its message and the original as__cause__; the traceback is logged, never put in the text.ParserErrorDefect, recorded inmail.parser_error_defectswhen the failure was confined to one unit of the message: one address header occurrence, oneDate, oneReceivedhop, one header to decode, one MIME part or the epilogue recovery. That unit is absent from the result (from_ == [],date is None, a raw-only hop, a part with no text and no attachment), its neighbours are parsed as usual, and the entry keeps the wire text of the unit inraw(at most 1024 characters,truncatedsays when it was cut), withexceptionanddetail.
What to do with one:
- Keep the message. It is the reproducer, and the parse is otherwise usable.
- Open a public issue with the message (or
the
rawof the entry), the Python version and the output ofmail-parser -f <file> -d -j, or a pull request with a regression test. It is not a security report: see SECURITY.md for what is, and for the one exception, a failure that comes together with another in-scope impact. - Expect a fix that parses the field. Every such entry is meant to become either normal parsing of that unit or a specific, named defect in a later release; neither artifact is a permanent classification.
MailParserError, RecursionError and MemoryError are never turned into a defect: a message
nested too deep ends the parse with MailParserRecursionError.
Forensic recovery
Every section below is the short form of a rule; the complete rules, with every edge case and the defect it records, are in docs/forensic-recovery.md.
Addresses
Address properties return (display_name, address) tuples. Selection respects quoted strings,
escapes, nested comments, groups and folding whitespace, and follows three rules:
- a complete angle-address (
<...>) wins over its display name, sobilling@trusted.example <billing@vendor.example>selects the vendor address and reports the misleading name asinvalid-display-name; - an address inside a comment or a quoted display name is never a candidate;
- an ambiguous or incomplete item is left out of the tuples, its evidence and candidates kept in
address_header_defects, and the valid items next to it are read as usual.
Internationalized addresses (RFC 6532) parse without
defects; code points are preserved as written (no normalization, no IDNA, no trimming of
whitespace lookalikes), and malformed UTF-8 is invalid-utf8 evidence, never a different valid
address. Encoded words in display names are decoded only where RFC 2047 allows them; a word that is
malformed, glued to other text, inside a quoted string, decodes to control characters or names an
ill-formed or punycode charset stays literal and is reported with its own reason.
mail = mailparser.parse_from_string(
"From: billing@trusted.example < billing@vendor.example >\r\n\r\n"
)
assert mail.from_ == [("billing@trusted.example", "billing@vendor.example")]
assert mail.address_header_defects[0]["reason"] == "invalid-display-name"
Received trace
Received clauses are split by a scanner that respects comments, quoted strings, domain literals
and angle addresses, so a delimiter inside them is never a clause boundary. An ambiguous header
keeps its text in received[*]["raw"] and is explained in received_header_defects; an ambiguous
trusted hop stops sender-IP attribution rather than letting an older, forgeable hop supply the IP.
Envelope annotations (envelope-from, envelope-sender) are lexical extractions, scanned without
backtracking: a nested or unterminated path is reported, not selected. Obsolete trace syntax that is
balanced stays raw and is not called invalid for being obsolete.
Dates
An impossible date (31 Feb), time (25:00) or zone gives None and a defect instead of silently
becoming another timestamp. A wrong weekday keeps the numerical date and records
weekday-mismatch. The same checks apply to Date, Resent-Date and the timestamp of every
Received hop, each with its header and occurrence in date_header_defects. Obsolete but
valid forms (comments, two-digit years, alphabetic zones) are accepted; leap seconds map to the next
representable datetime and the raw text keeps :60.
Text, charsets and payloads
- A body is decoded with its declared charset; when that fails, readable UTF-8 is used and
CharsetDecodeDefectsays so, then replacement characters if UTF-8 fails too. The bytes stay in the MIME part. - An attachment
payloadis base64 of the bytes the recipient received, so its hash is the hash of the file. Octets that are not UTF-8 in a text payload, or text the email package had to rewrite, are reported asPayloadEncodingDefect. - Headers are written back as stored:
message_as_stringnever re-encodes non-ASCII text as an encoded word, so a message parsed from bytes keeps its octets as surrogate escapes there. - Header decoding is strict: an unknown charset, an invalid byte sequence or a non-Unicode scalar
leaves the whole header literal, with
HeaderDecodeDefect, instead of dropping bytes or mixing a decoded prefix with the original. - A charset name outside RFC 2978 (
utf-8é), andpunycodein any position, are treated as charsets that name no codec, on every Python version. - A named
text/plainortext/htmlpart declaredinlineappears both in the text collections and inattachments.
MIME parameters and boundaries
A malformed RFC 2231 parameter never stops the parse: a charset that refuses its octets, numbered
and unnumbered sections mixed, a section given twice or a section number too long are read the way
current Python releases read them, on every Python, and reported as MimeHeaderDefect on that
part. Boundaries follow RFC 2046 section 5.1.1 and every departure is reported as
invalid-boundary-parameter while the parts are still found: an empty or missing boundary is read
with -- and ----, a boundary outside the bchars grammar or longer than 70 characters is read
as the body lines hold it (on both entry points, a non-ASCII or percent-encoded one included), and
a nested boundary that matches an enclosing delimiter is reported with the part it clashes with and
its hidden sub-parts are recovered from the epilogue as recovered entries of mime_tree. Other
parsers may split such a message differently: a message with this defect must not be assumed to
show the same attachments everywhere.
Resource limits
The textual copies of attached containers and forwarded messages share a per-message work budget
(32 times the estimated size of the tree, between 1 Mi and 32 Mi characters; 16 node visits per
part, between 1,024 and 100,000). A copy that does not fit is omitted from attachments, never
truncated, and resource_limit_defects names the part; its children and the neighbouring parts are
still recovered. The budget bounds the parser's own copies, not the input: bound the input size and
isolate workers according to your own constraints. message_as_string raises
MailParserRecursionError for a message nested too deeply to flatten (about 250 levels with the
default recursion limit); deep nesting is not a defect, and mail.message and mail.mime_tree
still expose the tree.
Command line
usage: mail-parser [-h] (-f FILE | -s STRING | -k)
[-l {CRITICAL,ERROR,WARNING,INFO,DEBUG,NOTSET}] [-j] [-b]
[-a] [-r] [-t] [-dt] [-m] [-u] [-c] [-d] [-o]
[-i Trust mail server string] [-p] [-z] [-sa]
[-ap ATTACHMENTS_PATH] [-st] [--mime-tree] [-v]
Wrapper for email Python Standard Library
options:
-h, --help show this help message and exit
-f, --file FILE Raw email file (default: None)
-s, --string STRING Raw email string (default: None)
-k, --stdin Enable parsing from stdin (default: False)
-l, --log-level {CRITICAL,ERROR,WARNING,INFO,DEBUG,NOTSET}
Set log level (default: WARNING)
-j, --json Show the JSON of parsed mail (default: False)
-b, --body Print the body of mail (default: False)
-a, --attachments Print the attachments of mail (default: False)
-r, --headers Print the headers of mail (default: False)
-t, --to Print the to of mail (default: False)
-dt, --delivered-to Print the delivered-to of mail (default: False)
-m, --from Print the from of mail (default: False)
-u, --subject Print the subject of mail (default: False)
-c, --receiveds Print all receiveds of mail (default: False)
-d, --defects Print the defects of mail (default: False)
-o, --outlook Analyze Outlook msg (default: False)
-i, --senderip Trust mail server string
Extract a reliable sender IP address heuristically
(default: None)
-p, --mail-hash Print mail fingerprints without headers (default:
False)
-z, --attachments-hash
Print attachments with fingerprints (default: False)
-sa, --store-attachments
Store attachments on disk (default: False)
-ap, --attachments-path ATTACHMENTS_PATH
Path where store attachments (default: /tmp)
-st, --structure Draw the message structure: headers, delivery path,
MIME tree (default: False)
--mime-tree Print the MIME tree of mail as JSON (default: False)
-v, --version show program's version number and exit
It takes as input a raw mail and generates a parsed object.
Examples:
mail-parser -f example_mail -j # parsed mail as JSON
mail-parser -f example_mail -u -m # subject and sender only
mail-parser -f email.msg -o -d -j # an Outlook file, with its defects
mail-parser -f example_mail -st # headers, delivery path and MIME tree as a drawing
mail-parser -f example_mail -j --mime-tree # JSON of the mail, then JSON of the MIME tree
mail-parser -f example_mail -j > example.json # logs go to stderr, stdout is JSON only
cat raw_email.eml | mail-parser -k -j # from stdin, for pipelines
Text taken from the headers reaches the terminal escaped: -u shows a control character, an ANSI
escape, a bidirectional override or a zero-width character as \x1b, and the like (a
backslash is doubled), as -st does, and the JSON options write the same characters as \uXXXX,
which parses to the same value. -b prints the body as the message has it, since it is the content
the analyst asked for: pipe it to cat -v when the source is not trusted.
See the transformation from raw email to parsed JSON output.
Exception hierarchy
MailParserError: Base MailParser Exception
|
\── MailParserOutlookError: Raised with Outlook integration errors
|
\── MailParserEnvironmentError: Raised when the environment is not correct
|
\── MailParserOSError: Raised when there is an OS error
|
\── MailParserPathError: Raised when an attachment escapes the output directory
|
\── MailParserReceivedParsingError: Raised when a received header cannot be parsed
|
\── MailParserRecursionError: Raised when a message is nested too deeply to parse or flatten
|
\── MailParserUnexpectedError: Raised when an unexpected exception escapes the parser on one message
Every error the library raises is a MailParserError. MailParserUnexpectedError is the one that
should never happen: see
When the parser reports its own failure.
Reporting security issues
Do not report vulnerabilities in public issues. See SECURITY.md for supported versions, private reporting channels and the disclosure process.
Docker deployment
A pre-built image is on Docker Hub:
sudo docker run -it --rm -v ~/mails:/mails fmantuano/spamscope-mail-parser
The command mounts your local ~/mails directory at /mails in the container; any command-line
option of mail-parser can follow. A docker-compose.yml with a read-only mount of ~/mails and a
test command is in the repository: sudo docker-compose up.
mail-parser in the ecosystem
Packages and distributions:
- FreeBSD: the
mail/py-mail-parserport. - Arch User Repository (AUR): the
community-maintained
mailparserpackage. - Debian: the
mail-parsersource package in Debian unstable (sid). - REMnux: included in the REMnux malware analysis toolkit.
Integrations:
- IBM Security QRadar SOAR — Parse Utilities:
uses mail-parser to extract headers, body parts and attachments from
.emland.msgfiles for incident response workflows.
Research use:
- A Large-Scale Empirical Study of Modern Phishing Email Content, Jaehwan Park et al., arXiv preprint, September 2026: analyzes 2.9 million phishing emails and uses mail-parser to extract PDF, image and calendar invitation attachments from their MIME structure (Section III-A, reference 34).
Support mail-parser
mail-parser is free and open source. Thousands of developers and security professionals rely on it for email processing and threat analysis. Every donation, whether $5 or $500, funds development time and infrastructure: detection of new evasion techniques, RFC compliance, performance, and tested releases you can trust in production.
Bitcoin address: bc1qxhz3tghztpjqdt7atey68s344wvmugtl55tm32
Show Bitcoin QR code
Thank you for supporting mail-parser!
License and authors
mail-parser is available under the Apache 2 license: it can be downloaded, used and modified free of charge.
Main author: Fedele Mantuano (LinkedIn).
Working with coding agents
AGENTS.md is the shared source of development commands, coding conventions,
architecture notes and security review requirements.
Codex reads it automatically;
CLAUDE.md imports the same file using
Claude Code's import syntax, so
updates to shared guidance belong in AGENTS.md.
The security reviewer is available as a Claude Code
sub-agent; Codex follows the same review procedure as described in AGENTS.md. Two repository
skills provide RFC parsing reviews: mail-rfc-diff for changed code and mail-rfc-assessment for
the entire repository. Both report demonstrated issues with RFC references, runnable examples and
suggested resolutions. See installation and usage for Codex and Claude
Code.
Metadata
Release files for mail-parser 4.13.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| mail_parser-4.13.0.tar.gz | 3.2 MB | Without provenance | Details for mail_parser-4.13.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| mail_parser-4.13.0-py3-none-any.whl | Python 3 | none | any | Details for mail_parser-4.13.0-py3-none-any.whl |
Total release size: 3.3 MB
Release files / mail_parser-4.13.0.tar.gz
| Download URL | mail_parser-4.13.0.tar.gz |
|---|---|
| Size | 3.2 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
68bf1252b58f244a4287d3eeef5e7be28f0a5944db233910b61594e36128de70
|
|
BLAKE2b-256 checksum How to use checksums |
02ede625dd866bae58622073c226868339b168eed7f8baeb4fc34dd3b91aa9da
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Release files / mail_parser-4.13.0-py3-none-any.whl
| Download URL | mail_parser-4.13.0-py3-none-any.whl |
|---|---|
| Size | 113.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
c8035b4278b240b830465626b0aa8e744222672abb7ec4e854b0fecb49a9fbcb
|
|
BLAKE2b-256 checksum How to use checksums |
5177ffb8bcc2bc5054ec4dfbf962a8301b434adfc404f17fd54075c94ef1aa63
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Security for mail-parser 4.13.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.