How to Automate Invoice Processing From Email With AI (Step by Step)
Twinkal Patel
Co-founder·12 min read
On this page

Stop digging through inboxes for invoices. Give invoices one email address, then let AI read each PDF and pull out the vendor, amount and due date into your spreadsheet or accounting tool. Plain-English guide with the code a developer needs.
To automate invoice processing from email, send every invoice to one dedicated address, such as invoices@yourdomain.com. Then have a small program read each new email, pass the PDF to an AI model, and save the vendor, amount and due date to your spreadsheet or accounting tool. Reloop handles the inbox part: it receives the email, keeps the original with its attachments, and notifies your program the moment an invoice arrives. The AI model does the reading.
The first half of this guide needs no technical skills at all and already fixes the most common problem: invoices scattered across everyone's inbox. The second half is for whoever builds the automation, explained so that anyone can follow what is happening.
Sound familiar?
If you pay bills for a business, you probably know at least one of these:
- It's the end of the month and you're searching three inboxes for "invoice", "receipt" and "bill", hoping you didn't miss one.
- A supplier sent the invoice to someone who was on holiday, and you only found out when the payment reminder arrived.
- You type the same five details (vendor, invoice number, date, amount, due date) from every PDF into a spreadsheet or Xero/QuickBooks, by hand.
- One typo turns $1,250.00 into $125.00, and nobody notices until the accounts don't add up.
- A late fee appears because a due date was buried in an attachment nobody opened.
- Your accountant keeps asking for receipts you're sure you received somewhere.
None of these is really a "data entry" problem. The underlying issue is that invoices arrive in too many places and are read too late. So the fix comes in two parts: one place to collect them, then automatic reading.
How it works, in plain English
1Supplier emails an invoice2 ↓3invoices@yourdomain.com ← one address for every invoice (Reloop)4 ↓5"New invoice arrived!" ← Reloop instantly notifies your program6 ↓7AI reads the PDF ← pulls out vendor, amount, due date…8 ↓9Saved to your spreadsheet, ← and anything unclear is flagged10accounting tool or database for a person to checkBeing clear about who does what:
Part 1: One inbox for every invoice (no code)
This part takes about fifteen minutes and is worth doing even if you never automate anything else.
Step 1: Create the address
Follow our step-by-step guide to receiving email on your own domain. In short:
- Add a domain in the Reloop dashboard. If your main domain already uses Gmail or Outlook, use a subdomain such as
billing.yourdomain.comso your existing email is untouched. - Add the one MX record Reloop shows you at your DNS provider.
- Create a mailbox, for example
invoices@billing.yourdomain.com.
The free plan includes 3 inboxes, so this costs nothing to try.
Step 2: Get invoices sent there
- Tell your suppliers. Send them the new address and ask them to update their billing contact. Most billing systems (Stripe, Shopify, AWS, Google, etc.) let you set a separate billing email in account settings.
- Forward what still lands elsewhere. In Gmail, create a filter (for example, emails with "invoice" in the subject and an attachment) that forwards to the new address. Gmail first sends a confirmation code to the new address; you'll see it in the Reloop inbox.
Step 3: Read it like a normal inbox
Add the mailbox to Apple Mail, Outlook or Thunderbird over IMAP (server imap.reloop.sh, port 993), with a Reloop API key as the password. Invoices and their PDFs show up like any other email. Your whole finance team can watch the same inbox.
Already better: every invoice is in one place, nothing depends on one person's inbox, and month-end means opening one folder.
Part 2: Let AI read the invoices (for whoever builds it)
This part needs someone comfortable running a small Node.js script: a developer, a technical co-founder, or a freelancer. You can hand them this page. Each step starts with what it does in plain English.
What you need
- The invoice mailbox from Part 1
- A Reloop API key and a webhook (set up in the dashboard)
- An API key for an AI model. This example uses Claude, which reads PDFs directly.
- Somewhere to run the code: any server or serverless function that can receive a web request
npm install reloop-email @anthropic-ai/sdk mailparser zodStep 1: Get notified when an invoice arrives
In plain English: instead of checking the inbox every few minutes, Reloop calls your program the moment an email arrives.
In the dashboard, create a webhook that subscribes to the email.received event and points to your program's URL. Each notification looks like this:
1{2 "type": "email.received",3 "data": {4 "email_id": "in_123456789",5 "mailbox_id": "mb_123456789",6 "from": "billing@supplier.com",7 "to": ["invoices@billing.yourdomain.com"],8 "subject": "Invoice INV-2041 from Supplier Ltd",9 "has_attachments": true,10 "is_spam": false11 }12}The notification tells you that an invoice arrived, not what is in it. Your program fetches the email itself in the next step.
Step 2: Get the PDF out of the email
In plain English: Reloop keeps an exact copy of every email exactly as it was received, attachments included. Your program downloads that copy and unpacks the PDF from it.
1import { simpleParser } from "mailparser";2import { reloop } from "./lib/reloop";3
4async function getInvoiceFiles(emailId: string) {5 const { message, messageError } = await reloop.inbox.messages.getRaw(emailId);6 if (messageError) throw messageError;7
8 const email = await simpleParser(message.raw);9 const pdfs = email.attachments.filter((a) => a.contentType === "application/pdf");10
11 return { email, pdfs };12}reloop.inbox.messages.getRaw returns the full original email. The open-source mailparser library turns it into a subject, a body and a list of attachments, each with its file contents.
Some invoices are not PDFs at all: many SaaS receipts are just the text of the email. The next step handles both.
Step 3: Ask the AI to read it
In plain English: you send the PDF to the AI with a short form to fill in (vendor, amount, due date…). It sends the form back completed. If something isn't on the invoice, it leaves that field empty instead of guessing.
1import Anthropic from "@anthropic-ai/sdk";2import { z } from "zod";3import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";4
5const anthropic = new Anthropic();6
7const InvoiceSchema = z.object({8 is_invoice: z.boolean(),9 vendor_name: z.string().nullable(),10 invoice_number: z.string().nullable(),11 invoice_date: z.string().nullable(), // YYYY-MM-DD12 due_date: z.string().nullable(), // YYYY-MM-DD13 currency: z.string().nullable(), // e.g. USD, EUR14 subtotal: z.number().nullable(),15 tax: z.number().nullable(),16 total: z.number().nullable(),17});18
19type Invoice = z.infer<typeof InvoiceSchema>;20
21async function readInvoice(pdf: Buffer | null, emailText: string): Promise<Invoice | null> {22 const content: Anthropic.ContentBlockParam[] = [];23 if (pdf) {24 content.push({25 type: "document",26 source: { type: "base64", media_type: "application/pdf", data: pdf.toString("base64") },27 });28 }29 content.push({30 type: "text",31 text:32 "Extract the invoice details. Use null for anything not clearly stated; never guess. " +33 "Set is_invoice to false if this is not an invoice or receipt.\n\n" +34 `Email text:\n${emailText}`,35 });36
37 const response = await anthropic.messages.parse({38 model: "claude-opus-5-5",39 max_tokens: 16000,40 messages: [{ role: "user", content }],41 output_config: { format: zodOutputFormat(InvoiceSchema) },42 });43
44 if (response.stop_reason === "refusal") return null; // send to manual review45 return response.parsed_output;46}Two details matter here:
- "Use null, never guess." A blank field is easy to spot and fill in. A confidently wrong amount isn't.
is_invoice. Newsletters, "your invoice is ready" notifications without the actual invoice, and marketing emails will reach the address too. This lets your program skip them.
Step 4: Check it, then save it
In plain English: the program runs a few common-sense checks. Anything that passes goes into your spreadsheet. Anything that looks off is marked "needs review" for a person.
1function needsReview(inv: Invoice): string[] {2 const problems: string[] = [];3 if (!inv.vendor_name) problems.push("missing vendor");4 if (inv.total === null) problems.push("missing total");5 if (!inv.due_date) problems.push("missing due date");6 if (inv.subtotal !== null && inv.tax !== null && inv.total !== null &&7 Math.abs(inv.subtotal + inv.tax - inv.total) > 0.01) {8 problems.push("subtotal + tax doesn't equal total");9 }10 return problems;11}Then save it wherever your team already works: a row in Google Sheets, a draft bill in your accounting software through its API, or a table in your own database. Always store the email_id with the row so anyone can open the original email in one click.
Step 5: Put it together
1import { verify } from "./lib/verify-webhook"; // signature check2
3export async function POST(req: Request): Promise<Response> {4 const raw = await req.text();5 if (!verify(raw, req.headers.get("Reloop-Signature") ?? "", process.env.RELOOP_WEBHOOK_SECRET!)) {6 return new Response("Bad signature", { status: 401 });7 }8
9 const event = JSON.parse(raw);10 if (event.type !== "email.received" || event.data.is_spam) {11 return new Response("skipped");12 }13
14 // Reply straight away, do the slow work in the background15 await queue.add("process-invoice", { emailId: event.data.email_id });16 return new Response("ok");17}18
19async function processInvoice(emailId: string) {20 if (await alreadyProcessed(emailId)) return; // the same notification can arrive twice21
22 const { email, pdfs } = await getInvoiceFiles(emailId);23 const files = pdfs.length > 0 ? pdfs.map((p) => p.content) : [null];24
25 for (const file of files) {26 const invoice = await readInvoice(file, email.text ?? "");27 if (!invoice) {28 await saveForReview(emailId, ["AI could not read this one"]);29 } else if (invoice.is_invoice) {30 await saveInvoice(emailId, invoice, needsReview(invoice));31 }32 }33}The signature check (verify) is the same function shown in our receiving email guide. It proves the request really came from Reloop and not from someone pretending.
Mistakes that cause real problems
Most of these come from treating the AI as if it can't be wrong.
ok immediately and process in a background jobemail_id you've already processed, and flag repeated vendor + invoice number pairsnull when unsure and send those to reviewemail_id with every row; the original stays in the mailboxIs it worth it for you?
Probably yes if you receive more than a handful of invoices a month, several people currently receive them, or you've paid a late fee or lost a receipt in the last year. Part 1 alone is worth doing at any size.
Probably not yet if you get three invoices a month from the same suppliers. A shared inbox (Part 1) is enough; the automation would take longer to build than it saves.
Something to be aware of: the AI model is billed separately by its provider, per invoice it reads. Check their pricing against your monthly invoice volume before you switch it on for everything.
FAQ
Not for Part 1. Creating the invoice inbox, pointing suppliers at it and reading it in Outlook or Apple Mail needs no code. Automatic reading of the invoices (Part 2) needs a short program, so you'll need a developer or a technical teammate for that part.
No. Reloop receives the emails, keeps the originals with their attachments, and notifies your program when one arrives. An AI model that you connect, such as Claude, reads the invoice. Your program decides where the details are saved.
Yes. When there's no PDF attached, the example in Step 5 sends the email's text to the AI instead. Many SaaS receipts work this way.
Your program can, because both have APIs for creating draft bills. Reloop doesn't have a built-in Xero or QuickBooks connection. A common approach is to create the bill as a draft so someone approves it inside the accounting tool.
Invoices contain business and sometimes personal data, so check the AI provider's data and retention terms and your own obligations (for example, GDPR) before you start. Keep the API keys for the mailbox restricted to that one invoice address.
Automation doesn't remove that risk, and it can make it easier to miss if payments happen without review. Keep a person approving payments, only trust known vendors automatically, and always confirm changed bank details by phone with a number you already have.
Ship your first email with Reloop
in minutes.
Open-source, deliverability-focused, and yours to self-host or run on Reloop Cloud. No lock-in, no rewrite later.


