MailSage API Reference · v1.0.0

API Reference

Complete documentation for MailSage — the open-source PHP email intelligence library. PHP 8.2+, MIT License, zero external dependencies.

No configuration required. MailSage works out of the box after composer install. All detection engines are lazy-loaded inside the Email model.

Installation

Requires PHP 8.2 or higher, ext-mbstring, and ext-json.

bash
composer require mailsage/mailsage

Quick Start

php
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.

MethodReturnsDescription
EmailParser::parse(string $raw)EmailParse a raw email string. Throws InvalidEmailException if empty.
EmailParser::fromFile(string $path)EmailParse 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

MethodReturnsDescription
subject()stringDecoded 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()stringRaw Date header value
messageId()stringMessage-ID header
body()stringDecoded plain text body
htmlBody()stringDecoded HTML body
headers()arrayAll parsed headers. Keys are lowercased. Multi-valued headers return string[].
header(string $name)string|array|nullSingle header value by name (case-insensitive)
metadata()arrayraw_size, has_html, has_plain, attachment_count, content_type

Intelligence Methods

MethodReturnsDescription
isSpam()boolTrue when spam score ≥ 50
spamScore()intSpam score 0–100 (cached after first call)
isPhishing()boolTrue when phishing confidence ≥ 50
isInvoice()boolTrue when invoice confidence ≥ 40
invoice()InvoiceExtracted invoice data object
isOrder()boolTrue when order confidence ≥ 40
order()OrderExtracted order data object
isLead()boolTrue when lead confidence ≥ 35
lead()LeadExtracted lead/contact data object
isSupportRequest()boolTrue when support confidence ≥ 30
supportSubCategory()stringbug_report | login_issue | refund_request | complaint | technical | general
category()stringPrimary category: invoice, order, support, sales, marketing, spam, general
confidence()intConfidence score for the detected category (0–100)

Reports & Attachments

MethodReturnsDescription
headerReport()arraySPF, DKIM, DMARC results, Return-Path, Received chain
securityReport()arrayFull security analysis (cached). See Security Report section.
attachmentRisk()stringHighest risk level across all attachments
attachments()AttachmentManagerThe attachment manager instance
saveAttachments(string $dir)string[]Save all attachments to directory, returns file paths

AttachmentManager & Attachment

Returned by $email->attachments().

AttachmentManager

MethodReturnsDescription
all()Attachment[]All attachment objects
count()intNumber of attachments
hasAttachments()boolWhether any attachments exist
highestRiskLevel()stringHighest risk level across all attachments
hasDangerousAttachment()boolTrue 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

MethodReturnsDescription
name()stringOriginal filename
extension()stringLowercase file extension
mimeType()stringMIME type (e.g. application/pdf)
size()intSize in bytes after decoding
content()stringDecoded binary content
riskLevel()stringsafe | low | medium | high | critical
save(string $dir)stringSave to directory, return absolute path
toArray()arrayAll 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.

php
$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.

php
$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

php
$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.

php
$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

php
$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

php
$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.

php
$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.

php
$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

php
$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

php
$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

ExceptionWhen Thrown
InvalidEmailExceptionEmpty email string passed to parse(), or malformed content
InvalidEMLExceptionEML file not found, unreadable, empty, or no valid email headers detected
AttachmentExceptionSave directory missing, not writable, or file write failed
ParserExceptionMIME structure parsing failed or unsupported content encoding
SecurityExceptionSecurity analysis error
SpamDetectionExceptionSpam analysis error or invalid score
php
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

IndicatorMax 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
Score is capped at 100. Emails scoring 50 or above are classified as spam.

Attachment Risk Levels

LevelExamples
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