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

Laravel Mailboxlayer Laravel Package

ashallendesign/laravel-mailboxlayer

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ashallendesign/laravel-mailboxlayer
    

    Publish the config file:

    php artisan vendor:publish --provider="AshAllenDesign\MailboxLayer\MailboxLayerServiceProvider"
    

    Add your MailboxLayer API key to .env:

    MAILBOXLAYER_API_KEY=your_api_key_here
    
  2. First Use Case: Validate an email address in a registration form:

    use AshAllenDesign\MailboxLayer\Facades\MailboxLayer;
    
    $email = 'user@example.com';
    $result = MailboxLayer::validate($email);
    
    if ($result->isValid()) {
        // Proceed with registration
    } else {
        // Handle invalid email (e.g., show error)
    }
    
  3. Key Files to Review:

    • config/mailboxlayer.php (configuration options)
    • app/Providers/MailboxLayerServiceProvider.php (service binding)
    • app/Exceptions/Handler.php (error handling, if needed)

Implementation Patterns

Common Workflows

1. Email Validation in Registration

public function register(Request $request)
{
    $validated = $request->validate([
        'email' => 'required|email',
    ]);

    $validation = MailboxLayer::validate($validated['email']);

    if (!$validation->isValid()) {
        return back()->withErrors(['email' => 'Invalid email address']);
    }

    // Proceed with user creation
}

2. Bulk Email Validation

public function validateEmails(array $emails)
{
    $results = MailboxLayer::validate($emails);

    return collect($results)->map(function ($result) {
        return [
            'email' => $result->email,
            'valid' => $result->isValid(),
            'reason' => $result->reason ?? null,
        ];
    });
}

3. Integration with Laravel Validation

Extend Laravel’s validation rules:

use AshAllenDesign\MailboxLayer\Rules\MailboxLayerValidation;

$request->validate([
    'email' => ['required', 'email', new MailboxLayerValidation],
]);

4. Caching Responses (Optional)

Cache API responses to reduce calls:

$cacheKey = 'mailboxlayer_' . md5($email);
$validation = Cache::remember($cacheKey, now()->addHours(1), function () use ($email) {
    return MailboxLayer::validate($email);
});

Integration Tips

  1. Rate Limiting:

    • MailboxLayer has API rate limits. Implement retries or queue delayed jobs for bulk validations:
    MailboxLayer::validate($email)->retry(3, 1000); // Retry 3 times with 1s delay
    
  2. Async Validation: Use Laravel Queues for non-critical validations (e.g., background email checks):

    ValidateEmailJob::dispatch($email);
    
  3. Logging: Log validation results for analytics:

    \Log::info('MailboxLayer validation', [
        'email' => $email,
        'valid' => $validation->isValid(),
        'reason' => $validation->reason,
    ]);
    
  4. Fallback Logic: Combine with Laravel’s built-in validation for resilience:

    if (!Filter::isValid($email) || !$validation->isValid()) {
        // Reject
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Management:

    • Never hardcode the API key. Always use .env and restrict access to the file.
    • Rotate keys periodically and update them in .env.
  2. Rate Limits:

    • MailboxLayer’s free tier has strict limits (e.g., 100 requests/day). Monitor usage via their dashboard.
    • Error: 429 Too Many Requests → Implement exponential backoff or queue delays.
  3. Caching Caveats:

    • Cache invalidations: If an email’s validity changes (e.g., disposable inbox expires), cached results may stale.
    • Use short TTLs (e.g., 1 hour) for disposable email checks.
  4. Disposable Email Detection:

    • MailboxLayer flags disposable emails (e.g., temp-mail.org). Handle these cases explicitly:
    if ($validation->isDisposable()) {
        return back()->withErrors(['email' => 'Disposable emails are not allowed.']);
    }
    
  5. Network Issues:

    • The package uses Guzzle under the hood. Handle timeouts explicitly:
    MailboxLayer::setTimeout(30); // 30 seconds
    

Debugging

  1. Enable Debug Mode:

    MailboxLayer::setDebug(true); // Logs raw API responses
    

    Check logs for errors like:

    • Connection refused → Proxy/firewall blocking requests.
    • Invalid API key → Verify .env and MailboxLayer dashboard.
  2. Mocking for Tests: Use Laravel’s HTTP mocking to test without hitting the API:

    $this->mock(MailboxLayer::class)->shouldReceive('validate')
        ->once()
        ->andReturn(new \AshAllenDesign\MailboxLayer\Validation('test@example.com', true));
    
  3. Common Errors:

    Error Solution
    InvalidArgumentException Check API key format (should be 32-character alphanumeric).
    GuzzleException Increase timeout or check network connectivity.
    ValidationException Handle isValid() and reason properties in your logic.

Extension Points

  1. Custom Validation Logic: Extend the Validation class to add domain-specific rules:

    namespace App\Services;
    
    use AshAllenDesign\MailboxLayer\Validation as BaseValidation;
    
    class CustomValidation extends BaseValidation
    {
        public function isAllowedDomain()
        {
            return str_ends_with($this->email, '@yourdomain.com');
        }
    }
    
  2. Webhook Integration: Use MailboxLayer’s webhooks to validate emails in real-time (requires additional setup):

    • Configure webhook endpoints in the MailboxLayer dashboard.
    • Handle incoming webhooks in Laravel:
    Route::post('/mailboxlayer-webhook', function (Request $request) {
        \Log::info('Webhook received', $request->all());
        // Process validation result
    });
    
  3. Batch Processing: For large datasets, use chunking to avoid rate limits:

    $emails = User::pluck('email');
    $chunkSize = 20;
    foreach (array_chunk($emails, $chunkSize) as $chunk) {
        MailboxLayer::validate($chunk);
        sleep(2); // Respect rate limits
    }
    
  4. Fallback Providers: Implement a fallback to another service (e.g., Hunter.io) if MailboxLayer fails:

    try {
        $validation = MailboxLayer::validate($email);
    } catch (\Exception $e) {
        $validation = FallbackValidator::validate($email);
    }
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope