PHP SDK

Modern PHP SDK with PSR-4 autoloading, Composer support, and seamless Laravel/Symfony integration.

✅ Ready v1.0.0 PSR-4

Quick Start

Installation

# Install via Composer
composer require sparkmailr/php-sdk

Basic Usage

<?php
require_once 'vendor/autoload.php';

use SparkMailr\SparkMailrClient;
use SparkMailr\Exceptions\SparkMailrException;

// Initialize client
$client = new SparkMailrClient([
    'api_key' => 'your-api-key'
]);

try {
    // Send email
    $response = $client->emails->send([
        'to' => ['user@example.com'],
        'from' => 'noreply@yourapp.com',
        'subject' => 'Welcome to SparkMailr!',
        'html' => '<h1>Hello World</h1>',
        'text' => 'Hello World'
    ]);
    
    echo "Email sent: " . $response['id'];
} catch (SparkMailrException $e) {
    echo "Error: " . $e->getMessage();
}

Configuration

<?php
use SparkMailr\SparkMailrClient;

// Full configuration
$client = new SparkMailrClient([
    'api_key' => 'your-api-key',
    'base_url' => 'https://api.sparkmailr.com',  // Optional
    'timeout' => 30,                             // Request timeout in seconds
    'max_retries' => 3,                          // Max retry attempts
    'retry_delay' => 1,                          // Delay between retries
    'debug' => false                             // Enable debug mode
]);

// Environment-based configuration
$client = new SparkMailrClient([
    'api_key' => $_ENV['SPARKMAILR_API_KEY'],
    'debug' => $_ENV['APP_DEBUG'] ?? false
]);

Laravel Integration

Service Provider Setup

// config/services.php
'sparkmailr' => [
    'api_key' => env('SPARKMAILR_API_KEY'),
    'base_url' => env('SPARKMAILR_BASE_URL', 'https://api.sparkmailr.com'),
],

// .env
SPARKMAILR_API_KEY=your-api-key

// app/Providers/AppServiceProvider.php
use SparkMailr\SparkMailrClient;

public function register()
{
    $this->app->singleton(SparkMailrClient::class, function ($app) {
        return new SparkMailrClient(config('services.sparkmailr'));
    });
}

Controller Usage

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use SparkMailr\SparkMailrClient;

class EmailController extends Controller
{
    private $sparkMailr;
    
    public function __construct(SparkMailrClient $sparkMailr)
    {
        $this->sparkMailr = $sparkMailr;
    }
    
    public function sendWelcomeEmail(Request $request)
    {
        try {
            $response = $this->sparkMailr->emails->send([
                'to' => [$request->user()->email],
                'from' => 'noreply@yourapp.com',
                'template_id' => 'welcome-template',
                'template_data' => [
                    'name' => $request->user()->name,
                    'activation_url' => route('activate', $request->user()->id)
                ]
            ]);
            
            return response()->json([
                'success' => true,
                'email_id' => $response['id']
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ], 500);
        }
    }
}

Laravel Mail Integration

<?php
namespace App\Mail;

use Illuminate\Mail\Mailable;
use SparkMailr\SparkMailrClient;

class WelcomeMail extends Mailable
{
    private $sparkMailr;
    private $userData;
    
    public function __construct(SparkMailrClient $sparkMailr, $userData)
    {
        $this->sparkMailr = $sparkMailr;
        $this->userData = $userData;
    }
    
    public function build()
    {
        // Send via SparkMailr instead of Laravel's mail driver
        $response = $this->sparkMailr->emails->send([
            'to' => [$this->userData['email']],
            'from' => config('mail.from.address'),
            'template_id' => 'welcome-template',
            'template_data' => $this->userData
        ]);
        
        return $this;
    }
}

Advanced Features

Template Emails

<?php
// Send email with template
$response = $client->emails->send([
    'to' => ['user@example.com'],
    'from' => 'noreply@yourapp.com',
    'template_id' => 'welcome-template',
    'template_data' => [
        'name' => 'John Doe',
        'activation_link' => 'https://app.example.com/activate/123',
        'company' => 'Acme Corp'
    ]
]);

echo "Template email sent: " . $response['id'];

Bulk Email Sending

<?php
// Send bulk emails
$recipients = [
    [
        'to' => 'user1@example.com',
        'template_data' => ['name' => 'User 1', 'code' => 'ABC123']
    ],
    [
        'to' => 'user2@example.com',
        'template_data' => ['name' => 'User 2', 'code' => 'DEF456']
    ]
];

