Skill: jeane-li/invoice-extractor-from-mail (version 1.0.0)

--- name: invoice-extractor-from-mail description: Designed for AP finance teams in cross-border trade enterprises. Automatically fetches invoice attachments from email (IMAP/OAuth) or local files, batch-extracts key fields (invoice number, amount, currency, etc.) via ADP, and exports results to Excel or business systems — no manual data entry required. --- <div align="center"> <a id="Invoice extractor from mail skill"></a> # Invoice Extractor from Mail Skill </div> **Invoice Extractor from Mail Skill** is a dedicated invoice extraction skill officially built by Laiye Technology for finance teams in traditional manufacturing enterprises. Powered by Laiye ADP (Agentic Document Processing) core capabilities, it establishes an end-to-end automated document processing pipeline from email to business systems, compressing the previously tedious "find attachments -> manual data entry" workflow into a single automated execution: automatically retrieve attachments -> ADP intelligent extraction -> automatic field mapping -> one-click output to Excel / business systems, significantly improving cross-border procurement invoice processing efficiency and data accuracy. --- ## Use Cases - AP finance teams in traditional manufacturing enterprises can improve end-to-end processing efficiency for overseas invoice collection from email attachments, intelligent information extraction, and data entry during overseas procurement and cross-border settlement workflows. - Audit teams in cross-border trade enterprises can batch-extract key information from overseas invoices and uniformly archive them during audit and compliance review workflows, improving document organization efficiency and completeness. - Whether invoices are scattered across employee mailboxes or stored in local files, they can all be processed in batch with concurrency, dramatically improving email processing efficiency. --- ## 1. Core Design Principles **Guided decision tree, not an exhaustive matrix.** The Skill does not preset specific email types or business system platforms. Each step asks only one question, follows the corresponding branch based on the user's answer, and automatically skips unnecessary steps. This means: - New email types and new business system platforms do not require modifying the Skill; simply guide the user to provide the corresponding connection parameters during the conversation. - The configuration file structure uses a universal `type` + `params` pattern, without defining a dedicated schema for each vendor. --- ## 2. User Workflow ``` First-time use: invoice-extract init |-- Q1: Where do the files come from? | |-- "Email" -> Q2: Which email service? -> Collect connection parameters -> Q3: Filter criteria | +-- "Local" -> Skip email configuration |-- Q4: ADP Key (required for first use) |-- Q5: Do you need field mapping? -> Yes -> Guide configuration / No -> Use ADP raw fields +-- Q6: Where should results be output? |-- "Local Excel file" (default) |-- "Upload to cloud platform" -> Which platform? -> Guide connection parameter configuration +-- "Push to business system API" -> Guide endpoint, authentication, and field mapping configuration Daily use: invoice-extract run [--source mail|local] [--path ./invoices/] [--out ./result.xlsx] ``` --- ## 3. Skill Internal Processing Flow ``` +----------------------------------------------------------+ | Phase 1: Retrieve Files | | +-----------+ +----------------+ | | | Local | | Email | | | | Files | | Attachments | | | | Read | | Connect->Filter| | | | Directly | | ->Download | | | +-----+-----+ +-------+--------+ | | +--------+-----------+ | | v | | Phase 2: Unified Adaptation | | Select optimal method by source: file_url / file_path | | / base64 | | v | | Phase 3: ADP Extraction | | Auto-match invoice extraction app -> Call ADP API -> | | Receive structured JSON | | v | | Phase 4: Field Mapping (Optional) | | ADP raw fields -> Business field names | | v | | Phase 5: Output | | Local Excel file / Upload to user-specified business | | system | +----------------------------------------------------------+ ``` ### Detailed Description for Each Phase #### Phase 1: Retrieve Files **Branch A -- Local Files:** - Supports user uploading a single file or specifying a local folder - Supported formats: .jpeg, .jpg, .png, .bmp, .tiff, .pdf, .doc, .docx, .xls, .xlsx - Supported size: 50 MB (if file > 20 MB, the ADP async interface is recommended) - Folder mode automatically performs recursive scanning, filtering by file extension - Batch processing supports concurrency, with a default concurrency of 2 (ADP free users will automatically be limited to 1 concurrent process) **Branch B -- Email Attachments:** - Ask the user: "What email service do you use?" (no preset options; the user specifies) - Based on the user's answer, guide the collection of corresponding connection parameters: - Generic IMAP types (QQ / 163 / Gmail / Outlook / Feishu Mail / DingTalk Mail / Enterprise Mail / Exchange, etc.): User needs to provide: email address, authorization code, IMAP server address - API types (enterprise self-built mail open platforms / other systems providing Mail Open API): Corresponding app_id, app_secret, authentication method - Other unknown types: Ask the user what protocol the email service supports, and provide two guided paths: IMAP and API - Collect filter criteria: - Whether to filter unread emails only - Attachment type whitelist - Sender whitelist - Time range - Maximum number of messages to process #### Phase 2: Unified Adaptation ADP supports three file input methods. The Skill automatically selects the optimal method based on the source: | Source | Adaptation Method | Priority Notes | |---|---|---| | Local files | Pass `file_path` (local path) | Most direct, no conversion needed | | API-type attachments (providing a temporary download URL) | Pass `file_url` to ADP | No download needed, most efficient | | Agent scenarios (file already uploaded to server) | Pass `file_url` to ADP | Same as above | | IMAP-type attachments (binary stream download) | Download then pass `file_path`; if unable to write to disk, convert to `base64` | Prefer writing to disk and using path; fall back to base64 | #### Phase 3: ADP Extraction (via CLI) This Skill completes extraction through the ADP CLI tool (rather than calling the API directly). The CLI runs faster after installation and is simpler to integrate. **Prerequisites before first run:** 1. Install ADP CLI ```bash # Agent usage npx skills add laiye-ai/adp-cli -y -g # npm (recommended) npm install -g @laiye-adp/agentic-doc-parse-and-extract-cli # Linux / macOS curl -fsSL https://raw.githubusercontent.com/laiye-ai/adp-cli/main/scripts/adp-init.sh | bash # Windows (PowerShell) irm https://raw.githubusercontent.com/laiye-ai/adp-cli/main/scripts/adp-init.ps1 | iex ``` 2. Run `adp config get` to check credentials. If not configured, guide the user to execute `adp config set --api-key <KEY> --api-base-url <URL>` > a. The API key provided by the user can be saved as an environment variable to avoid repeated configuration each time ADP is called. <br> > b. The base URL can be auto-populated based on the user's region without requiring user input. ADP provides independent public cloud access URLs for domestic and overseas users. Accessing the nearest endpoint ensures the highest speed and stability. <br> > | Region | Login Address | API Base URL | > |-----|----------|--------------| > | Chinese Mainland | [https://adp.laiye.com/](https://adp.laiye.com/?utm_source=clawhub) | `https://adp.laiye.com/` | > | Overseas Region | [https://adp-global.laiye.com/](https://adp-global.laiye.com/?utm_source=clawhub) | `https://adp-global.laiye.com/` | 3. Run `adp app-id list` to get the invoice processing application ID. Subsequently, prefer using `adp app-id cache` > The `app id` should preferably be a preset invoice processing application. If the application list contains multiple invoice-processing-related applications, ask the user which one to use. > After querying the app id list, the ID list can be saved to cache for faster future queries. **Core Flow: Execute Extraction** ```bash # Single file extraction -- local file adp extract local <file_path> --app-id <app_id> # Single file extraction -- URL adp extract url <file_url> --app-id <app_id> # Single file extraction -- Base64 adp extract base64 <base64> --app-id <app_id> # Large file async extraction and result querying adp extract local <file_path> --app-id <app_id> --async adp extract query <task_id> # Batch extraction -- local folder (email attachments downloaded and placed in a folder) adp extract local <folder_path> --app-id <app_id> --export <output_folder> --concurrency 2 # Batch extraction -- URL list file (one URL per line) adp extract url <url_list_file> --app-id <app_id> --export <output_folder> --concurrency 2 ``` **Application Matching Logic:** - From `adp app-id list` / `adp app-id cache`, preferably select the preset invoice processing application. If the application list contains multiple invoice-processing-related applications, ask the user which one to use. - If the preset template does not meet the user's needs, a custom extraction template can be created using `adp custom-app create`. Custom templates can be reused. #### Phase 4: Field Mapping (Optional) - To ensure that data exported from ADP can be smoothly imported into business systems, users can manually adjust field name mappings. - If the user has configured mapping rules: Replace the ADP raw field name `field_name` with the mapped field name. - If not configured: Use the raw field names returned by ADP directly. - Mapping rules are grouped by document type and support post-run additions/modifications. #### Phase 5: Output **Mode A (Default) — Local Excel File:** - Generates `./out/invoices_YYYYMMDD_HHMM.xlsx` - One row per document - When outputting the Excel file, proactively ask the customer to verify the extraction results and whether they need to import the results into a business system **Mode B — Upload to Cloud Platform (file-based):** - Upload the generated Excel to cloud storage - Ask the user which platform they use - Based on the answer, guide the collection of corresponding authentication parameters and target location - Common scenario references (for guidance only, not hardcoded): - Feishu Docs: Requires app_id + folder_token - DingTalk: Requires access_token + space_id - OneDrive/SharePoint: Requires OAuth + drive_id - Google Sheets: Requires service account + spreadsheet_id - Others: Ask the user for the platform's API documentation or upload method **Mode C — Push to Business System API (structured data):** - Push ADP's structured JSON extraction results directly to the user's business system (ERP, finance system, etc.) via HTTP API - Guide the user to provide the following: 1. **API Endpoint**: The receiving interface URL of the business system (e.g., `https://erp.company.com/api/v1/invoices`) 2. **Authentication**: Bearer Token / API Key / OAuth 2.0 / Basic Auth 3. **Request Format**: POST body structure (JSON) and the field names expected by the business system 4. **Field Mapping**: Use `field_map.json` to map ADP's `field_key` to the target field names in the business system - Push flow: ``` ADP structured JSON → Field mapping (field_key → business system field name) → Assemble request body → POST to endpoint ``` - Common scenario references (for guidance only, not hardcoded): - SAP: Requires API endpoint + OAuth client credentials + field mapping - Kingdee/Yonyou: Requires API endpoint + App Key + App Secret + field mapping - Custom ERP: Requires user to provide API documentation; Skill guides configuration accordingly - After push completes, display the push status for each record (success/failure); failed records are written to `failed.log` --- ## 4. Configuration File Structure All configurations are stored in the `~/.invoice_extract/` directory, with `chmod 600` permissions, and must not be committed to version control. ### 4.1 Source Configuration `source.json` Universal structure: `type` + `params`, without defining a dedicated schema for each email platform. ```json { "type": "imap", "params": { "host": "imap.qq.com", "port": 993, "ssl": true, "username": "[REDACTED_SECRET]", "password": "your_authorization_code", "mailbox": "INBOX" } } ``` ```json { "type": "local", "params": { "path": "./invoices/" } } ``` ### 4.2 Filter Criteria `filter.json` (Email Mode Only) ```json { "unread_only": true, "with_attachment_only": true, "attachment_ext": ["pdf", "jpg", "jpeg", "png", "bmp", "tiff"], "sender_whitelist": [], "since": "2026-04-01", "until": "2026-04-30", "max_messages": 200 } ``` ### 4.3 ADP Credentials (Managed via CLI) ```bash # View current configuration adp config get # Set API Key adp config set --api-key <KEY> # Set API Base URL (Chinese Mainland: https://adp.laiye.com/ Overseas: https://adp-global.laiye.com/) adp config set --api-base-url <url> # Check balance adp credit ``` ### 4.4 Field Mapping `field_map.json` (Optional) > **Full field schema reference:** See [`refers/adp-invoice-fields.md`](refers/adp-invoice-fields.md) for the complete ADP field definition, JSON structure, and mapping rules. Mapping rules: The left-side key is the `field_key` from ADP output JSON (fixed identifier, cannot be modified). The right-side value is the user-defined display name (used as Excel column headers or business system target field names, freely modifiable by user). Example: ```json { "invoice/receipt": { "invoice_number": "Invoice Number", "invoice_date": "Invoice Date", "supplier_name": "Vendor", "total_amount": "Grand Total", "line_items_description": "Item Description", "line_items_total_amount": "Line Amount" } } ``` - If no mapping is configured, the Skill uses ADP's raw `field_name` as the display name - For API push mode (Mode C), the values become the field names in the POST request body ### 4.5 Output Configuration `output.json` ```json { "type": "excel", "params": { "dir": "./out/" } } ``` ```json { "type": "cloud", "platform": "feishu", "params": { "app_id": "cli_xxxxxxx", "app_secret": "xxxxxxxxxxxxxxxx", "folder_token": "xxxxxxxx" } } ``` ```json { "type": "api", "params": { "endpoint": "https://erp.company.com/api/v1/invoices", "method": "POST", "auth_type": "bearer", "auth_token": "your_token_here", "headers": { "Content-Type": "application/json" } } } ``` > **API mode notes:** > - `auth_type` supports: `bearer` (Bearer Token), `api_key` (in header or query), `oauth2` (Client Credentials), `basic` (username + password) > - When pushing, the Skill assembles ADP extraction results into a JSON body according to `field_map.json` mapping, then POSTs each record to the endpoint > - If the business system supports batch APIs, the user can configure `"batch": true` and the Skill will combine multiple records into an array for a single push > - Before pushing, a preview is displayed (request body of the first record) for user confirmation before batch execution --- ## 5. Command Reference ```bash # First-time configuration (guided wizard) invoice-extract init # Execute extraction (using saved configuration) invoice-extract run # Override source (extract from local files this time) invoice-extract run --source local --path ./invoices/ # Override time range invoice-extract run --since 2026-04-01 --until 2026-04-30 # Preview only (list files to be processed without actually extracting) invoice-extract dry-run # View/edit field mapping invoice-extract map --edit # Reconfigure a specific step invoice-extract init --only source invoice-extract init --only adp invoice-extract init --only output ``` --- ## 6. Excel Output Column Conventions - Use the `field_name` from the ADP output JSON results as columns, with one field name corresponding to one column name. - All results from one document are output as a single row. - The Excel sheet is named "adp extract result". --- ## 7. Error Handling | Scenario | Behavior | |---|---| | Email connection failure | Terminate immediately, prompt to check connection parameters | | Single file download/read failure | Skip, log to `failed.log`, continue processing the next file | | ADP CLI not installed | Automatically execute the installation script | | ADP credentials not configured / authentication failure | Terminate immediately, guide the user to execute `adp config set --api-key <KEY>` | | ADP extraction failure (corrupted file / blank page, etc.) | Do not retry, log to `failed.log` | | ADP async task timeout | Exponential backoff polling with `adp extract query <task_id>`, up to 3 retries | | Cloud platform upload failure | Excel is still retained locally, prompt the user to check platform configuration | | API push authentication failure (401/403) | Terminate immediately, prompt user to check if token/credentials have expired | | API push single record failure (4xx/5xx) | Skip the record, log to `failed.log`, continue pushing the next one; summarize failure count after completion | | API push endpoint unreachable | Terminate immediately, prompt user to check network and endpoint URL | --- ## 8. Security and Privacy - All credential files have `chmod 600` permissions and must not be committed to version control. - Email passwords/authorization codes are stored locally only and are not sent to ADP. - ADP will transmit files to its server for processing. For sensitive files, please confirm data compliance first. - Cache directory: `./.cache/invoice_extract/` --- ## 9. Limitations - Single file <= 50 MB (ADP limitation) - Recommended <= 100 files per batch; please process in batches if exceeded. - Encrypted emails (S/MIME) and password-protected PDFs are not supported. - Default concurrency is 2, but ADP free users only support a concurrency of 1. If the user is a free user, concurrency will be automatically reduced to 1. ## 10. Billing Rules - **New user benefit:** 100 free credits per month, with no restrictions on which applications can be used. - **Credit consumption rules:** | Processing Stage | Cost | |-----------------|------| | Document parsing | 0.5 credits/page | | Purchase order extraction | 1.5 credits/page | | Invoice/receipt extraction | 1.5 credits/page | | Custom extraction | 1 credit/page | > When credits are insufficient, you can log in to the ADP portal directly to top up. We provide independent public cloud access URLs for domestic and overseas users, which need to be configured separately by region. Accessing the nearest endpoint ensures the highest speed and stability.<br> > - Chinese Mainland users: [Login](https://adp.laiye.com/)<br> > - Non-Chinese Mainland users: [Login](https://adp-global.laiye.com/)<br> If you encounter any payment issues, please contact support: [REDACTED_SECRET] --- ## 11. Related Resources - **CLI Documentation**: [ADP CLI User Guide](https://laiye-tech.feishu.cn/wiki/YIaawiK2DimisZk5KfDc8a8cnLh) - **API Documentation**: [OpenAPI User Guide](https://laiye-tech.feishu.cn/wiki/S1t2wYR04ivndKkMDxxcp2SFnKd) - **User Guide**: [Public Cloud Operation Manual](https://laiye-tech.feishu.cn/wiki/OfexwgVUQiOpEek4kO7c7NEJnAe) - **Problem Feedback**: [REDACTED_SECRET] - **Official Website**: [Laiye Technology](https://laiye.com) --- Copyright (c) 2026 [Laiye Technology (Beijing) Co., Ltd.] All rights reserved.

path: license.md
content: Commercial License Agreement

Effective Date: [March 30, 2026]
Copyright © 2026 [Laiye Technology (Beijing) Co., Ltd.] All rights reserved.

This “Skill” (referring to the entirety including models, software, code, weights, documentation, data, and related derivative works, “the Product”) is developed and wholly owned by Laiye Technology (Beijing) Co., Ltd. (“Licensor”). The mentioned derivative works refer to new works created by modifying, integrating, fine-tuning, or further developing the Product. Subject to your (“Licensee” or “you”) compliance with the terms of this Agreement, the Licensor grants you a worldwide, royalty-free, non-exclusive license.

1. Licensing

1.1 Free Use and Distribution: The Licensor grants the Licensee a non-transferable, non-exclusive right to freely use, copy, publish, and distribute copies of the Product for non-commercial purposes. The aforementioned "non-commercial purposes" include, but are not limited to:
Personal learning, research, teaching, and evaluation.
Technical exchanges within academic institutions or open-source communities, non-profit projects.
Integration or demonstration in non-commercial products or services.
1.2 Commercial License:	Any activity intended to directly or indirectly obtain commercial benefits, revenue, or consideration (“Commercial Exploitation”) requires the explicit written authorization (i.e., a "Commercial License") from the Licensor. Commercial Exploitation includes, but is not limited to:
Distributing the Product or derivative works thereof in forms such as sales, resale, licensing fees, subscription fees, or other charges.
Providing the Product or derivative works thereof as a SaaS (Software as a Service) to third parties.
Integrating the Product or derivative works thereof, as a core function, into software, hardware, or services intended for sale or lease.
Any for-profit activity that utilizes the functionality or content of the Product to provide services to third parties.

2. Reserved Rights and Ownership

2.1	Ownership, intellectual property rights (including but not limited to copyright, patents, trademarks, trade secrets), and other related rights and interests in the Product (including all copies thereof) belong to the Licensor or its affiliates. This Agreement does not constitute any form of transfer of rights or sale of the Licensor's intellectual property.
2.2	The Licensee may non-commercially distribute unmodified copies of the Product through channels such as open-source platforms, or engage in non-commercial further development, and distribution, provided that this Agreement, the copyright notice, and the original identification are fully retained.
3. Distribution Conditions

When the Licensee distributes or provides the Product, all of the following conditions must be met:
Retention of Notices:	Prominently retain all copyright notices of the Product, the text of this License Agreement, and the disclaimer on distributed copies.
No Misrepresentation:	Should not imply that the Licensor endorses your distribution version.

4. Disclaimer of Warranties

THE PRODUCT IS PROVIDED "AS IS", WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO: THE LICENSOR DOES NOT WARRANT THAT THE PRODUCT IS FREE FROM ERRORS, BUGS, WILL OPERATE PROPERLY, OR IS SUITABLE FOR A PARTICULAR PURPOSE; THE LICENSOR DOES NOT WARRANT THAT USE OF THE PRODUCT WILL NOT INFRINGE UPON THIRD-PARTY RIGHTS; THE LICENSOR SHALL NOT BE LIABLE TO THE LICENSEE OR ANY THIRD PARTY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, OR PUNITIVE DAMAGES ARISING FROM THE USE OF THE PRODUCT.

