AI Email Parser: Extract and Validate an Invoice as JSON
Parse a sample invoice email into JSON with MailSlurp, then check its fields, totals and duplicates using a downloadable Python example.

Some email is practically a database row wearing a trench coat. The fields are all there, but they are tucked into a subject line, an HTML table, a PDF attachment, or a sentence written differently by every sender.
An AI email parser turns that mixed content into a predictable record. It can receive the message, read the body and attachments, apply OCR where needed, classify the content, and return fields in a schema your application understands.
The useful result is not simply "the AI understood the email." It is a typed output that can be checked, traced to its source, reviewed when something looks wrong, and delivered safely to another system.
Quick answer: how does AI email parsing work?
An AI email parsing workflow has five layers:
| Layer | What happens | What you should keep |
|---|---|---|
| Intake | Receive a message in a dedicated inbox, by forwarding, or from a connected account | Email ID, sender, recipient, headers, received time |
| Reading | Separate the text, HTML, and attachments; use OCR for scanned content | Attachment IDs and the original files |
| Extraction | Classify the message and map the useful facts into named fields | Instructions, schema, and schema version |
| Validation | Check required fields, formats, totals, duplicates, and workflow rules | Validation outcome and review reason |
| Delivery | Send an accepted result to an API, webhook, queue, database, or spreadsheet | Result ID, delivery receipt, retry state |
That final pair of layers is what makes email data extraction useful in production. A plausible-looking value is not the same thing as a safe invoice, support ticket, or shipment update.
AI parser, rules, or both?
AI is helpful when language and layout vary. Rules are excellent when the input is stable. Most reliable systems use both.
| Input | Better starting point | Why |
|---|---|---|
| One sender with a fixed template | Rules | Fast, deterministic, and easy to test |
| Many invoice suppliers and layouts | AI plus schema | The meaning is consistent even when the page layout is not |
| A scanned PDF or image | OCR, then AI extraction | The text must be recovered before fields can be interpreted |
| Free-form support messages | AI classification and extraction | Intent and identifiers may be expressed in many ways |
| High-risk finance workflow | Hybrid | AI finds the fields; deterministic checks decide what can proceed |
A rule can recognize that a sender address ends in a known domain, or that a subject contains Invoice. AI can then interpret the less predictable body or attachment. After extraction, ordinary code should still check the parts that must be exact.
If you have one stable text template, a conventional email parser API may be all you need. If the important data moves between prose, tables, PDFs, and scans, AI parsing earns its keep.
What happens to an email before extraction?
Email is not one neat block of text. A single message may contain a plain-text body, an HTML body, inline images, headers, and several attachments, all wrapped in MIME parts.
A sound intake process should:
- preserve the original email and its identifiers;
- choose the useful body representation instead of parsing navigation or signatures as business data;
- list and retain attachments rather than flattening them into the message body;
- extract text from born-digital documents; and
- use OCR when a PDF or image contains pixels rather than selectable text.
MailSlurp parser workflows can work with message bodies and attachments such as PDF, CSV, XLSX, DOCX, and HTML. You can create a purpose-built receiving address, forward an existing mailbox, or connect supported Gmail and Outlook accounts. A dedicated inbox is often the cleanest choice for a new workflow because it gives the parser a narrow, predictable stream of messages.
OCR is one step, not the whole solution. It can turn an image of Total: $184.50 into text, but it does not decide whether that number is the subtotal, tax-inclusive total, amount paid, or balance due. That distinction belongs in the extraction instructions and the checks that follow.
A real email-to-JSON example
Let's use a small invoice email from the fictional supplier Cedar Paper Co. The email body mentions purchase order PO-7701; its attachment, invoice.txt, contains invoice INV-1042. The parser needs to keep those two references separate and extract the amounts from the invoice.
Download the complete invoice parsing example. It includes the MIME email, readable attachment, instructions, schema, extraction client, captured result and validation code. Extract it and run the commands from the ai-email-parser folder with Python 3.9 or newer. No additional Python packages are required.
The attachment contains:
Cedar Paper Co.
Invoice: INV-1042
Invoice date: 2026-10-01
Currency: USD
Description | Quantity | Line total
A5 notebooks | 2 | USD 50.00
Recycled paper cartons | 1 | USD 100.00
Subtotal: USD 150.00
Tax: USD 22.50
Total payable: USD 172.50
MailSlurp's extraction returned this object, which is included as result.json:
{
"supplier": "Cedar Paper Co.",
"invoiceNumber": "INV-1042",
"invoiceDate": "2026-10-01",
"currency": "USD",
"subtotalCents": 15000,
"taxCents": 2250,
"totalCents": 17250,
"lineItems": [
{ "description": "A5 notebooks", "quantity": 2, "lineTotalCents": 5000 },
{ "description": "Recycled paper cartons", "quantity": 1, "lineTotalCents": 10000 }
]
}
The invoice number comes from the attachment, and USD 172.50 becomes 17250 integer cents. This example uses a text attachment imported into a MailSlurp inbox; it demonstrates extraction, without an outbound send, PDF parsing or OCR. Scanned documents need their own examples and checks.
You can inspect and validate the included result without an account or API key:
python3 validate.py result.json
python3 test_validation.py
The first command prints:
PASS: invoice fields, dates, currency and totals are valid.
PASS: replay rejected; one invoice remains stored.
The replay check uses an in-memory SQLite database inside that command. It demonstrates rejecting the same invoice twice within one process; it does not retain invoices after the command exits.
The prompt explains meaning; the schema controls shape
The extraction instructions tell MailSlurp which facts to use:
Extract only the invoice facts from the attached invoice.txt. Use the supplier invoice number, not the purchase order reference in the email body. Convert monetary amounts to integer cents. Preserve each line item separately. invoiceDate must use YYYY-MM-DD. Do not infer a missing field from a different message or invent a value.
The bundled schema.json declares eight required invoice fields, including a nonempty line-item array. Monetary amounts use integer cents, and each line item has a description, positive integer quantity and nonnegative integer line total. The date is a string whose description asks for YYYY-MM-DD.
That schema guides the requested output. The Python validator separately enforces exact fields, valid calendar dates, USD currency and arithmetic. Unknown-field rejection belongs to that application validator; the example does not send an additionalProperties setting to the API. A correctly shaped object still needs checking against the source invoice.
Run a new extraction with your account
The optional live step requires a MailSlurp API key, paid AI access and sufficient AI and inbox allowance. Provide your key as the MAILSLURP_API_KEY environment variable using your usual secret manager or shell setup, then run:
python3 extract.py
python3 validate.py result.json
The script requests a temporary inbox, imports the supplied MIME email with runPipeline: false, and calls POST /ai/structured-content/email with contentSelector: "BODY_ATTACHMENTS", the instructions and the schema. One successful run makes one AI extraction request and overwrites result.json with the returned object. Repeat runs consume additional allowance; validate each result before using it.
The script attempts to delete only its own temporary inbox in a cleanup block, including after an error. It reports successful deletion or a cleanup warning, and requests a ten-minute inbox expiry when creating it. The download's README explains the files and failure handling.
Validate the business fact, not just the JSON
Schema validation answers questions such as "Is totalCents an integer?" Business validation asks whether that amount agrees with the invoice and the other extracted values.
In this example, validate.py checks the exact invoice and line-item fields, nonempty strings, a real date, USD currency and integer cents. It requires both equations to hold:
sum(lineTotalCents) = subtotalCents
subtotalCents + taxCents = totalCents
A mismatch exits with a nonzero status. The offline tests exercise missing required fields, unexpected fields, invalid dates, wrong types or currency, incorrect totals and duplicate invoices. These checks catch malformed or inconsistent output; they do not establish supplier identity or invoice authenticity.
For a production invoice workflow, also check:
- monetary values reconcile under the currency and rounding rules your application uses;
- the currency is allowed for the supplier and destination account;
- the supplier and invoice number form a stable duplicate key;
- any required purchase order is present and valid;
- a sudden bank-detail change is held for independent review;
- dates are plausible and normalized without discarding the source value; and
- line-item totals reconcile with the subtotal before tax, discounts or shipping adjustments.
For support email labeling, the checks are different. You may require an account or order ID before routing a billing request, allow a missing ID for a general question, and send uncertain intent or priority to a person.
The parser should be allowed to say, in effect, "I do not have enough evidence." A review queue is healthier than a confident guess with excellent JSON formatting.
Test real variations before switching on automation
One tidy example proves only that one tidy example worked. Build a small fixture set from the variations the workflow will actually receive:
- a normal message with all required fields;
- a forwarded or replied-to message with extra thread text;
- a message with a renamed or missing attachment;
- a scan with imperfect OCR;
- a document with two plausible totals or dates;
- a duplicate message or retried event;
- a sender-template change; and
- a document that belongs to a different message class.
Start by removing a required field or changing totalCents in a copy of result.json, then confirm that validation rejects it. Then add representative source emails and compare fresh extractions with the facts in each source. Passing the clean invoice above does not establish accuracy for another supplier, a scan or an ambiguous document.
Keep the examples that reveal a mistake. They become regression fixtures for the next prompt or schema version. Otherwise, fixing one troublesome supplier can quietly break three that were already working.
A trust checklist for every parsed record
Before a record leaves the parsing workflow, make sure you can answer these questions:
| Question | Evidence to store | Why it matters |
|---|---|---|
| Which message produced this? | Source email ID and received time | Opens the original evidence quickly |
| Which file was read? | Attachment ID, filename, and content type | Separates attachment errors from message errors |
| Which parser rules applied? | Transformer ID and schema version | Makes changes and regressions traceable |
| Did the output match the contract? | Schema validation result | Stops malformed records at the boundary |
| Did the business values agree? | Totals, duplicate, and policy checks | Catches correct-looking but unusable data |
| Why was it reviewed? | Missing field or review reason | Gives a person a useful starting point |
| Where was it delivered? | Destination ID and response | Distinguishes extraction success from delivery success |
| Can it be retried safely? | Idempotency key and step state | Prevents duplicate invoices, tickets, or rows |
Keep these details beside the accepted record or its review entry so a failed extraction or delivery can be investigated without losing the source.
Deliver the result without creating duplicates
The sample's accept function validates the invoice and inserts it into SQLite with a unique supplier-and-invoice-number key. It normalizes superficial case and spacing, so a replay with CEDAR PAPER CO. still conflicts with the first record. That is an application-owned duplicate rule, separate from any webhook delivery identifier.
For production, use durable storage and a supplier identity rule appropriate to your records. Commit the duplicate key and business write atomically. The in-memory example resets on every run and does not demonstrate delivery to an accounting system.
MailSlurp can store transform results and emit a NEW_AI_TRANSFORM_RESULT webhook. The event includes an idempotent messageId, the aiTransformResultId, the transformer ID, and a source entity ID when available.
Record the event before changing another system. If the destination is temporarily unavailable, retry the delivery from the stored result rather than paying for another extraction and risking a slightly different answer.
Common destinations include:
- an application API or queue for transactional processing;
- a database or warehouse for normalized records;
- an accounting or ticketing system after validation;
- CSV, Excel, or another export for analyst review; and
- Google Sheets for a shared operational queue.
For a shared spreadsheet queue, use an application-owned writer that receives the webhook, validates the result and handles row matching and retries. The email parser Google Sheets guide explains that approach.
Three useful applications
Invoice and receipt processing
Receive invoices in a dedicated address or connected account, read PDF and image attachments, extract supplier and accounting fields, validate totals and duplicates, then route uncertain documents to review. The invoice OCR workflow covers the finance controls in more detail.
Logistics and delivery documents
Convert shipment notices, order confirmations, proof-of-delivery documents, and exception messages into order references, addresses, dates, line items, and status fields. Keep the original email and file attached to the operational record so a coordinator can verify an unusual result.
Support and claims routing
Classify intent and urgency, extract customer or case identifiers, retain attachments, and choose the correct queue. A parser can prepare the ticket, but high-impact actions such as refunds, account changes, or claim approval should still follow explicit business controls.
How to evaluate an AI email parser
Use your own representative messages rather than a polished vendor sample. A useful evaluation asks:
- Can it receive the message sources you actually use?
- Does it retain headers, body variants, attachments, and source identifiers?
- Can it read both text documents and scans that need OCR?
- Can you define and version a strict output schema?
- Can you inspect the source beside the result?
- Can invalid or uncertain records enter review without being lost?
- Can delivery be retried without rerunning extraction?
- Can your application prevent a repeated event from creating a duplicate?
Run the same fixture set through every option. Accuracy matters, but so do recovery, auditability, and the amount of glue code required between mailbox intake and the final destination.
FAQ
What is an AI email parser?
An AI email parser receives an email and its attachments, identifies the useful information, and returns it as structured fields. It is especially useful when message wording or document layouts vary too much for fixed rules.
Does an AI email parser need OCR?
It needs OCR when the useful text is contained in a scan or image. A born-digital PDF may already contain extractable text. OCR recovers text; the parser still needs instructions, a schema, and validation to turn that text into a dependable record.
Can an AI email parser convert email to JSON?
Yes. Define the expected field names and types in a JSON schema, then validate the result before using it. The schema controls structure, while separate business checks confirm totals, identifiers, dates, and other facts that must be correct.
Can it parse PDF invoices from Gmail or Outlook?
Yes. MailSlurp supports purpose-built receiving inboxes, forwarding, and connected Gmail or Outlook sources. The workflow can read the email and attachment, extract invoice fields, and pass the result to review or a downstream system.
Is AI better than a rule-based email parser?
Not always. Rules are usually better for a stable template with exact markers. AI is more useful for varied language, layouts, and attachments. A hybrid design often works best: deterministic rules select and validate the message, while AI interprets its less predictable content.
How should failed extraction be retried?
Keep extraction and destination delivery as separate steps. If the stored extraction is valid but a webhook, sheet, or database write fails, retry only that delivery step. Re-run extraction when the source or extraction configuration actually needs to change.
Final take
When adapting the invoice example, change the source fixture, extraction instructions, schema and validator together. Keep a known result for each fixture so a prompt change can be checked against the invoices your application actually handles.