Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Elasticemail Php Laravel Package

elasticemail/elasticemail-php

PHP client for Elastic Email’s REST API. Authenticate with your API key and manage campaigns and other resources via GET/POST/PUT/DELETE. Supports PHP 7.4+ (incl. 8.0) and uses Guzzle with configurable timeouts and connection limits.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package Add to composer.json:

    "require": {
        "elasticemail/elasticemail-php": "^1.0"
    }
    

    Run composer install.

  2. Configure API Key Set your ElasticEmail API key in config/services.php (or environment variables):

    'elasticemail' => [
        'api_key' => env('ELASTICEMAIL_API_KEY'),
    ],
    

    Or directly in code:

    $config = ElasticEmail\Configuration::getDefaultConfiguration()
        ->setApiKey('X-ElasticEmail-ApiKey', env('ELASTICEMAIL_API_KEY'));
    
  3. First Use Case: Send a Transactional Email

    $apiInstance = new ElasticEmail\Api\EmailsApi(new GuzzleHttp\Client(), $config);
    $body = new \ElasticEmail\Model\SendTransactionalEmailRequest([
        'from' => 'sender@example.com',
        'to' => 'recipient@example.com',
        'subject' => 'Test Email',
        'bodyHtml' => '<h1>Hello!</h1>',
    ]);
    $result = $apiInstance->emailsTransactionalPost($body);
    

Key Files to Explore

  • examples/: Pre-built use cases (e.g., sendTransactionalEmails.php).
  • src/Api/: API classes (e.g., CampaignsApi, ContactsApi).
  • src/Model/: Request/response models (e.g., SendTransactionalEmailRequest).

Implementation Patterns

1. Service Layer Abstraction

Wrap the client in a Laravel service for reusability:

// app/Services/ElasticEmailService.php
class ElasticEmailService {
    protected $client;

    public function __construct() {
        $config = ElasticEmail\Configuration::getDefaultConfiguration()
            ->setApiKey('X-ElasticEmail-ApiKey', config('services.elasticemail.api_key'));
        $this->client = new ElasticEmail\Api\EmailsApi(new GuzzleHttp\Client(), $config);
    }

    public function sendTransactional($data) {
        return $this->client->emailsTransactionalPost($data);
    }
}

Register in AppServiceProvider:

$this->app->singleton(ElasticEmailService::class, function ($app) {
    return new ElasticEmailService();
});

2. Common Workflows

Bulk Emails

// Upload CSV and send
$csv = fopen('contacts.csv', 'r');
$api = new ElasticEmail\Api\EmailsApi($client, $config);
$response = $api->emailsMergefilePost([
    'file' => new \GuzzleHttp\Psr7\Stream(fopen('contacts.csv', 'r')),
    'subject' => 'Bulk Campaign',
    'bodyHtml' => '<p>Hello {name}!</p>',
]);

Campaign Management

// Create and pause a campaign
$campaignApi = new ElasticEmail\Api\CampaignsApi($client, $config);
$campaignApi->campaignsPost(new \ElasticEmail\Model\AddCampaignRequest([
    'name' => 'Welcome Series',
    'subject' => 'Welcome!',
    'bodyHtml' => '<h1>Welcome!</h1>',
    'listName' => 'subscribers',
]));
$campaignApi->campaignsByNamePausePut('Welcome Series');

Contact Management

// Add/update contacts via API
$contactApi = new ElasticEmail\Api\ContactsApi($client, $config);
$contactApi->contactsPost(new \ElasticEmail\Model\AddContactRequest([
    'email' => 'user@example.com',
    'name' => 'John Doe',
    'customFields' => ['signup_date' => '2023-01-01'],
]));

3. Event Handling

Use webhooks (via ElasticEmail dashboard) to trigger Laravel jobs:

// routes/web.php
Route::post('/elasticemail/webhook', [EmailWebhookHandler::class, 'handle']);
// app/Handlers/EmailWebhookHandler.php
class EmailWebhookHandler {
    public function handle(Request $request) {
        $event = $request->json()->all();
        if ($event['type'] === 'email_sent') {
            EmailSentJob::dispatch($event['data']);
        }
    }
}

