email.parser Splits MIME Messages
Parse a multipart MIME message with email.parser, list each content type, and read text bodies and attachment payloads.
Code
from email import policy
from email.parser import Parser
RAW = '''From: [email protected]
To: [email protected]
Subject: Release checklist
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="cut"
--cut
Content-Type: text/plain; charset="utf-8"
Ship the release notes.
--cut
Content-Type: application/json
Content-Disposition: attachment; filename="meta.json"
{"version": "1.2.0"}
--cut--
'''
def main() -> None:
message = Parser(policy=policy.default).parsestr(RAW)
print('subject:', message['subject'])
print('from:', message['from'])
print('multipart:', message.is_multipart())
for part in message.walk():
kind = part.get_content_type()
name = part.get_filename()
print('part:', kind, '| filename:', name)
if kind == 'text/plain':
print('body:', part.get_content().strip())
elif name:
payload = part.get_payload(decode=True) or b''
print('attachment payload:', payload.decode('utf-8').strip())
if __name__ == '__main__':
main()What the code does
email.parser Splits MIME Messages keeps everything in the function main.
Repetition is confined to for part in message.walk() — the rest of the file is straight-line. Reach for email and what you get is policy, Parser — that is the whole API contact area.
Watch out for
- Plan for an install step:
emailis a real dependency, resolved by the package manager.
Applying it
Entry signature: def main() -> None
The run emits 6 labeled sections — subject:, from:, multipart:, part:, body:, attachment payload: — one per step.
Interactive Tools for This Topic
Quoted-Printable CodecEncode and decode quoted-printable (RFC 2045) used by email, escaping non-ASCII bytes and wrapping long lines.Email Address ValidatorValidate email syntax, checking the local part, domain labels, and top-level domain against common rules.MIME Type LookupResolve a file extension, file name, or MIME type to its media type, category, and related extensions using a local reference table.
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `email`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.