API Reference
Complete documentation for MailSage — the open-source PHP email intelligence library. PHP 8.2+, MIT License, zero external dependencies.
composer install. All detection engines are lazy-loaded inside the Email model.
Installation
Requires PHP 8.2 or higher, ext-mbstring, and ext-json.
composer require mailsage/mailsage
Quick Start
use MailSage\EmailParser; // From raw email string $email = EmailParser::parse($rawEmail); // From EML file $email = EmailParser::fromFile('path/to/email.eml'); // Basic usage $email->subject(); $email->category(); // "invoice" | "order" | "spam" | ... $email->isSpam(); $email->isInvoice(); $email->invoice()->amount(); $email->toJson();
EmailParser
The primary entry point. All methods are static for convenience; the class can also be instantiated and used via instance methods.
| Method | Returns | Description |
|---|---|---|
| EmailParser::parse(string $raw) | Parse a raw email string. Throws InvalidEmailException if empty. | |
| EmailParser::fromFile(string $path) | Parse an EML file. Throws InvalidEMLException if missing/invalid. |
Email Model
The Email object returned by all parsing operations. All intelligence methods are lazy-loaded — detectors only run when first called and their results are cached.
Basic Fields
| Method | Returns | Description |
|---|---|---|
| subject() | string | Decoded subject line (RFC 2047 MIME words decoded) |
| sender() | array | {name, email, raw} — the From address |
| recipient() | array[] | List of {name, email, raw} — all To addresses |
| cc() | array[] | CC recipients |
| bcc() | array[] | BCC recipients |
| date() | string | Raw Date header value |
| messageId() | string | Message-ID header |
| body() | string | Decoded plain text body |
| htmlBody() | string | Decoded HTML body |
| headers() | array | All parsed headers. Keys are lowercased. Multi-valued headers return string[]. |
| header(string $name) | string|array|null | Single header value by name (case-insensitive) |
| metadata() | array | raw_size, has_html, has_plain, attachment_count, content_type |
Intelligence Methods
| Method | Returns | Description |
|---|---|---|
| isSpam() | bool | True when spam score ≥ 50 |
| spamScore() | int | Spam score 0–100 (cached after first call) |
| isPhishing() | bool | True when phishing confidence ≥ 50 |
| isInvoice() | bool | True when invoice confidence ≥ 40 |
| invoice() | Invoice | Extracted invoice data object |
| isOrder() | bool | True when order confidence ≥ 40 |
| order() | Order | Extracted order data object |
| isLead() | bool | True when lead confidence ≥ 35 |
| lead() | Lead | Extracted lead/contact data object |
| isSupportRequest() | bool | True when support confidence ≥ 30 |
| supportSubCategory() | string | bug_report | login_issue | refund_request | complaint | technical | general |
| category() | string | Primary category: invoice, order, support, sales, marketing, spam, general… |
| confidence() | int | Confidence score for the detected category (0–100) |
Reports & Attachments
| Method | Returns | Description |
|---|---|---|
| headerReport() | array | SPF, DKIM, DMARC results, Return-Path, Received chain |
| securityReport() | array | Full security analysis (cached). See Security Report section. |
| attachmentRisk() | string | Highest risk level across all attachments |
| attachments() | AttachmentManager | The attachment manager instance |
| saveAttachments(string $dir) | string[] | Save all attachments to directory, returns file paths |
AttachmentManager & Attachment
Returned by $email->attachments().
AttachmentManager
| Method | Returns | Description |
|---|---|---|
| all() | Attachment[] | All attachment objects |
| count() | int | Number of attachments |
| hasAttachments() | bool | Whether any attachments exist |
| highestRiskLevel() | string | Highest risk level across all attachments |
| hasDangerousAttachment() | bool | True if any attachment is high or critical risk |
| filterByExtension(string ...$ext) | Attachment[] | Filter by one or more extensions |
| saveAll(string $dir) | string[] | Save all attachments, return saved paths |
| toArray() | array[] | All attachments as plain arrays |
Attachment
| Method | Returns | Description |
|---|---|---|
| name() | string | Original filename |
| extension() | string | Lowercase file extension |
| mimeType() | string | MIME type (e.g. application/pdf) |
| size() | int | Size in bytes after decoding |
| content() | string | Decoded binary content |
| riskLevel() | string | safe | low | medium | high | critical |
| save(string $dir) | string | Save to directory, return absolute path |
| toArray() | array | All properties as array |
Spam Detection
The spam detector uses a keyword scoring engine that produces a 0–100 score. Emails scoring 50 or above are considered spam.
$email->isSpam(); // bool — score >= 50 $email->spamScore(); // int 0-100 // Full analysis via SpamDetector directly use MailSage\Spam\SpamDetector; $detector = new SpamDetector(); $analysis = $detector->analyze($email); // ['score' => 91, 'is_spam' => true, 'indicators' => [...]]
Phishing Analysis
Detects display name spoofing, brand impersonation, shortened URLs, and phishing language patterns.
$email->isPhishing(); // bool $report = $email->securityReport(); $report['phishing_confidence']; // int 0-100 $report['phishing_indicators']; // string[] $report['sender_mismatch']; // bool $report['suspicious_urls']; // string[] $report['overall_risk']; // 'safe'|'low'|'medium'|'high'|'critical'
Invoice Extraction
$email->isInvoice(); // bool $invoice = $email->invoice(); $invoice->number(); // ?string e.g. "INV-2026-0547" $invoice->date(); // ?string e.g. "June 25, 2026" $invoice->amount(); // ?float e.g. 1595.00 $invoice->currency(); // ?string e.g. "USD" $invoice->vendor(); // ?string sender name/domain $invoice->toArray();
Order Detection
Detects e-commerce order confirmations. Supported platforms: Shopify, WooCommerce, Magento, PrestaShop, BigCommerce, Amazon, eBay, Etsy, and generic.
$email->isOrder(); // bool $order = $email->order(); $order->number(); // ?string e.g. "1042" $order->customer(); // ?string recipient name $order->amount(); // ?float e.g. 89.95 $order->currency(); // ?string e.g. "USD" $order->platform(); // ?string e.g. "shopify" $order->toArray();
Lead Extraction
$email->isLead(); // bool $lead = $email->lead(); $lead->name(); // ?string e.g. "Sarah Johnson" $lead->email(); // ?string e.g. "sarah@techstartup.com" $lead->phone(); // ?string e.g. "+1 (415) 555-9876" $lead->company(); // ?string e.g. "TechStartup Inc." $lead->toArray();
Support Detection
$email->isSupportRequest(); // bool $email->supportSubCategory(); // string // 'bug_report' | 'login_issue' | 'refund_request' // 'complaint' | 'technical' | 'general'
Categorization
Auto-categorizes emails with confidence scoring. Supports custom category registration at runtime.
$email->category(); // "invoice" | "order" | "spam" | "support" | ... $email->confidence(); // int 0-100 // Register custom categories use MailSage\Categorization\Category; Category::register('legal', ['contract', 'nda', 'agreement']); Category::register('pr', ['press release', 'media']); Category::unregister('legal'); Category::clearAll(); Category::has('legal'); // bool Category::getCustomCategories(); // array
Built-in categories: invoiceordersupportsalesmarketingfeedbackjob_applicationpartnershipspamgeneral
Security Report
Returns a comprehensive security analysis. Results are cached after the first call.
$report = $email->securityReport(); $report['is_phishing'] // bool $report['phishing_confidence'] // int 0-100 $report['has_dangerous_attachment'] // bool $report['attachment_risk'] // 'safe'|'low'|'medium'|'high'|'critical' $report['suspicious_urls'] // string[] $report['phishing_indicators'] // string[] $report['sender_mismatch'] // bool $report['overall_risk'] // 'safe'|'low'|'medium'|'high'|'critical'
Header Report
$report = $email->headerReport(); $report['message_id'] // string $report['return_path'] // string $report['spf'] // 'pass'|'fail'|'softfail'|null $report['dkim'] // 'pass'|'fail'|null $report['dmarc'] // 'pass'|'fail'|null $report['received'] // string[] all Received headers
Export
$email->toArray(); // Full email as PHP array $email->toJson(); // Pretty-printed JSON $email->toCsv(); // CSV (flat single row: subject, from, to, date, body snippet, attachments)
Exceptions
| Exception | When Thrown |
|---|---|
| InvalidEmailException | Empty email string passed to parse(), or malformed content |
| InvalidEMLException | EML file not found, unreadable, empty, or no valid email headers detected |
| AttachmentException | Save directory missing, not writable, or file write failed |
| ParserException | MIME structure parsing failed or unsupported content encoding |
| SecurityException | Security analysis error |
| SpamDetectionException | Spam analysis error or invalid score |
use MailSage\Exceptions\InvalidEmailException; use MailSage\Exceptions\InvalidEMLException; use MailSage\Exceptions\AttachmentException; try { $email = EmailParser::fromFile('email.eml'); $email->saveAttachments('/uploads'); } catch (InvalidEMLException $e) { // File not found or invalid } catch (AttachmentException $e) { // Directory not writable }
Spam Score Breakdown
| Indicator | Max Points |
|---|---|
| Spam keywords in subject line | +30 |
| Spam keywords in body | +20 |
| Phishing-related language | +24 |
| Excessive ALL CAPS words | +10 |
| Excessive hyperlinks (>5) | +10 |
| Shortened URL (bit.ly, tinyurl…) | +5 |
| Sender uses disposable domain | +15 |
| Subject is ALL CAPS | +8 |
| Excessive exclamation marks | +5 |
Attachment Risk Levels
| Level | Examples |
|---|---|
| safe | .png, .jpg, .gif, .txt, .csv, .mp4, .mp3 |
| low | .pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx |
| medium | .docm, .xlsm, .pptm, .xlsb, .dotm (macro-enabled Office) |
| high | .zip, .rar, .7z, .tar, .gz, .iso, .dmg, .dll, .sys |
| critical | .exe, .bat, .cmd, .scr, .js, .vbs, .ps1, .msi, .hta, .jar |