4. Error Handling

Centralize API errors in a middleware or service:

// app/Exceptions/Handler.php
public function render($request, Throwable $exception) {
    if ($exception instanceof \ElasticEmail\ApiException) {
        return response()->json([
            'error' => 'ElasticEmail API Error',
            'details' => $exception->getResponseBody(),
        ], 400);
    }
    return parent::render($request, $exception);
}

Gotchas and Tips

1. Rate Limits & Timeouts

  • Concurrency Limit: 20 concurrent requests. Use Laravel queues for bulk operations:
    foreach ($contacts as $contact) {
        SendEmailJob::dispatch($contact);
    }
    
  • Timeout: 600 seconds per request. For long-running tasks (e.g., exports), poll status:
    $exportId = $contactApi->contactsExportPost($criteria);
    while (true) {
        $status = $contactApi->contactsExportByIdStatusGet($exportId);
        if ($status->getStatus() === 'completed') break;
        sleep(5);
    }
    

2. API Key Management

  • Security: Never hardcode keys. Use Laravel’s .env:
    ELASTICEMAIL_API_KEY=your_key_here
    
  • Rotation: Use the SecurityApi to generate/rotate keys programmatically:
    $securityApi = new ElasticEmail\Api\SecurityApi($client, $config);
    $newKey = $securityApi->securityApikeysPost(new \ElasticEmail\Model\AddApiKeyRequest([
        'name' => 'Laravel App Key',
        'accessLevel' => 'full_access',
    ]));
    

3. CSV/Attachment Handling

  • Bulk Uploads: Use GuzzleHttp\Psr7\Stream for file uploads:
    $file = new \GuzzleHttp\Psr7\Stream(fopen('file.csv', 'r'));
    $api->contactsImportPost(['file' => $file]);
    
  • Validation: Validate CSV format before upload to avoid API errors.

4. Debugging

  • Enable Guzzle Logging:
    $client = new GuzzleHttp\Client([
        'handler' => GuzzleHttp\HandlerStack::create(new GuzzleHttp\Handler\CurlHandler()),
        'debug' => true,
    ]);
    
  • Check Response Codes: ElasticEmail uses HTTP status codes (e.g., 400 for invalid requests).

5. Laravel-Specific Tips

  • Service Container: Bind the client to the container for dependency injection:
    $this->app->bind(ElasticEmail\Api\EmailsApi::class, function ($app) {
        return new ElasticEmail\Api\EmailsApi(
            new GuzzleHttp\Client(),
            ElasticEmail\Configuration::getDefaultConfiguration()
                ->setApiKey('X-ElasticEmail-ApiKey', config('services.elasticemail.api_key'))
        );
    });
    
  • Testing: Mock the API in tests:
    $mock = Mockery::mock(ElasticEmail\Api\EmailsApi::class);
    $mock->shouldReceive('emailsTransactionalPost')
         ->once()
         ->andReturn(new \ElasticEmail\Model\SendTransactionalEmailResponse());
    $this->app->instance(ElasticEmail\Api\EmailsApi::class, $mock);
    

6. Common Pitfalls

  • Case Sensitivity: Campaign/list names are case-sensitive.
  • Async Operations: Exports/bulk sends are async. Always check status.
  • Field Limits: Custom fields have a 100-character limit. Validate before sending.
  • Webhook Signatures: Verify ElasticEmail webhook payloads using the X-ElasticEmail-Signature header.

7. Extending the Package

  • Custom Models: Extend ElasticEmail\Model classes for additional validation:
    class ExtendedContactRequest extends \ElasticEmail\Model\AddContactRequest {
        public function setCustomFields(array $fields) {
            $this->customFields = array_filter($fields, fn($v) => strlen($v) <= 100);
            return $this;
        }
    }
    
  • Retry Logic: Implement exponential backoff for rate-limited requests:
    use Symfony\Component\HttpClient\RetryStrategy;
    
    $client = new GuzzleHttp\Client([
        'handler' => HandlerStack::create(new RetryHandler([
            'max_retries' => 3,
            'delay' => 100,
            'max_delay' => 1000,
        ])),
    ]);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky