All posts →
|Also available in:DE

Automatically Process Email Attachments

Process .eml and .msg files with the MaraDocs API. Extract email attachments, validate them and process them further as images or PDFs. Recursive support for emails within emails.

•Martin Kurtz
APIEmailDocument ProcessingDevelopers
Automatically Process Email Attachments

Incoming emails often contain documents as attachments – images, PDFs, and sometimes nested .eml or .msg files. In our law firm, a single client email could contain a dozen photos of an accident report, a PDF expert opinion, and a forwarded email with its own attachments. An email attachment processing API that extracts every attachment, validates it, and routes it into the right pipeline would save hours of manual work.

Images need to be routed to document extraction or OCR, PDFs to merging or compression – and nested emails must be processed recursively.

Why Building Your Own Email Attachment Processing Takes Weeks

Anyone who wants to build this themselves quickly discovers that parsing .eml and .msg requires mail-parser, extract-msg, or something similar. Then MIME has to be decoded, nested messages processed, binary data extracted, formats detected (magika, file signatures), files scanned for viruses, and the flow branched according to image/PDF logic. Each step has its own sources of error: malformed headers, encodings, and nested emails with their own attachments. Building a robust email attachment processing API in-house takes weeks.

How the MaraDocs Email Attachment Processing API Solves This in Minutes

The MaraDocs API validates .eml and .msg files in a single call. You get structured attachment handles – each with type information. From there, you can branch into image or PDF operations: validate by type, then apply document extraction, OCR, composition, or compression. The API supports recursive processing of emails attached within other emails.

Email Attachment Processing Workflow: Upload, Validate, Extract, Route

Upload the email file and call email.validate. The response contains attachment handles – each with content type and metadata. For each attachment, check the type (image, PDF, or nested email). Validate the attachment with img.validate or pdf.validate, then chain it into the pipeline: flow.ocrImg for images, pdf.compose to merge PDFs, pdf.optimize for compression. Nested emails can be validated again to extract their attachments recursively. The entire pipeline runs server-side; handles are passed between steps without downloading and re-uploading.

Get your API key in under a minute

Register for a free account and get your API key in under a minute. Of course we'll provide you with some developer credits.

Try MaraDocs API now →

What Sets MaraDocs Apart: Workspaces, Webview, and German Data Protection Law

Most document APIs force you to download every attachment, upload it again elsewhere, and track identities across multiple steps. With MaraDocs, all files – the email and its attachments – live in the same workspace. Validate the email, iterate over the attachment handles, and pass them to img/pdf/flow endpoints. Handles flow; data stays server-side. No download-upload cycles for each attachment.

If a nested email has an unexpected structure or an attachment needs to be checked manually, you can open app.maradocs.io with the workspace secret to inspect and reorder files. Users get full manual control when automation reaches its limits.

Processing takes place in Germany (Maramia GmbH), with encryption at rest and in transit. Workspaces expire after 7 days. No data leaves the EU. For privacy-sensitive email processing, this matters.

TypeScript Code for Extracting Email Attachments

API reference: data/upload, email/validate, img/validate, pdf/validate, flow.ocrImg, data/download/pdf

import { MaraDocsClient } from "@maramia/maradocs-sdk-ts";
import { okEmail } from "@maramia/maradocs-sdk-ts/models/email";
import { okImg } from "@maramia/maradocs-sdk-ts/models/img";
import { okPdf } from "@maramia/maradocs-sdk-ts/models/pdf";

const client = new MaraDocsClient({ workspaceSecret: workspace_secret });

// E-Mail hochladen und validieren
const uploaded = await client.data.upload(emailFile);
const validated = await client.email.validate({
  unvalidated_file_handle: uploaded.unvalidated_file_handle,
});
const email = okEmail(validated);

const pdfHandles: string[] = [];
for (const att of email.attachments) {
  if (att.content_type?.startsWith("image/")) {
    const imgVal = await client.img.validate({
      unvalidated_file_handle: att.unvalidated_file_handle,
    });
    const imgHandle = okImg(imgVal);
    const pdfHandle = await client.flow.ocrImgHandle(imgHandle);
    pdfHandles.push(pdfHandle);
  } else if (att.content_type === "application/pdf") {
    const pdfVal = await client.pdf.validate({
      unvalidated_file_handle: att.unvalidated_file_handle,
    });
    pdfHandles.push(okPdf(pdfVal));
  }
}
// Zusammenführen und herunterladen
const composed = await client.pdf.compose({
  pdfs: pdfHandles.map((pdf_handle) => ({ pdf_handle })),
});
const blob = await client.data.downloadPdf({ pdf_handle: composed.pdf_handle });

