How to Use Gemini to Process Invoices Directly from Gmail
Step-by-step guide to using Gemini in Gmail to process invoices, extraction prompts, validation, exception flagging, and a light Google Apps Script workflow to automate the whole thing.
Key Takeaway
Most AP invoices land in an inbox, not in an ERP upload portal. This guide shows you how to use Gemini in Gmail to extract, validate, cross-reference, exception-flag, and respond to invoices without leaving the email thread, plus a light Google Apps Script that logs every invoice email to a tracker sheet automatically. Together with Post 1, it closes the loop from inbox to monthly CFO summary, entirely inside Google Workspace.
If you read Post 1 of this series
You know how to use Gemini in Google Sheets to analyse your AP spend data. That post starts after the invoice has already landed somewhere, in your ERP, in an export, in a spreadsheet.
This post starts earlier. At the inbox.
Most AP invoices don't arrive via your ERP's upload portal. They arrive as email attachments: PDFs, scanned images, the occasional Word document. Someone on your AP team opens the email, downloads the attachment, reads the invoice, keys the data somewhere, and the process begins. That opening sequence, open, download, read, key, is where a surprising amount of AP time disappears.
Why Gemini in Gmail changes the maths
Gemini in Gmail can read an invoice attachment directly from the email thread, extract the structured data you need, validate it, flag exceptions, and draft a response, all without leaving Gmail. If you're already using Gemini in Google Sheets for spend analysis, adding this step upstream creates a connected Google Workspace AP workflow that covers the invoice from the moment it arrives to the moment it's analysed. This is Post 2 of the Gemini for AP Teams series. We'll cover exactly how to use Gemini in Gmail for invoice processing, the prompts for each step, how to connect the output to your Google Sheets workflow from Post 1, and, for the technically inclined, a light Google Apps Script section that automates the whole sequence.
What Gemini can do in Gmail
Gemini in Gmail is a different capability from Gemini in Google Sheets. It's worth being precise about what it can and can't do before building a workflow around it.
What Gemini in Gmail can do
- Read and summarise email threads and attachments
- Extract structured data from invoice PDFs and images attached to emails
- Draft reply emails based on the content of the thread and your instructions
- Identify key information (amounts, dates, vendor names) from invoice attachments
- Flag anomalies or missing information in an invoice before you action it
- Summarise a long email thread, useful when an invoice has a dispute history
What Gemini in Gmail cannot do natively
- Write extracted data directly to a Google Sheet without an additional step or Apps Script
- Automatically process every invoice that arrives without you opening the email first
- Post to your ERP directly
- Remember previous invoices from the same vendor without context you provide
- Access your vendor master or contract library unless you paste the relevant details in
What the workflow is designed around
The workflow in this post is designed around what Gemini can actually do, not what a fully automated system would do. You'll still open the email. Gemini handles everything after that.
What you need before you start
Google Workspace plan with Gemini: same requirement as Post 1, Business Standard, Business Plus, or Enterprise. Gemini needs to be enabled for your account by your Google Workspace admin. If you can see the Gemini icon in Gmail's toolbar, you're set.
How to access Gemini in Gmail
Open any email in Gmail. Look for the Gemini icon, a star or sparkle symbol, in the top right of the email thread. Clicking it opens the Gemini side panel where you can ask questions about the email or its attachments. Alternatively, use the Summarise this email shortcut that appears at the top of longer threads.
Your invoice emails
This workflow works best when vendor invoices arrive as PDF attachments to emails. Inline invoice images work with reduced accuracy. For invoices that arrive as links to a vendor portal, Gemini cannot follow the link, you'll need to download the PDF first.
Step 1: Extract invoice data from the attachment
Open the email containing the invoice. Open the Gemini side panel. Paste this prompt.
PROMPT 1: Invoice Extraction
Read the invoice attachment in this email and extract all data fields. Return the following as structured data: INVOICE HEADER: - Vendor name - Vendor address - Invoice number - Invoice date (DD/MM/YYYY) - Due date (DD/MM/YYYY) - Payment terms - PO number (null if not present) - Currency - Vendor email or contact (from the email sender if not on the invoice) LINE ITEMS: For each line item on the invoice return: - Line number - Description (exact text from invoice) - Quantity (null if not stated) - Unit (null if not stated) - Unit price (null if not stated) - Line total INVOICE TOTALS: - Subtotal - Tax amount (null if not stated) - Tax rate % (null if not stated) - Any additional charges (shipping, handling: null if none) - Total amount due Return null for any field that cannot be determined from the invoice. Do not guess. Flag any fields marked null that would typically appear on a standard commercial invoice as MISSING: [field name].
What to do with the output
Copy the extracted data into your AP tracking sheet in Google Sheets, the same sheet you're using for the spend analysis workflow from Post 1. This is the manual step that the Apps Script section later in this post automates.
Step 2: Validate the invoice
Run this prompt immediately after extraction, in the same Gemini side panel session. Gemini retains the context of the invoice it just read.
PROMPT 2: Invoice Validation
Now validate the invoice data you just extracted. Check the following: ARITHMETIC VALIDATION: 1. Do all line totals equal quantity × unit price for each line item? Flag any lines where this does not hold. 2. Does the sum of all line totals equal the subtotal? 3. Does subtotal + tax amount equal the total amount due? COMPLETENESS VALIDATION: 4. Are any of these critical fields missing: - Invoice number - Vendor name - Total amount due - Due date If yes, flag each as CRITICAL MISSING FIELD. CONSISTENCY VALIDATION: 5. Is the invoice date before the due date? Flag if not. 6. Is the due date in the future? Flag if it is already past due. 7. Does the currency appear consistent throughout the invoice? Return a validation report: - arithmetic_status: PASS or FAIL - completeness_status: COMPLETE or INCOMPLETE - consistency_status: PASS or FAIL - overall_status: APPROVED FOR PROCESSING, REVIEW REQUIRED, or HOLD - CRITICAL ISSUE - issues_found: bulleted list of all flags (empty if none)
Three possible outcomes
- APPROVED FOR PROCESSING: invoice is clean, move straight to logging it in your AP sheet and routing for approval.
- REVIEW REQUIRED: something needs checking before this invoice moves forward, missing due date, a line total that doesn't add up, a currency inconsistency. Review it manually before actioning.
- HOLD - CRITICAL ISSUE: invoice number missing, total amount blank, arithmetic that doesn't reconcile. Hold the invoice and contact the vendor before doing anything else.
Step 3: Cross-reference against your PO or contract
This is the step most AP workflows skip, and the one that catches the most expensive errors. If the invoice references a PO or a contract, paste the relevant details here and ask Gemini to compare. (If you want this enforced automatically across every contract, that's the contract intelligence layer.)
PROMPT 3: PO / Contract Cross-Reference
Compare this invoice against the purchase order or contract details below. [PASTE YOUR PO OR CONTRACT DETAILS HERE: vendor name, PO number, agreed line items and prices, payment terms, contract rate caps, delivery address, any special terms] Check the following: 1. Does the vendor name on the invoice match the vendor in the PO/contract? 2. Does the PO number on the invoice match the PO reference provided? 3. Do the line item descriptions match the scope in the PO/contract? 4. Are the unit prices equal to or below the agreed rates? Flag any line where the invoice price exceeds the agreed rate. 5. Does the total invoice value match the PO value or fall within the contracted scope? 6. Are the payment terms on the invoice consistent with the agreed terms? For each check return: - check_name - result: MATCH, DISCREPANCY, or CANNOT VERIFY - detail: one sentence explaining the finding - action_required: YES or NO Return an overall match status: FULLY MATCHED, MINOR DISCREPANCIES - REVIEW, or SIGNIFICANT DISCREPANCY - HOLD.
When to use this prompt
Use it for every invoice above your review threshold. For low-value, repeat invoices from trusted vendors, you may skip them. For any invoice above $5,000, for new vendors, or for invoices referencing a specific SOW or contract, run it every time. The five minutes it takes to paste the PO details and run the prompt has caught billing errors worth multiples of that time in recovery efforts.
Step 4: Flag exceptions before they reach AP
If the validation or cross-reference prompts flag anything, use this prompt to triage the exception before deciding what to do with it. Includes a duplicate flagging check on the invoice number pattern.
PROMPT 4: Exception Triage
Based on the invoice validation and cross-reference results above, assess this invoice for exceptions. Check for: 1. PRICE DISCREPANCY Is any line item priced above the agreed rate or above this vendor's typical billing range? 2. DUPLICATE RISK The invoice number is [INSERT NUMBER]. Does this number follow a pattern that suggests resubmission (e.g. suffix -R, -2, -REVISED)? 3. MISSING PO REFERENCE Is the PO number missing on an invoice where one would be expected? 4. PAYMENT DETAIL CHANGE Does the email contain any mention of a change to bank account details, payment method, or remittance address? If yes, flag as HIGH RISK: this is a common fraud vector. 5. UNUSUAL TIMING Is this invoice arriving significantly earlier or later than expected based on the invoice date and typical vendor billing cycle? For each exception found return: - exception_type - severity: HIGH / MEDIUM / LOW - detail: one sentence - recommended_action: one sentence If no exceptions are found, return: NO EXCEPTIONS IDENTIFIED - APPROVED FOR PROCESSING.
Pay particular attention to Exception 4
A vendor email that mentions a bank account change, especially one that arrives separately from the invoice itself, or from a slightly different email address, is one of the most common business email compromise fraud patterns. Do not action a bank account change from an email alone. Always verify by calling the vendor on a number from your vendor master, not from the email.
Step 5: Draft the vendor response
Once you've processed the invoice, you'll often need to send a response, confirming receipt, flagging a discrepancy, or requesting missing information. Use one of these three prompts depending on the outcome.
Prompt 5a: Acknowledgement of receipt (clean invoice)
PROMPT 5A: Acknowledgement Email
Draft a brief, professional email acknowledging receipt of this invoice. Include: - Confirmation that invoice [number] for [amount] has been received - Confirmation of the payment due date - A request to reference the invoice number on all payment correspondence - Your AP contact details for any queries Tone: professional, warm, brief. Under 80 words in the body. Use the vendor's name from the invoice. Sign off from the AP team.
Prompt 5b: Discrepancy email
PROMPT 5B: Discrepancy Email
Draft a professional email to the vendor flagging a discrepancy on this invoice. The discrepancy is: [DESCRIBE THE ISSUE, e.g. line item 3 is billed at $175/hr against a contracted rate of $150/hr, resulting in an overcharge of $87.50] The email should: - Reference the invoice number and date clearly - Describe the discrepancy in one sentence, factually, without accusation - State that payment is on hold pending resolution - Request either a corrected invoice or written confirmation of the agreed rate - Give a response deadline of 5 business days - Provide your AP contact for follow-up Tone: professional, factual, not adversarial. Under 120 words.
Prompt 5c: Missing information request
PROMPT 5C: Missing Information Email
Draft an email to the vendor requesting missing information on this invoice. Missing fields: [LIST THE MISSING FIELDS, e.g. PO number, due date, tax breakdown] The email should: - Reference the invoice number - List the missing information clearly - Explain that the invoice cannot be processed without these details - Request a corrected invoice or the missing information in writing within 3 business days - Keep a professional, helpful tone, assume vendor oversight, not bad intent Under 100 words.
Connecting this to your Google Sheets workflow
At the end of each invoice processed through Gmail, you have structured extracted data in the Gemini side panel. To connect it to the Google Sheets spend analysis workflow from Post 1, you need to get that data into your AP tracking sheet.
Three ways to do it
- The manual approach: copy the extracted data from the Gemini panel and paste it into your Google Sheet. Tedious for high volumes, but workable for teams processing fewer than 50 invoices a month.
- The semi-automated approach: keep a Google Form open alongside Gmail. After each invoice, enter the key fields into the form, vendor name, invoice number, amount, due date, status. Form responses feed directly into a Google Sheet that your Gemini spend analysis prompts can then run on.
- The automated approach: Google Apps Script. See the next section.
Advanced: automating this with Google Apps Script
This section is for finance ops leads or IT administrators who want to build the Gmail invoice workflow into an automated pipeline. If you're running this manually, skip ahead. Google Apps Script is Google's built-in automation language, it lives in Google Workspace and can connect Gmail, Google Sheets, and Google Drive without any external tools or API keys. The script below monitors a Gmail label for new invoice emails, extracts key data using Gemini, and writes the results to a Google Sheet automatically.
Step 1: set up your Gmail label
Create a Gmail label called AP-Invoices. Train your team, or set up a Gmail filter, to apply this label to every email containing an invoice. The script watches this label for unprocessed emails.
Step 2: create the Google Sheet
Create a new Google Sheet called AP Invoice Tracker with these column headers in Row 1: Timestamp | Email Subject | Sender | Vendor Name | Invoice Number | Invoice Date | Due Date | Amount | Currency | PO Number | Payment Terms | Status | Notes.
Step 3: the Apps Script
In Google Sheets, go to Extensions → Apps Script. Paste this script:
function processInvoiceEmails() {
// Configuration
const LABEL_NAME = 'AP-Invoices';
const SHEET_NAME = 'AP Invoice Tracker';
const PROCESSED_LABEL = 'AP-Invoices/Processed';
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName(SHEET_NAME);
// Get unprocessed emails from the AP-Invoices label
const label = GmailApp.getUserLabelByName(LABEL_NAME);
if (!label) {
Logger.log('Label not found: ' + LABEL_NAME);
return;
}
const threads = label.getThreads(0, 20); // Process up to 20 at a time
threads.forEach(thread => {
const messages = thread.getMessages();
const latestMessage = messages[messages.length - 1];
// Get email metadata
const subject = latestMessage.getSubject();
const sender = latestMessage.getFrom();
const timestamp = latestMessage.getDate();
// Get attachments
const attachments = latestMessage.getAttachments();
const hasPDF = attachments.some(att =>
att.getContentType() === 'application/pdf'
);
if (!hasPDF) {
// Log emails without PDF attachments for manual review
sheet.appendRow([
timestamp, subject, sender,
'NO PDF ATTACHMENT', '', '', '',
'', '', '', '', 'MANUAL REVIEW',
'No PDF attachment found'
]);
} else {
// Log the email for manual Gemini processing
// with all available metadata
sheet.appendRow([
timestamp, subject, sender,
'PENDING GEMINI EXTRACTION',
'', '', '', '', '', '', '',
'PENDING',
'PDF found: run Gemini extraction'
]);
}
// Move to processed label to avoid reprocessing
try {
let processedLabel = GmailApp.getUserLabelByName(
PROCESSED_LABEL
);
if (!processedLabel) {
processedLabel = GmailApp.createLabel(
PROCESSED_LABEL
);
}
thread.addLabel(processedLabel);
thread.removeLabel(label);
} catch(e) {
Logger.log('Label error: ' + e.toString());
}
});
Logger.log('Processed ' + threads.length + ' email threads');
}
// Set up a time-based trigger to run every hour
function createTrigger() {
ScriptApp.newTrigger('processInvoiceEmails')
.timeBased()
.everyHours(1)
.create();
}Step 4: run it
Save the script. Click Run → createTrigger once to set up the hourly automation. After that, the script runs every hour, scans the AP-Invoices label for new emails, logs them to your tracker sheet, and moves them to the Processed sublabel.
What this gives you
Every invoice email is automatically logged to your Google Sheet within an hour of arrival, with the email subject, sender, timestamp, and a status of PENDING GEMINI EXTRACTION. Your AP team then opens each logged invoice from the sheet, goes to the Gmail thread, runs the Gemini extraction prompts from Steps 1 to 4, and updates the row with the extracted data. This is a semi-automated workflow: the logging is automatic, the Gemini extraction is still manual per invoice. It ensures nothing falls through the inbox cracks while keeping a human in the loop for the data extraction step.
A note on full automation
Full end-to-end automation, where Gemini reads the attachment, extracts the data, and writes it to the sheet without human intervention, is possible using the Gemini API with a Google Cloud Functions backend. That level of implementation is beyond this post, but if your team has an IT resource or a developer, the Apps Script above is the foundation to build on. The Gemini API documentation at ai.google.dev covers the document processing capabilities you'd need for the next step.
The full Gmail-to-Sheets invoice workflow, end to end
Here's the complete workflow so you can see how Posts 1 and 2 connect.
- Invoice arrives in Gmail.
- Gmail filter applies the AP-Invoices label automatically.
- Apps Script logs it to the AP Invoice Tracker sheet within the hour.
- AP team member opens the email thread.
- Runs Prompt 1 (extraction) in the Gemini side panel.
- Runs Prompt 2 (validation), gets APPROVED, REVIEW, or HOLD.
- If APPROVED: runs Prompt 5A (acknowledgement email), copies data to master AP sheet.
- If REVIEW: runs Prompt 3 (PO cross-reference) and Prompt 4 (exception triage).
- If HOLD: runs Prompt 5B or 5C (discrepancy or missing-info email), flags for follow-up.
- Extracted, validated data lands in Google Sheets.
- Monthly vendor drift detection and the rest of the Post 1 spend analysis prompts run on the accumulated data.
- CFO summary generated.
- Full AP visibility, from inbox to insight, in Google Workspace.
Where this workflow stops and Blackbee AI picks up
The Gmail-to-Sheets workflow in this post covers the invoice from arrival to analysis. What it can't cover is what happens before the invoice arrives, the spend intent, the purchase commitment, the contract validation, and the approval chain that should have governed whether this vendor invoice was expected in the first place. That's the upstream gap that causes most AP exceptions. Blackbee AI governs that upstream process, starting at spend intent, validating every commitment against your contracts, and ensuring that by the time an invoice arrives, the AP team already knows it's coming, who approved it, and what it should cost. If your team is ready to close that gap, see how the full Intake-to-Pay platform works.