PHPackages                             turahe/mailclient - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. turahe/mailclient

ActiveLibrary

turahe/mailclient
=================

A comprehensive Laravel mail client package for managing email accounts, messages, and folders

v1.2.1(8mo ago)14MITPHPPHP ^8.4CI passing

Since Jan 20Pushed 8mo ago1 watchersCompare

[ Source](https://github.com/turahe/mail-client)[ Packagist](https://packagist.org/packages/turahe/mailclient)[ RSS](/packages/turahe-mailclient/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (3)Dependencies (14)Versions (7)Used By (0)

Turahe Mail Client
==================

[](#turahe-mail-client)

[![Latest Version on Packagist](https://camo.githubusercontent.com/0dfa14c8247b3ea2bcf36abea23f822f7472ed02422889fdefb72788e3bf9ed7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7475726168652f6d61696c636c69656e742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/turahe/mailclient)[![GitHub Tests Action Status](https://camo.githubusercontent.com/a4393d1b850641919bc79c994b9d5c9ce1e9795d8af4c581f4fde81ac3ade8c7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7475726168652f6d61696c2d636c69656e742f63692e796d6c3f6272616e63683d6d6173746572266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/turahe/mail-client/actions?query=workflow%3Aci+branch%3Amaster)[![Total Downloads](https://camo.githubusercontent.com/c392488bcd62b8169dd66ef9eb87199baf0b7238f827d047591af3a71707c51e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7475726168652f6d61696c636c69656e742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/turahe/mailclient)[![License](https://camo.githubusercontent.com/b80f3f99f8d804ca72f0cc002a08becb0792693797f50175d43bde461bbbdf50/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f7475726168652f6d61696c636c69656e742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/turahe/mailclient)[![PHP Version Require](https://camo.githubusercontent.com/1317bd28fd7160aab0f8d838f9a2e1a7a77134efce4db4256622adc80711d58c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f7475726168652f6d61696c636c69656e742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/turahe/mailclient)[![Test Coverage](https://camo.githubusercontent.com/bf85cb9269d780292c65e8588797f9db0a0d46de1a62c660e01ed324ccb39ea1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d353636253230617373657274696f6e732d627269676874677265656e3f7374796c653d666c61742d737175617265)](https://github.com/turahe/mail-client)

A comprehensive Laravel mail client package for managing email accounts, messages, and folders with support for IMAP, SMTP, Gmail, Outlook, and various email providers.

---

📋 Table of Contents
-------------------

[](#-table-of-contents)

- [Features](#-features)
- [Requirements](#-requirements)
- [Quick Start](#-quick-start)
- [Configuration](#%EF%B8%8F-configuration)
- [Basic Usage](#-basic-usage)
- [Advanced Features](#-advanced-features)
- [Models &amp; Architecture](#%EF%B8%8F-models--architecture)
- [Testing](#-testing)
- [API Reference](#-api-reference)
- [Troubleshooting](#-troubleshooting)
- [Contributing](#%EF%B8%8F-contributing)
- [Support](#-support)

---

✨ Features
----------

[](#-features)

- **🔐 Multi-Provider Support** - IMAP, SMTP, Gmail API, Outlook/Exchange
- **📧 Complete Email Management** - Send, receive, organize, and track emails
- **📂 Folder Hierarchy** - Nested folder structures with full CRUD operations
- **📋 Email Templates** - Predefined and reusable email templates
- **⏰ Scheduled Emails** - Queue and schedule emails for future delivery
- **📊 Link Tracking** - Track email link clicks and analytics
- **🔄 Sync Management** - Intelligent email synchronization
- **🆔 ULID Support** - Modern, sortable unique identifiers
- **🧪 100% Test Coverage** - 173 tests, 566 assertions, rock-solid reliability

---

🚀 Requirements
--------------

[](#-requirements)

ComponentVersion**PHP**8.4+**Laravel**12.0+**Database**MySQL 8.0+ / PostgreSQL 13+ / SQLite 3.35+---

⚡ Quick Start
-------------

[](#-quick-start)

### 1. Install Package

[](#1-install-package)

```
composer require turahe/mailclient
```

### 2. Publish &amp; Migrate

[](#2-publish--migrate)

```
php artisan vendor:publish --provider="Turahe\MailClient\MailClientServiceProvider"
php artisan migrate
```

### 3. Create Your First Email Account

[](#3-create-your-first-email-account)

```
use Turahe\MailClient\Models\EmailAccount;
use Turahe\MailClient\Enums\ConnectionType;

$account = EmailAccount::create([
    'email' => 'user@example.com',
    'password' => 'your_password',
    'connection_type' => ConnectionType::IMAP,
    'imap_server' => 'imap.example.com',
    'imap_port' => 993,
    'smtp_server' => 'smtp.example.com',
    'smtp_port' => 587,
]);
```

### 4. Send Your First Email

[](#4-send-your-first-email)

```
$client = $account->createClient();

$message = $client->compose()
    ->to('recipient@example.com')
    ->subject('Hello World!')
    ->html('Hello from Laravel Mail Client!')
    ->send();
```

---

⚙️ Configuration
----------------

[](#️-configuration)

### Environment Setup

[](#environment-setup)

```
# Gmail OAuth
GMAIL_CLIENT_ID=your_gmail_client_id
GMAIL_CLIENT_SECRET=your_gmail_client_secret
GMAIL_REDIRECT_URL=your_callback_url

# Outlook OAuth
OUTLOOK_CLIENT_ID=your_outlook_client_id
OUTLOOK_CLIENT_SECRET=your_outlook_client_secret
OUTLOOK_REDIRECT_URL=your_callback_url
```

### Package Configuration

[](#package-configuration)

```
// config/mail-client.php
return [
    'default_connection_type' => 'imap',
    'sync_batch_size' => 50,
    'max_attachment_size' => 25 * 1024 * 1024, // 25MB
    'allowed_attachment_types' => ['pdf', 'doc', 'docx', 'jpg', 'png'],
];
```

---

📧 Basic Usage
-------------

[](#-basic-usage)

**📥 Email Account Management**### Creating Different Account Types

[](#creating-different-account-types)

#### IMAP/SMTP Account

[](#imapsmtp-account)

```
$account = EmailAccount::create([
    'email' => 'user@example.com',
    'password' => 'secure_password',
    'connection_type' => ConnectionType::IMAP,
    'imap_server' => 'imap.example.com',
    'imap_port' => 993,
    'imap_encryption' => 'ssl',
    'smtp_server' => 'smtp.example.com',
    'smtp_port' => 587,
    'smtp_encryption' => 'tls',
]);
```

#### Gmail Account

[](#gmail-account)

```
$gmailAccount = EmailAccount::create([
    'email' => 'user@gmail.com',
    'connection_type' => ConnectionType::GMAIL,
    'access_token' => $accessToken,
    'refresh_token' => $refreshToken,
]);
```

#### Outlook Account

[](#outlook-account)

```
$outlookAccount = EmailAccount::create([
    'email' => 'user@outlook.com',
    'connection_type' => ConnectionType::OUTLOOK,
    'access_token' => $accessToken,
    'refresh_token' => $refreshToken,
]);
```

### Account Operations

[](#account-operations)

```
// Test connection
if ($account->testConnection()) {
    echo "✅ Connection successful!";
}

// Sync management
$account->enableSync();
$account->disableSync();

// Get statistics
$stats = $account->getStats();
echo "📧 Total: {$stats['total_messages']}";
echo "🔵 Unread: {$stats['unread_messages']}";
```

**📂 Folder Management**### Creating and Organizing Folders

[](#creating-and-organizing-folders)

```
// Create main folder
$folder = EmailAccountFolder::create([
    'email_account_id' => $account->id,
    'name' => 'Important',
    'display_name' => 'Important Messages',
    'syncable' => true,
]);

// Create subfolder
$subFolder = EmailAccountFolder::create([
    'email_account_id' => $account->id,
    'parent_id' => $folder->id,
    'name' => 'Urgent',
    'display_name' => 'Urgent Items',
]);

// Browse hierarchy
$rootFolders = $account->folders()->whereNull('parent_id')->get();
foreach ($rootFolders as $folder) {
    echo "📁 {$folder->name}\n";
    foreach ($folder->children as $child) {
        echo "   └─ 📁 {$child->name}\n";
    }
}
```

**📨 Sending Emails**### Basic Email Composition

[](#basic-email-composition)

```
$client = $account->createClient();

// Simple email
$message = $client->compose()
    ->to('user@example.com')
    ->subject('Meeting Tomorrow')
    ->text('Don\'t forget our meeting at 2 PM tomorrow.')
    ->send();

// Rich HTML email
$message = $client->compose()
    ->to('user@example.com')
    ->cc('manager@example.com')
    ->bcc('archive@example.com')
    ->subject('Project Update')
    ->html('
        Project Status Update
        The project is on track for completion.

            ✅ Phase 1: Complete
            🔄 Phase 2: In Progress
            ⏳ Phase 3: Planned

    ')
    ->attach('/path/to/report.pdf')
    ->send();
```

### Using Templates

[](#using-templates)

```
$template = PredefinedMailTemplate::find(1);
$message = $client->compose()
    ->to('customer@example.com')
    ->fromTemplate($template)
    ->variables([
        'customer_name' => 'John Doe',
        'order_number' => 'ORD-12345',
        'delivery_date' => '2025-01-15'
    ])
    ->send();
```

**📬 Managing Messages**### Reading Messages

[](#reading-messages)

```
// Get recent unread messages
$messages = $account->messages()
    ->unread()
    ->orderBy('date', 'desc')
    ->take(10)
    ->get();

foreach ($messages as $message) {
    echo "📧 {$message->subject}\n";
    echo "👤 From: {$message->from_address}\n";
    echo "📅 Date: {$message->date}\n\n";
}
```

### Message Operations

[](#message-operations)

```
$message = EmailAccountMessage::find($messageId);

// Status operations
$message->markAsRead();
$message->markAsUnread();

// Organization
$message->moveToFolder($importantFolder);
$message->addToFolders([$folder1, $folder2]);

// Lifecycle management
$message->archive();
$message->trash();
$message->restore();
$message->purge(); // Permanent delete
```

### Working with Content

[](#working-with-content)

```
// Get message content
$htmlBody = $message->getHtmlBody();
$textBody = $message->getTextBody();

// Handle attachments
foreach ($message->attachments as $attachment) {
    echo "📎 {$attachment->name} ({$attachment->size} bytes)\n";

    // Download attachment
    $content = $attachment->getContent();
    file_put_contents("/downloads/{$attachment->name}", $content);
}
```

---

🚀 Advanced Features
-------------------

[](#-advanced-features)

**📋 Email Templates**### Creating Templates

[](#creating-templates)

```
$template = PredefinedMailTemplate::create([
    'name' => 'Order Confirmation',
    'subject' => 'Order {{order_number}} Confirmed',
    'html_body' => '
        Order Confirmed! 🎉
        Hello {{customer_name}},
        Your order #{{order_number}} has been confirmed.
        Expected delivery: {{delivery_date}}
    ',
    'text_body' => 'Hello {{customer_name}}, your order #{{order_number}} is confirmed. Delivery: {{delivery_date}}',
    'is_shared' => true,
]);
```

### Using Template Variables

[](#using-template-variables)

```
$processedTemplate = $template->process([
    'customer_name' => 'Sarah Johnson',
    'order_number' => 'ORD-789',
    'delivery_date' => 'January 20, 2025'
]);

// Result:
// Subject: "Order ORD-789 Confirmed"
// Body: "Hello Sarah Johnson, your order #ORD-789 is confirmed..."
```

**⏰ Scheduled Emails**### Scheduling Emails

[](#scheduling-emails)

```
$scheduledEmail = ScheduledEmail::create([
    'email_account_id' => $account->id,
    'to' => 'customer@example.com',
    'subject' => 'Weekly Newsletter',
    'html_body' => 'This Week in Tech...',
    'scheduled_at' => Carbon::now()->addWeek(),
    'data' => ['newsletter_id' => 456],
]);
```

### Processing Scheduled Emails

[](#processing-scheduled-emails)

```
// In your scheduled job (e.g., daily)
$dueEmails = ScheduledEmail::dueForSend()->get();

foreach ($dueEmails as $email) {
    try {
        $email->send();
        echo "✅ Sent: {$email->subject}\n";
    } catch (Exception $e) {
        echo "❌ Failed: {$e->getMessage()}\n";
    }
}
```

**📊 Link Tracking**### Automatic Link Tracking

[](#automatic-link-tracking)

```
// Links in emails are automatically tracked
$message = $client->compose()
    ->to('user@example.com')
    ->subject('Check out our new features!')
    ->html('
        Visit our new features page
        Read the latest blog post
    ')
    ->send();
```

### Analyzing Click Data

[](#analyzing-click-data)

```
$message = EmailAccountMessage::find($messageId);

// Get all clicks
$clicks = $message->linkClicks;

foreach ($clicks as $click) {
    echo "🔗 URL: {$click->url}\n";
    echo "📅 Clicked: {$click->clicked_at}\n";
    echo "🌍 IP: {$click->ip_address}\n";
    echo "💻 Browser: {$click->user_agent}\n\n";
}

// Statistics
$totalClicks = $message->linkClicks()->count();
$uniqueClicks = $message->linkClicks()->distinct('ip_address')->count();
echo "📊 Total clicks: {$totalClicks} | Unique: {$uniqueClicks}";
```

**🔄 Bulk Operations**### Mass Message Management

[](#mass-message-management)

```
// Get messages to process
$messages = $account->messages()
    ->where('subject', 'like', '%newsletter%')
    ->get();

// Bulk operations
$account->moveMessagesToFolder($messages, $newsletterFolder);
$account->markMessagesAsRead($messages);
$account->deleteMessages($messages);
```

### Sync Management

[](#sync-management)

```
use Turahe\MailClient\Services\EmailAccountMessageSyncService;

$syncService = app(EmailAccountMessageSyncService::class);

// Full account sync
$syncService->syncAccount($account);

// Incremental sync (faster)
$lastSync = $account->last_synced_at;
$syncService->syncAccountIncremental($account, $lastSync);

// Sync specific folder only
$syncService->syncFolder($folder);
```

---

🏗️ Models &amp; Architecture
----------------------------

[](#️-models--architecture)

### Core Models Overview

[](#core-models-overview)

ModelPurposeKey Features**EmailAccount**Email account managementMulti-provider support, OAuth, sync settings**EmailAccountFolder**Folder organizationHierarchical structure, sync control**EmailAccountMessage**Message storageRich content, attachments, metadata**EmailAccountMessageAddress**Email addressesFrom, To, CC, BCC tracking**EmailAccountMessageHeader**Email headersTechnical metadata storage**PredefinedMailTemplate**Email templatesVariable substitution, sharing**ScheduledEmail**Email schedulingQueue management, retry logic**MessageLinksClick**Link analyticsClick tracking, user behavior### Key Relationships

[](#key-relationships)

```
// EmailAccount (1:N)
$account->folders;           // All folders
$account->messages;          // All messages
$account->scheduledEmails;   // Scheduled emails

// EmailAccountMessage (N:M)
$message->folders;           // Associated folders
$message->addresses;         // Email addresses
$message->headers;           // Technical headers
$message->linkClicks;        // Click analytics

// EmailAccountFolder (Tree)
$folder->parent;             // Parent folder
$folder->children;           // Child folders
$folder->messages;           // Folder messages
```

---

🧪 Testing
---------

[](#-testing)

### Running Tests

[](#running-tests)

```
# All tests (173 tests, 566 assertions)
vendor/bin/phpunit

# Specific test suites
vendor/bin/phpunit --testsuite=Unit     # Unit tests only
vendor/bin/phpunit --testsuite=Feature  # Feature tests only

# With coverage report
vendor/bin/phpunit --coverage-html coverage
```

### Using Test Factories

[](#using-test-factories)

```
use Turahe\MailClient\Tests\Factories\EmailAccountFactory;

// Create test account
$account = EmailAccountFactory::new()->create([
    'email' => 'test@example.com'
]);

// Create account with related data
$account = EmailAccountFactory::new()
    ->withMessages(10)      // 10 messages
    ->withFolders(5)        // 5 folders
    ->create();

// Create specific message
$message = EmailAccountMessageFactory::new()
    ->forAccount($account)
    ->create([
        'subject' => 'Test Message',
        'from_address' => 'sender@example.com'
    ]);
```

---

📖 API Reference
---------------

[](#-api-reference)

**EmailAccount Methods**```
// Connection management
$account->testConnection(): bool
$account->createClient(): Client

// Sync control
$account->enableSync(): void
$account->disableSync(): void
$account->isSyncDisabled(): bool

// Statistics
$account->getStats(): array
$account->getUnreadCount(): int

// Token management (OAuth accounts)
$account->refreshAccessToken(): void
$account->isTokenExpired(): bool
```

**EmailAccountMessage Methods**```
// Status management
$message->markAsRead(): void
$message->markAsUnread(): void
$message->isRead(): bool

// Organization
$message->moveToFolder(EmailAccountFolder $folder): void
$message->addToFolders(array $folders): void
$message->removeFromFolder(EmailAccountFolder $folder): void

// Lifecycle
$message->archive(): void
$message->trash(): void
$message->restore(): void
$message->purge(): void

// Content access
$message->getHtmlBody(): string
$message->getTextBody(): string
$message->hasAttachments(): bool
```

**PredefinedMailTemplate Methods**```
// Template processing
$template->process(array $variables): array
$template->getProcessedSubject(array $variables): string
$template->getProcessedBody(array $variables): string

// Sharing
$template->makeShared(): void
$template->makePrivate(): void
$template->isShared(): bool
```

---

🐛 Troubleshooting
-----------------

[](#-troubleshooting)

**Connection Issues****Problem**: Connection timeout errors

```
// Solution: Increase timeout settings
'imap_timeout' => 60,  // seconds
'smtp_timeout' => 30,  // seconds
```

**Problem**: SSL certificate errors

```
// Solution: Disable SSL verification (development only)
'imap_options' => [
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false,
    ]
]
```

**Memory Issues****Problem**: Memory exhaustion with large attachments

```
// Solution 1: Increase memory limit
ini_set('memory_limit', '512M');

// Solution 2: Use streaming
$attachment->streamToFile('/path/to/destination');

// Solution 3: Process in chunks
$account->messages()->chunk(50, function ($messages) {
    // Process 50 messages at a time
});
```

**OAuth Token Issues****Problem**: Expired access tokens

```
// Solution: Automatic token refresh
if ($account->isTokenExpired()) {
    $account->refreshAccessToken();
}

// Or handle in exception
try {
    $client->getMessages();
} catch (UnauthorizedException $e) {
    $account->refreshAccessToken();
    $client->getMessages(); // Retry
}
```

---

🛠️ Contributing
---------------

[](#️-contributing)

We welcome contributions! Here's how to get started:

### Development Setup

[](#development-setup)

```
# Clone and setup
git clone https://github.com/turahe/mail-client.git
cd mail-client
composer install

# Prepare testing
cp phpunit.xml.dist phpunit.xml
vendor/bin/phpunit

# Start coding!
```

### Contribution Process

[](#contribution-process)

1. **Fork** the repository
2. **Create** feature branch (`git checkout -b feature/amazing-feature`)
3. **Write** tests for your changes
4. **Ensure** all tests pass (`vendor/bin/phpunit`)
5. **Commit** your changes (`git commit -m 'Add amazing feature'`)
6. **Push** to branch (`git push origin feature/amazing-feature`)
7. **Open** a Pull Request

### Code Standards

[](#code-standards)

- ✅ **PHP 8.4+** type declarations
- ✅ **PSR-12** coding standards
- ✅ **100% test coverage** for new features
- ✅ **PHPStan level 8** compliance
- ✅ **Clear documentation** for public methods

---

📞 Support
---------

[](#-support)

- 📧 **Email**:
- 🐛 **Issues**: [GitHub Issues](https://github.com/turahe/mail-client/issues)
- 📖 **Wiki**: [Documentation](https://github.com/turahe/mail-client/wiki)
- 💬 **Discussions**: [GitHub Discussions](https://github.com/turahe/mail-client/discussions)

---

📄 License
---------

[](#-license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

📈 Changelog
-----------

[](#-changelog)

See [CHANGELOG.md](CHANGELOG.md) for version history and updates.

---

**Built with ❤️ for the Laravel community**

[⭐ Star us on GitHub](https://github.com/turahe/mail-client) • [📦 View on Packagist](https://packagist.org/packages/turahe/mailclient)

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance60

Regular maintenance activity

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~45 days

Total

6

Last Release

256d ago

PHP version history (3 changes)v1.0.1PHP ^8.2

v1.0.2PHP ^8.3

v1.1.0PHP ^8.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/f3513bd6100438bcb8c6b1a7e241a66e1ddaf1c11ee33883e06ef4a2784120db?d=identicon)[turahe](/maintainers/turahe)

---

Top Contributors

[![turahe](https://avatars.githubusercontent.com/u/6832622?v=4)](https://github.com/turahe "turahe (47 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/turahe-mailclient/health.svg)

```
[![Health](https://phpackages.com/badges/turahe-mailclient/health.svg)](https://phpackages.com/packages/turahe-mailclient)
```

###  Alternatives

[beyondcode/laravel-mailbox

Handle incoming emails in your Laravel application.

1.1k1.0M4](/packages/beyondcode-laravel-mailbox)[magento/community-edition

Magento 2 (Open Source)

12.1k52.1k10](/packages/magento-community-edition)[spatie/laravel-ray

Easily debug Laravel apps

31738.4M2.8k](/packages/spatie-laravel-ray)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)[jason-munro/cypht

Lightweight Open Source webmail written in PHP and JavaScript

1.5k146.0k](/packages/jason-munro-cypht)[wheelpros/fitment-platform-api

Magento 2 (Open Source)

12.1k1.2k](/packages/wheelpros-fitment-platform-api)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
