ashallendesign/laravel-mailboxlayer
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
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)
}
Key Files to Review:
config/mailboxlayer.php (configuration options)app/Providers/MailboxLayerServiceProvider.php (service binding)app/Exceptions/Handler.php (error handling, if needed)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
}
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,
];
});
}
Extend Laravel’s validation rules:
use AshAllenDesign\MailboxLayer\Rules\MailboxLayerValidation;
$request->validate([
'email' => ['required', 'email', new MailboxLayerValidation],
]);
Cache API responses to reduce calls:
$cacheKey = 'mailboxlayer_' . md5($email);
$validation = Cache::remember($cacheKey, now()->addHours(1), function () use ($email) {
return MailboxLayer::validate($email);
});
Rate Limiting:
MailboxLayer::validate($email)->retry(3, 1000); // Retry 3 times with 1s delay
Async Validation: Use Laravel Queues for non-critical validations (e.g., background email checks):
ValidateEmailJob::dispatch($email);
Logging: Log validation results for analytics:
\Log::info('MailboxLayer validation', [
'email' => $email,
'valid' => $validation->isValid(),
'reason' => $validation->reason,
]);
Fallback Logic: Combine with Laravel’s built-in validation for resilience:
if (!Filter::isValid($email) || !$validation->isValid()) {
// Reject
}
API Key Management:
.env and restrict access to the file..env.Rate Limits:
429 Too Many Requests → Implement exponential backoff or queue delays.Caching Caveats:
Disposable Email Detection:
temp-mail.org). Handle these cases explicitly:if ($validation->isDisposable()) {
return back()->withErrors(['email' => 'Disposable emails are not allowed.']);
}
Network Issues:
MailboxLayer::setTimeout(30); // 30 seconds
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.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));
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. |
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');
}
}
Webhook Integration: Use MailboxLayer’s webhooks to validate emails in real-time (requires additional setup):
Route::post('/mailboxlayer-webhook', function (Request $request) {
\Log::info('Webhook received', $request->all());
// Process validation result
});
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
}
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);
}
How can I help you explore Laravel packages today?