mail-parser

4.2.1 · active · verified Sat Apr 11

mail-parser is a production-grade, RFC-compliant email parsing library that enhances the Python standard library's email module. It extracts all details into a comprehensive object, including headers, plain text and HTML bodies, attachments, and routing information, with a strong focus on security analysis and defect detection. It provides access to parsed elements as Python objects, raw strings, and JSON. The library is actively maintained.

Warnings

Install

Imports

Quickstart

Parses a raw email string and extracts basic headers and the plain text body. Demonstrates accessing structured email components like sender, subject, and body content.

import mailparser

raw_email = (
    "From: Sender Name <sender@example.com>\n"
    "To: Recipient Name <recipient@example.com>\n"
    "Subject: Test Email from mail-parser\n"
    "Content-Type: text/plain; charset=\"utf-8\"\n"
    "\n"
    "Hello, this is the plain text body of the email.\n"
    "It was parsed using the mail-parser library."
)

mail = mailparser.parse_from_string(raw_email)

print(f"From: {mail.from_}")
print(f"Subject: {mail.subject}")
if mail.text_plain:
    print(f"Body: {mail.text_plain[0]}")

# Example of accessing the 'to' address list
for recipient in mail.to:
    print(f"To Name: {recipient[0]}, Address: {recipient[1]}")

view raw JSON →