email.parser Splits MIME Messages

Parse a multipart MIME message with email.parser, list each content type, and read text bodies and attachment payloads.

PythonData Fetching

Code

pythonsnippet
42 lines
from email import policy
from email.parser import Parser


RAW = '''From: ada@example.com
To: team@example.com
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: email is 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

FAQ

Which packages must be installed first?
Yes. The imports resolve to `email`, which the package manager must provide.