5. Termination

5.1	This Agreement becomes effective from the Licensee's first use of the Product and continues until terminated.
5.2	If the Licensee violates the restrictions in Article 1 "License Grant" of this Agreement (e.g., unauthorized Commercial Exploitation), this Agreement will terminate automatically without prior notice.
5.3	Upon termination, the Licensee must immediately cease using the Product and destroy all copies of the Product in its possession.

6. Miscellaneous

6.1	The formation, execution, interpretation, and dispute resolution of this Agreement shall be governed by the laws of the People's Republic of China.
6.2	The Licensee shall not assign or transfer any of its rights or obligations under this Agreement without the Licensor's prior written consent.
6.3	This Agreement constitutes the entire agreement between the parties concerning this license matter and supersedes any prior oral or written communications and agreements between the parties regarding this matter.
6.4	Any dispute related to this Agreement shall be settled through friendly negotiation between the parties. If negotiation fails, either party has the right to submit the dispute to the competent court in the place where the Licensor is registered.

For obtaining a Commercial License or if you have any questions, please contact:
[[REDACTED_SECRET]]


The Product is licensed under the Commercial License Agreement.  For commercial use, please contact us to obtain authorization.

path: README.md
content: <div align="center">

# 📨 Invoice Extractor from Mail

**Intelligent Invoice Extraction Skill for Email**

Built for AP finance teams in overseas procurement and cross-border trade enterprises

`Auto-fetch email attachments` → `ADP intelligent extraction` → `One-click output to Excel / business systems`

</div>

---

## 📖 Product Overview