$response = $client->emails->sendBulk([
    'from' => 'newsletter@yourapp.com',
    'template_id' => 'newsletter-template',
    'recipients' => $recipients
]);

echo "Bulk batch: " . $response['batch_id'];

Email Tracking & Analytics

<?php
// Get email status
$emailId = 'em_1234567890';
$status = $client->emails->getStatus($emailId);

echo "Status: " . $status['status'] . "\n";
echo "Delivered: " . $status['delivered_at'] . "\n";

// Get analytics
$analytics = $client->analytics->getEmailStats([
    'start_date' => '2025-01-01',
    'end_date' => '2025-01-31'
]);

echo "Total sent: " . $analytics['sent'] . "\n";
echo "Delivery rate: " . $analytics['delivery_rate'] . "%\n";
echo "Open rate: " . $analytics['open_rate'] . "%\n";

Symfony Integration

# config/services.yaml
services:
    SparkMailr\SparkMailrClient:
        arguments:
            $config:
                api_key: '%env(SPARKMAILR_API_KEY)%'
                base_url: '%env(SPARKMAILR_BASE_URL)%'

# Controller usage
<?php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use SparkMailr\SparkMailrClient;

class EmailController extends AbstractController
{
    private $sparkMailr;
    
    public function __construct(SparkMailrClient $sparkMailr)
    {
        $this->sparkMailr = $sparkMailr;
    }
    
    public function sendEmail()
    {
        $response = $this->sparkMailr->emails->send([
            'to' => ['user@example.com'],
            'from' => 'noreply@yourapp.com',
            'subject' => 'Hello from Symfony',
            'html' => '<p>This is a test email</p>'
        ]);
        
        return $this->json(['email_id' => $response['id']]);
    }
}

Error Handling

<?php
use SparkMailr\Exceptions\{
    SparkMailrException,
    AuthenticationException,
    RateLimitException,
    ValidationException
};

try {
    $response = $client->emails->send([
        'to' => ['invalid-email'],
        'from' => 'noreply@yourapp.com',
        'subject' => 'Test Email'
    ]);
} catch (AuthenticationException $e) {
    echo "Authentication failed: " . $e->getMessage();
} catch (RateLimitException $e) {
    echo "Rate limited. Retry after: " . $e->getRetryAfter() . " seconds";
} catch (ValidationException $e) {
    echo "Validation failed:\n";
    foreach ($e->getValidationErrors() as $field => $errors) {
        echo "  $field: " . implode(', ', $errors) . "\n";
    }
} catch (SparkMailrException $e) {
    echo "SparkMailr error: " . $e->getMessage();
} catch (\Exception $e) {
    echo "Unexpected error: " . $e->getMessage();
}

Testing with PHPUnit

<?php
use PHPUnit\Framework\TestCase;
use SparkMailr\SparkMailrClient;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;

class SparkMailrTest extends TestCase
{
    public function testSendEmailSuccess()
    {
        // Mock HTTP client
        $mock = new MockHandler([
            new Response(200, [], json_encode([
                'id' => 'em_123456',
                'status' => 'queued'
            ]))
        ]);
        
        $handlerStack = HandlerStack::create($mock);
        
        $client = new SparkMailrClient([
            'api_key' => 'test-key',
            'http_handler' => $handlerStack
        ]);
        
        $response = $client->emails->send([
            'to' => ['test@example.com'],
            'from' => 'noreply@test.com',
            'subject' => 'Test Email',
            'html' => '<p>Test content</p>'
        ]);
        
        $this->assertEquals('em_123456', $response['id']);
        $this->assertEquals('queued', $response['status']);
    }
    
    public function testRateLimitHandling()
    {
        $mock = new MockHandler([
            new Response(429, [], json_encode([
                'error' => 'Rate limit exceeded',
                'retry_after' => 60
            ]))
        ]);
        
        $client = new SparkMailrClient([
            'api_key' => 'test-key',
            'http_handler' => HandlerStack::create($mock)
        ]);
        
        $this->expectException(\SparkMailr\Exceptions\RateLimitException::class);
        
        $client->emails->send([
            'to' => ['test@example.com'],
            'from' => 'noreply@test.com',
            'subject' => 'Test'
        ]);
    }
}

// Run tests: ./vendor/bin/phpunit

Need More Help?

Complete Documentation Packagist Contact Support