Inspect inert MIME attachments
Describe decoded attachment bytes without opening them or trusting their filenames.
MIME separates content from transport encoding
An email may contain plain text, HTML, inline images, and attached files in a nested MIME tree. message.walk() visits its parts. Container parts group other parts; leaf parts hold payload bytes. Select leaf parts explicitly marked with an attachment disposition for this exercise.
Base64 and quoted-printable are transport encodings. Hash the decoded payload, not the encoded text displayed in the raw message. get_payload(decode=True) returns the bytes needed for a length calculation and a SHA-256 digest. Different transport encodings of the same file should produce the same hash.
A filename is untrusted metadata
An attachment can claim any filename or content type. Record those claims without executing the content or writing it to the claimed path. A filename such as ../outside.txt must not become permission to write outside an evidence directory. This exercise produces metadata only and never extracts attachments to disk.
Keep duplicate filenames as separate entries in traversal order. A dictionary keyed only by filename could silently overwrite one attachment with another. A zero-byte attachment is still an attachment and has a valid digest.
The fixture contains inert training text. A digest identifies bytes for comparison; it does not label them malicious or safe. A production investigation would retain collection context and compare against a suitably trusted source before making a conclusion.
from hashlib import sha256
import base64
payload = base64.b64decode("aGVsbG8=")
print(len(payload), sha256(payload).hexdigest())
Put it into practice.
Define attachment_manifest(raw). Walk parsed email bytes; include non-multipart parts whose disposition is attachment. Return filename (empty if absent), content_type, size in decoded bytes, and lowercase SHA-256 for each, in traversal order. Preserve duplicate or path-like filenames as metadata only. Do not write any attachment to disk. Ignore inline parts.
See an explained solution
from email import policy
from email.parser import BytesParser
from hashlib import sha256
def attachment_manifest(raw):
message = BytesParser(policy=policy.default).parsebytes(raw)
entries = []
for part in message.walk():
if part.is_multipart() or part.get_content_disposition() != "attachment":
continue
payload = part.get_payload(decode=True) or b""
entries.append({"filename": part.get_filename() or "", "content_type": part.get_content_type(), "size": len(payload), "sha256": sha256(payload).hexdigest()})
return entries
The manifest describes each leaf attachment using its decoded bytes. Filenames stay inert metadata, and a list preserves duplicate names.