Python Code for Email Attachment Extraction

API reference: data/upload, email/validate, img/validate, pdf/validate, pdf/compose, data/download/pdf

# pip install python-decouple requests
"""Extract PDF attachments from an email using MaraDocs. Set ACCOUNT_SECRET in .env or environment."""

import sys
import time
from pathlib import Path

import requests
from decouple import config

API_URL = "https://api.maradocs.io/v1"


def create_workspace() -> dict:
    """Create a workspace and return auth headers."""
    r = requests.post(
        f"{API_URL}/workspace",
        headers={"Authorization": f"Bearer {config('ACCOUNT_SECRET')}"},
        json={"subaccount": None},
    )
    ws = r.json()
    return {"Authorization": f"Bearer {ws['workspace_secret']}"}


def upload_file(path: Path, auth: dict) -> dict:
    """Upload a file via two-step flow (signed URL + S3 POST). Returns unvalidated_file_handle."""
    data = path.read_bytes()
    resp = requests.post(
        f"{API_URL}/data/upload",
        headers={**auth, "Content-Type": "application/json"},
        json={"name": path.name, "size": len(data)},
    ).json()
    requests.post(
        resp["post_url"],
        data=resp.get("post_header", {}),
        files={"file": (path.name, data, "message/rfc822")},
    )
    return resp["unvalidated_file_handle"]


def run_job(path: str, payload: dict, auth: dict, timeout: int = 60) -> dict:
    """Run a job and poll until complete. Returns the result (unwraps response if present)."""
    url = f"{API_URL}/{path}"
    r = requests.post(url, headers=auth, json=payload).json()
    job_id = r["job_id"]
    start = time.time()
    while time.time() - start < timeout:
        poll_r = requests.get(f"{url}/{job_id}", headers=auth)
        if poll_r.status_code == 200:
            return poll_r.json()
    raise TimeoutError(f"Job {path} timed out")


def pdf_handles_from_email(email_handle: dict) -> list:
    """Recursively extract all pdf_handles from an email_handle (handles nested emails)."""
    handles = []
    for att in email_handle.get("attachments", []):
        media = att.get("media_type") or {}
        mt = media.get("media_type", "") if isinstance(media, dict) else ""
        validated = att.get("validated") or {}

        if mt == "application/pdf":
            resp = validated.get("response", {})
            if pdf_h := resp.get("pdf_handle"):
                handles.append(pdf_h)
        elif mt == "message/rfc822":
            nested = (validated.get("response") or {}).get("email_handle")
            if nested:
                handles.extend(pdf_handles_from_email(nested))
    return handles


def download_pdf(pdf_handle: str, auth: dict) -> bytes:
    """Request signed URL and fetch PDF bytes."""
    r = requests.post(
        f"{API_URL}/data/download/pdf",
        headers=auth,
        json={"pdf_handle": pdf_handle},
    )
    info = r.json()
    dl = requests.get(info["url"], headers=info.get("headers", {}))
    return dl.content


def main() -> None:
    email_path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("input_email.eml")
    auth = create_workspace()
    handle = upload_file(email_path, auth)
    email_data = run_job("email/validate", {"unvalidated_file_handle": handle}, auth)
    email_handle = email_data["response"]["email_handle"]
    pdf_handles = pdf_handles_from_email(email_handle)

    if not pdf_handles:
        sys.exit("No PDF attachments found")

    composed = run_job(
        "pdf/compose",
        {"pdfs": [{"pdf_handle": h} for h in pdf_handles]},
        auth,
    )
    pdf_handle = composed["pdf_handle"]
    Path("attachments.pdf").write_bytes(download_pdf(pdf_handle, auth))
    print("attachments.pdf created")


if __name__ == "__main__":
    main()

Summary and Next Steps

An email attachment processing API that extracts, validates, and routes attachments is available. MaraDocs handles virus scanning, format detection, and recursive email parsing. For full automation, combine it with the document scanner, PDF processing, and text recognition.


Try it now: MaraDocs API | TypeScript SDK


Subscribe to our newsletter

Stay up to date with us and receive the latest news, articles, and resources by email.