**Invoice Extractor from Mail** is a dedicated invoice extraction skill officially built by Laiye Technology for finance teams in traditional manufacturing enterprises. Powered by [ADP (Agentic Document Processing)](https://adp-global.laiye.com/?utm_source=github) core capabilities, it establishes an end-to-end automated document processing pipeline from email to business systems, compressing the previously tedious "find attachments → manual data entry" workflow into a single automated execution: auto-fetch attachments → ADP intelligent extraction → one-click output to Excel / business systems, significantly improving cross-border procurement invoice processing efficiency and data accuracy.

It supports integration with mainstream domestic and international email services via IMAP/OAuth secure access, automatically capturing invoice attachments from emails and batch-extracting key information from multilingual invoices worldwide (invoice number, amount, currency, etc.). If invoices are stored locally, they can also be uploaded directly for processing. The entire process requires no manual data entry, significantly improving AP invoice processing efficiency while reducing human error rates and compliance risks.

> 💡 **In one sentence**: Automatically turn supplier invoices scattered across your mailbox into a clean Excel spreadsheet.

### 😩 Before

```
Open mailbox → Search for invoice emails one by one → Download attachments → Open PDF/images
→ Manually identify invoice numbers, amounts, taxes... → Enter into Excel → Double-check repeatedly
→ 30 invoices later, your eyes are exhausted
```

### 🚀 After

```
Connect mailbox → Auto-fetch attachments → AI recognition in seconds → Structured output → Done ✅
```

### ✨ Key Advantages

| Feature | Description |
|---------|-------------|
| **Zero template configuration** | Works out of the box — no need to configure templates for different supplier invoice formats |
| **Global multilingual support** | Recognizes invoices in Chinese, English, Japanese, German, French, and more |
| **High accuracy** | Dual-engine powered by VLM + LLM, key field accuracy > 95% |
| **Batch concurrency** | Supports batch processing, up to 2 concurrent tasks for paid users |
| **Flexible output** | Exports to Excel by default, or integrates with Feishu, DingTalk, OneDrive, and other business systems |

---

## 🎯 Use Cases

| Scenario | Who you are | What you deal with every day | How this skill helps |
|----------|-------------|------------------------------|----------------------|
| **Overseas procurement reconciliation** | AP accountant at a manufacturing enterprise | 200+ overseas supplier emails per month — opening each one, downloading PDFs, manually copying invoice numbers, amounts, and currencies into Excel, frequently making errors that get sent back by management | Automatically connects to your mailbox, batch-downloads all invoice attachments, AI extracts in seconds, one-click reconciliation Excel generation |
| **Multi-currency settlement verification** | Cross-border trade settlement specialist | Suppliers from 5 countries, invoices in English, Japanese, German — all different formats, each requiring field-by-field verification with translation software | Multilingual auto-recognition, unified standardized field output — no more translating invoice by invoice |
| **Quarterly audit preparation** | Internal / external auditors | During audit periods, digging through six months of emails to find all invoices, sorting by date, verifying amounts — just finding the files takes two days | Set a time range for automatic retrieval, batch-extract key information and archive — two days of work becomes 10 minutes |
| **Employee reimbursement processing** | Administrative finance staff | Employee reimbursement invoices come from everywhere — some in emails, some photographed, some as PDFs — scattered sources are hard to manage uniformly | Email attachments + local files processed together, all reimbursement forms handled in one run |
| **ERP system data entry** | Finance IT manager | Invoice information needs to be manually entered into SAP / Kingdee / Yonyou one by one — 3 minutes per invoice, 200 invoices takes a full day | Map fields to business system field names, import directly after extraction — eliminates manual data entry |

---

## 📬 Supported Email Types

This skill uses universal protocol adaptation and is not limited to specific email providers. The following are commonly verified email services:

### IMAP Protocol Access

| Email Type | IMAP Server Address | Port | Encryption | Authentication | Notes |
|------------|---------------------|------|------------|----------------|-------|
| Gmail | `imap.gmail.com` | 993 | SSL/TLS | App Password | Requires 2-step verification and an app-specific password |
| Outlook / Hotmail | `outlook.office365.com` | 993 | SSL/TLS | Password / OAuth | Personal accounts use password; enterprise accounts recommend OAuth |
| Exchange (On-premises) | Depends on enterprise configuration | 993 / 143 | SSL/TLS / STARTTLS | Domain credentials | Requires IT admin to provide server address; some deployments use 143 + STARTTLS |
| Yahoo Mail | `imap.mail.yahoo.com` | 993 | SSL/TLS | App Password | Requires 2-step verification and an app-specific password |
| Zoho Mail | `imap.zoho.com` | 993 | SSL/TLS | App Password | Requires generating an app-specific password in Zoho security settings; custom domain users may use `imappro.zoho.com` |
| iCloud Mail | `imap.mail.me.com` | 993 | SSL/TLS | App Password | Requires two-factor authentication and an app-specific password generated from Apple ID page |
| QQ Mail | `imap.qq.com` | 993 | SSL/TLS | Authorization code | Requires enabling IMAP in settings and generating an authorization code |
| 163 Mail | `imap.163.com` | 993 | SSL/TLS | Authorization code | Requires enabling IMAP in NetEase Mail settings |
| Feishu Mail | `imap.feishu.cn` | 993 | SSL/TLS | Authorization code | Requires enabling IMAP in Feishu admin console |
| DingTalk Mail | `imap.dingtalk.com` | 993 | SSL/TLS | Authorization code | Requires enabling in DingTalk Mail settings |
| WeCom Mail | `imap.exmail.qq.com` | 993 | SSL/TLS | Client-specific password | Admin must enable IMAP functionality |

### API Protocol Access

| Platform Type | Access Method | Required Credentials | Notes |
|---------------|---------------|----------------------|-------|
| Microsoft Graph API | OAuth 2.0 | client_id + client_secret + tenant_id | For Microsoft 365 Enterprise |
| Gmail API | OAuth 2.0 | client_id + client_secret | For Google Workspace |
| Enterprise self-built mail platform | Mail Open API | app_id + app_secret | Requires API documentation from the platform |

> 💡 **Your email not listed?** No problem — just tell the skill your email type, and it will automatically guide you to provide the corresponding connection parameters.

---

## 📎 Supported Attachment Formats

| Format Type | Supported Extensions |
|-------------|----------------------|
| PDF | `.pdf` |
| Images | `.jpeg` `.jpg` `.png` `.bmp` `.tiff` |
| Word | `.doc` `.docx` |
| Excel | `.xls` `.xlsx` |

Maximum file size for all formats is **50 MB**. Files exceeding 20 MB are recommended to be processed using the ADP async interface.

---

## 🔑 Getting Your ADP API Key

ADP provides independent public cloud access URLs for domestic and overseas users. Accessing the nearest endpoint ensures the best network experience:

| Region | Login Address | API Base URL |
|--------|---------------|--------------|
| Chinese Mainland | [adp.laiye.com](https://adp.laiye.com/?utm_source=clawhub) | `https://adp.laiye.com/` |
| Outside Chinese Mainland | [adp-global.laiye.com](https://adp-global.laiye.com/?utm_source=clawhub) | `https://adp-global.laiye.com/` |

**Steps to obtain:**
1. Visit the login address above and register an ADP account (new users receive **100 free credits per month**)
2. After logging in, click on your avatar in the top-right corner to access the API Key management page
3. Copy your API Key

> On first use, the skill will automatically guide you through API Key configuration — no manual setup required.

---

## 💰 Billing

**🎁 New user benefit:** **100 free credits per month**, usable across all applications, reset at the beginning of each month.

| Processing Type | Credits Consumed | Description |
|-----------------|------------------|-------------|
| Document parsing | 0.5 credits/page | Full-text content parsing |
| Invoice/receipt extraction | 1.5 credits/page | Key field structured extraction |
| Purchase order extraction | 1.5 credits/page | Order field structured extraction |
| Custom extraction | 1 credit/page | User-defined field templates |

> When credits are insufficient, you can top up directly by logging into the ADP portal. Run `adp credit` to check your current balance at any time.

---

## 📁 Document Structure

```
invoice-extractor-from-mail/
├── SKILL.md                        # Skill definition (English, primary)
├── README.md                       # Product overview (English)
├── README_CN.md                    # Product overview (Chinese)
├── refers/
│   └── adp-invoice-fields.md      # ADP field schema reference
└── license.md                      # License
```

| File | Purpose |
|------|---------|
| `SKILL.md` | Core skill logic: workflow, configuration, error handling |
| `refers/adp-invoice-fields.md` | ADP output field definitions and mapping rules |
| `README.md` / `README_CN.md` | User-facing product documentation |

---

## 📚 Resources

- **ADP Portal**: [Chinese Mainland](https://adp.laiye.com/?utm_source=github) | [Outside Chinese Mainland](https://adp-global.laiye.com/?utm_source=github)
- **CLI Documentation**: [ADP CLI User Guide](https://laiye-tech.feishu.cn/wiki/YIaawiK2DimisZk5KfDc8a8cnLh)
- **API Documentation**: [OpenAPI User Guide](https://laiye-tech.feishu.cn/wiki/S1t2wYR04ivndKkMDxxcp2SFnKd)
- **User Guide**: [Public Cloud Operation Manual](https://laiye-tech.feishu.cn/wiki/OfexwgVUQiOpEek4kO7c7NEJnAe)
- **Feedback**: [GitHub Issues](https://github.com/laiye-ai/adp-cli/issues) | [REDACTED_SECRET]
- **Official Website**: [Laiye Technology](https://laiye.com)

---

<div align="center">

[⬆ Back to top](#-invoice-extractor-from-mail)

**Building the future of agentic AI with ❤️**

Copyright © 2026 [Laiye Technology (Beijing) Co., Ltd.] All rights reserved.

</div>


path: README_CN.md
content: <div align="center">

# 📨 Invoice Extractor from Mail

**邮件发票智能抽取技能**

专为海外采购、跨境贸易企业的 AP 财务团队打造

`自动获取邮件附件` → `ADP 智能抽取` → `一键输出至 Excel / 业务系统`

</div>

---

## 📖 产品介绍

**Invoice Extractor from Mail** 是来也科技官方打造、面向传统制造业财务团队的专属发票抽取技能。依托来也 [ADP（Agentic Document Processing）](https://adp-global.laiye.com/?utm_source=github) 核心能力，打通从邮件到业务系统的端到端自动化文档处理链路，将原本繁琐的 "查找附件 → 手工录入" 压缩为一步自动化执行：自动获取附件 → ADP 智能抽取 → 一键输出至 Excel / 业务系统，大幅提升跨境采购发票处理效率与数据准确性。

支持对接国内外主流邮箱，通过 IMAP/OAuth 安全接入，可自动抓取邮件中的发票附件，批量提取全球多语种发票的关键信息（发票号、金额、币种等）。如果发票存储在本地，也可直接上传处理。全程无需人工手动录入，大幅提升 AP 财务票据处理效率，降低人工出错率与合规风险。

> 💡 **一句话理解**：把你邮箱里散落的供应商发票，自动变成一张干净的 Excel 表。

### 😩 没有它之前

```
打开邮箱 → 逐封查找发票邮件 → 下载附件 → 打开 PDF/图片
→ 肉眼识别发票号、金额、税额… → 手动录入 Excel → 反复核对
→ 一天下来处理了 30 张，眼睛已花
```

### 🚀 有了它之后

```
连接邮箱 → 自动抓取附件 → AI 秒级识别 → 结构化输出 → 完成 ✅
```

### ✨ 核心优势

| 特性 | 说明 |
|------|------|
| **零模板配置** | 开箱即用，无需为不同供应商的发票格式分别配置模板 |
| **全球多语种** | 中、英、日、德、法等多语种发票识别 |
| **高准确率** | VLM + LLM 双引擎驱动，关键字段准确率 > 95% |
| **批量并发** | 支持批量处理，付费用户最高 2 并发 |
| **灵活输出** | 默认导出 Excel，也可对接飞书、钉钉、OneDrive 等业务系统 |

---

## 🎯 适用场景

| 场景 | 你是谁 | 你每天在经历什么 | 这个技能怎么帮你 |
|------|--------|-----------------|-----------------|
| **海外采购对账** | 制造企业 AP 会计 | 每月 200+ 封海外供应商邮件，逐封打开、下载 PDF，手动抄写发票号、金额、币种到 Excel，经常抄错被领导退回 | 自动连接你的邮箱，批量下载所有发票附件，AI 秒级抽取，一键生成对账 Excel |
| **多币种结算核对** | 跨境贸易结算专员 | 供应商来自 5 个国家，发票有英文、日文、德文，格式各不相同，每张都要对着翻译软件逐字段核对 | 多语种自动识别，统一输出标准化字段，不用再逐张翻译 |
| **季度审计备查** | 内审 / 外审人员 | 审计期要从半年的邮件中翻出所有发票，按时间排列、核对金额，光找文件就花了两天 | 设定时间范围自动抓取，批量抽取关键信息并归档，两天的活变成 10 分钟 |
| **员工报销处理** | 行政财务 | 员工的报销发票有的在邮件里、有的拍照发过来、有的是 PDF，来源分散难统一管理 | 邮件附件 + 本地文件统一处理，一次跑完全部报销单 |
| **ERP 系统录入** | 财务信息化负责人 | 发票信息需要手动逐条录入 SAP / 金蝶 / 用友，录一张要 3 分钟，200 张就是一整天 | 字段映射到业务系统字段名，抽取后直接导入，省掉手工录入环节 |

---

## 📬 支持的邮箱类型

本技能采用通用协议适配，不限定具体邮箱品牌。以下为已验证的常见邮箱：

### IMAP 协议接入

| 邮箱类型 | IMAP 服务器地址 | 端口 | 加密 | 认证方式 | 备注 |
|----------|----------------|------|------|---------|------|
| Gmail | `imap.gmail.com` | 993 | SSL/TLS | App Password | 需开启两步验证并生成应用专用密码 |
| Outlook / Hotmail | `outlook.office365.com` | 993 | SSL/TLS | 密码 / OAuth | 个人账户使用密码，企业账户建议 OAuth |
| Exchange (本地部署) | 视企业配置而定 | 993 / 143 | SSL/TLS / STARTTLS | 域账号密码 | 需 IT 管理员提供服务器地址，部分部署使用 143 + STARTTLS |
| Yahoo Mail | `imap.mail.yahoo.com` | 993 | SSL/TLS | App Password | 需开启两步验证并生成应用专用密码 |
| Zoho Mail | `imap.zoho.com` | 993 | SSL/TLS | App Password | 需在 Zoho 安全设置中生成应用专用密码；自定义域名用户服务器可能为 `imappro.zoho.com` |
| iCloud Mail | `imap.mail.me.com` | 993 | SSL/TLS | App Password | 需开启双重认证并在 Apple ID 页面生成应用专用密码 |
| QQ 邮箱 | `imap.qq.com` | 993 | SSL/TLS | 授权码 | 需在设置中开启 IMAP 并生成授权码 |
| 163 邮箱 | `imap.163.com` | 993 | SSL/TLS | 授权码 | 需在网易邮箱设置中开启 IMAP |
| 飞书邮箱 | `imap.feishu.cn` | 993 | SSL/TLS | 授权码 | 需在飞书管理后台开启 IMAP |
| 钉钉邮箱 | `imap.dingtalk.com` | 993 | SSL/TLS | 授权码 | 需在钉钉邮箱设置中开启 |
| 企业微信邮箱 | `imap.exmail.qq.com` | 993 | SSL/TLS | 客户端专用密码 | 管理员需开启 IMAP 功能 |


### API 协议接入

| 平台类型 | 接入方式 | 所需凭证 | 备注 |
|----------|---------|---------|------|
| Microsoft Graph API | OAuth 2.0 | client_id + client_secret + tenant_id | 适用于 Microsoft 365 企业版 |
| Gmail API | OAuth 2.0 | client_id + client_secret | 适用于 Google Workspace |
| 企业自建邮件平台 | Mail Open API | app_id + app_secret | 需平台提供 API 文档 |

> 💡 **你的邮箱不在列表中？** 没关系——只需告诉技能你的邮箱类型，它会自动引导你提供对应的连接参数。

---

## 📎 支持的附件格式

| 格式类型 | 支持的扩展名 |
|---------|-------------|
| PDF | `.pdf` |
| 图片 | `.jpeg` `.jpg` `.png` `.bmp` `.tiff` |
| Word | `.doc` `.docx` |
| Excel | `.xls` `.xlsx` |

所有格式单文件最大支持 **50 MB**。超过 20 MB 的文件建议使用 ADP 异步接口处理。

---

## 🔑 ADP API Key 获取

ADP 为国内外用户提供了独立的公有云接入地址，就近访问可保障最佳网络体验：

| 区域 | 登录地址 | API Base URL |
|------|---------|--------------|
| 中国大陆 | [adp.laiye.com](https://adp.laiye.com/?utm_source=clawhub) | `https://adp.laiye.com/` |
| 非中国大陆 | [adp-global.laiye.com](https://adp-global.laiye.com/?utm_source=clawhub) | `https://adp-global.laiye.com/` |

**获取步骤：**
1. 访问上述登录地址，注册 ADP 账户（新用户每月获得 **100 免费积分**）
2. 登录后，点击右上角个人头像，进入 API Key 管理页面
3. 复制你的 API Key

> 首次使用时，技能会自动引导你完成 API Key 配置，无需手动操作。

---

## 💰 计费规则

**🎁 新用户福利：** 每月获得 **100 免费积分**，不限使用应用，每月初重置。

| 处理类型 | 消耗积分 | 说明 |
|---------|---------|------|
| 文档解析 | 0.5 积分/页 | 全文内容解析 |
| 发票/收据抽取 | 1.5 积分/页 | 关键字段结构化提取 |
| 采购订单抽取 | 1.5 积分/页 | 订单字段结构化提取 |
| 自定义抽取 | 1 积分/页 | 用户自定义字段模板 |

> 积分不足时可直接登录 ADP 门户进行充值。运行 `adp credit` 可随时查看当前余额。

---

## 📁 文档结构

```
invoice-extractor-from-mail/
├── SKILL.md                        # Skill 定义（英文，主文件）
├── README.md                       # 产品说明（英文）
├── README_CN.md                    # 产品说明（中文）
├── refers/
│   └── adp-invoice-fields.md      # ADP 字段 schema 参考
└── license.md                      # 许可证
```

| 文件 | 用途 |
|------|------|
| `SKILL.md` | 核心技能逻辑：工作流、配置、错误处理 |
| `refers/adp-invoice-fields.md` | ADP 输出字段定义与映射规则 |
| `README.md` / `README_CN.md` | 面向用户的产品文档 |

---

## 📚 相关资料

- **ADP 产品入口**：[中国大陆](https://adp.laiye.com/?utm_source=github) | [非中国大陆](https://adp-global.laiye.com/?utm_source=github)
- **CLI 文档**：[ADP CLI 使用指南](https://laiye-tech.feishu.cn/wiki/YIaawiK2DimisZk5KfDc8a8cnLh)
- **API 文档**：[OpenAPI 使用指南](https://laiye-tech.feishu.cn/wiki/S1t2wYR04ivndKkMDxxcp2SFnKd)
- **产品手册**：[公有云操作手册](https://laiye-tech.feishu.cn/wiki/OfexwgVUQiOpEek4kO7c7NEJnAe)
- **问题反馈**：[GitHub Issues](https://github.com/laiye-ai/adp-cli/issues) | [REDACTED_SECRET]
- **官方网站**：[来也科技](https://laiye.com)

---

<div align="center">

[⬆ 返回顶部](#-invoice-extractor-from-mail)

**用 ❤️ 构建智能体 AI 的未来**

版权所有 © 2026 [来也科技（北京）有限公司] 保留所有权利。

</div>


path: refers/adp-invoice-fields.md
content: # ADP Invoice/Receipt Extraction — Field Schema Reference

This document defines the fixed field schema returned by ADP for invoice/receipt extraction. The `field_key` values are immutable identifiers used for field mapping configuration.

---

## Header Fields

| field_key | Default field_name | Type | Description |
|-----------|-------------------|------|-------------|
| `invoice_number` | Invoice Number | string | Unique invoice identifier |
| `invoice_date` | Invoice Date | string (YYYY-MM-DD) | Date the invoice was issued |
| `supplier_name` | Supplier Name | string | Name of the supplier/vendor |
| `supplier_vat_number` | Supplier VAT Number | string | Tax identification number of the supplier |
| `customer_name` | Customer Name | string | Name of the buyer/customer |
| `customer_vat_number` | Customer VAT Number | string | Tax identification number of the customer |
| `currency` | Currency | string (ISO 4217) | Currency code (e.g., USD, EUR, CNY) |
| `total_without_tax` | Total (Excl. Tax) | string | Total amount before tax |
| `vat_rate` | VAT Rate | string | Tax rate percentage |
| `total_amount` | Total Amount | string | Total amount including tax |
| `amount_due` | Amount Due | string | Amount payable |

---

## Line Item Fields (within `table_values`)

The `line_items` field in ADP output contains a `table_values` array. Each row is an array of field objects with the following keys:

| field_key | Default field_name | Type | Description |
|-----------|-------------------|------|-------------|
| `line_items_item_code` | Item Code | string | Product/service code or SKU |
| `line_items_description` | Description | string | Line item description |
| `line_items_quantity` | Quantity | string | Quantity of items |
| `line_items_unit_price` | Unit Price | string | Price per unit |
| `line_items_total_amount` | Line Total | string | Total amount for this line |

---

## ADP Output JSON Structure

Each extracted document returns an array of field objects:

```json
[
  {
    "field_key": "invoice_number",
    "field_name": "Invoice Number",
    "field_values": [
      {
        "field_value": "MK-2026-03077",
        "field_confidence": 1.0,
        "references": []
      }
    ]
  },
  ...
  {
    "field_key": "line_items",
    "field_name": "Line Items",
    "field_confidence": 1.0,
    "references": [],
    "table_values": [
      [
        { "field_key": "line_items_item_code", "field_name": "Item Code", "field_values": [...] },
        { "field_key": "line_items_description", "field_name": "Description", "field_values": [...] },
        { "field_key": "line_items_quantity", "field_name": "Quantity", "field_values": [...] },
        { "field_key": "line_items_unit_price", "field_name": "Unit Price", "field_values": [...] },
        { "field_key": "line_items_total_amount", "field_name": "Line Total", "field_values": [...] }
      ]
    ]
  }
]
```

---

## Field Mapping Rules

- **Key** (`field_key`): Fixed ADP identifier. Used by the Skill to match ADP output to mapping configuration. **Cannot be modified.**
- **Value** (user-defined display name): Determines Excel column headers or target field names in business systems. **Freely modifiable by user.**
- If no mapping is configured, the Skill uses ADP's raw `field_name` as the display name.
- All `field_value` entries are strings. Numeric conversion (if needed) is handled at the output stage.
- `field_confidence` ranges from 0.0 to 1.0; values below 0.8 should be flagged for user review.

---

## Example `field_map.json`

```json
{
  "invoice/receipt": {
    "invoice_number":             "Invoice Number",
    "invoice_date":               "Invoice Date",
    "supplier_name":              "Supplier Name",
    "supplier_vat_number":        "Supplier VAT Number",
    "customer_name":              "Customer Name",
    "customer_vat_number":        "Customer VAT Number",
    "currency":                   "Currency",
    "total_without_tax":          "Total (Excl. Tax)",
    "vat_rate":                   "VAT Rate",
    "total_amount":               "Total Amount",
    "amount_due":                 "Amount Due",
    "line_items_item_code":       "Item Code",
    "line_items_description":     "Description",
    "line_items_quantity":        "Quantity",
    "line_items_unit_price":      "Unit Price",
    "line_items_total_amount":    "Line Total"
  }
}
```

> For API push mode (Mode C), the values in this mapping become the field names in the POST request body sent to the business system.


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)