Tutorials

Laravel: Triage Newsletter Imports by Verifying Emails with AI

Laravel: Triage Newsletter Imports by Verifying Emails with AI

A newsletter import should not turn a spreadsheet into a sending list in one step. A plausible address can still have a broken domain, questionable provider signals, or enough delivery risk to deserve a second look. Equally, a temporary validation outage should never become a permanent rejection.

We will build a Laravel command that streams a CSV, checks addresses through the Email Validator API, records durable decisions, and exports uncertain contacts for manual review. Interrupted runs can resume. Authentication failures and exhausted quota pause external checks without discarding contacts.

Get access and copy the service token

  1. Register an account, or sign in.
  2. Open the Email Validator service and plan page, choose an available Free, Plus, or Pro plan, and complete activation.
  3. Open the official documentation. Find the Service token panel and copy the service-scoped token.
  4. Store it in the project’s environment configuration. Regenerating the token revokes the previous active token, so coordinate rotation with running deployments.

This service requires a token. Its exact request is GET https://ai.mihajlo.mk/api/email-validator/v1/check-email, with token and email query parameters. Make one minimal request from a trusted development machine:

curl --get 'https://ai.mihajlo.mk/api/email-validator/v1/check-email' \
  --data-urlencode 'token=YOUR_SERVICE_TOKEN' \
  --data-urlencode '[email protected]'

Query authentication makes URL redaction essential: proxies, monitoring agents, and HTTP debug tooling must not retain the token.

Create a deliberately small import pipeline

Use PHP 8.3+, Composer, Laravel 12, and SQLite for this single-host example. A synchronous Artisan command suits operator-driven imports: it avoids queue infrastructure while preserving checkpoints between requests. Large scheduled imports can later move the same service into jobs.

composer create-project laravel/laravel newsletter-triage "^12.0"
cd newsletter-triage
php artisan make:migration create_newsletter_contacts_table
php artisan make:command TriageNewsletter

Add these values to .env before writing the integration:

EMAIL_VALIDATOR_TOKEN=YOUR_SERVICE_TOKEN
EMAIL_VALIDATOR_ACCEPT_POLICY='{}'

Add this entry inside the array returned by config/services.php:

'email_validator' => [
    'token' => env('EMAIL_VALIDATOR_TOKEN'),
    'policy' => json_decode(
        env('EMAIL_VALIDATOR_ACCEPT_POLICY', '{}'), true
    ) ?: [],
],

The supplied contract names status, score, recommendation, checks, and quota data, but does not specify enum values, score direction, or nested schemas. Inventing those details would make automatic acceptance unsafe.

Our local policy therefore starts empty. After checking the official documentation, configure an object containing status, recommendation, inclusive minimum and maximum score bounds, and a nonempty checks map of documented dot paths to required values. These are application policy keys. Until configured, otherwise valid results enter review.

The project adds three files: the generated migration, app/Services/EmailValidator.php, and app/Console/Commands/TriageNewsletter.php. Tests belong in tests/Feature/EmailValidatorTest.php.

Persist decisions before exporting anything

Replace the generated migration with:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
    public function up(): void
    {
        Schema::create('newsletter_contacts', function (Blueprint $table) {
            $table->id();
            $table->uuid('batch');
            $table->char('address_hash', 64);
            $table->text('email');
            $table->string('state');
            $table->string('reason');
            $table->json('evidence')->nullable();
            $table->timestamps();
            $table->unique(['batch', 'address_hash']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('newsletter_contacts');
    }
};

States distinguish accepted, rejected, review, and deferred. Only local syntax failures are automatically rejected here. Provider results outside the verified acceptance policy require human judgment; operational failures remain retryable.

Keep the HTTP boundary conservative

Create app/Services/EmailValidator.php:

<?php

namespace App\Services;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use LogicException;

final class EmailValidator
{
    public function check(string $email): array
    {
        $token = config('services.email_validator.token');

        if (!is_string($token) || $token === '') {
            throw new LogicException('Email Validator token is missing.');
        }

        for ($attempt = 0; $attempt < 2; $attempt++) {
            try {
                $response = Http::acceptJson()
                    ->connectTimeout(3)
                    ->timeout(8)
                    ->withOptions(['allow_redirects' => false])
                    ->get(
                        'https://ai.mihajlo.mk/api/email-validator/v1/check-email',
                        ['token' => $token, 'email' => $email]
                    );
            } catch (ConnectionException) {
                if ($attempt === 0) {
                    usleep(random_int(250000, 500000));
                    continue;
                }

                return $this->result('deferred', 'transport');
            }

            $http = $response->status();

            if (in_array($http, [500, 502, 503, 504], true)) {
                if ($attempt === 0) {
                    usleep(random_int(250000, 500000));
                    continue;
                }

                return $this->result('deferred', 'upstream');
            }

            if (in_array($http, [401, 403, 429], true)) {
                return $this->result('deferred', 'http_'.$http);
            }

            if ($http !== 200) {
                return $this->result('review', 'unexpected_http_'.$http);
            }

            return $this->map($response->json());
        }

        throw new LogicException('Unreachable retry state.');
    }

    private function map(mixed $data): array
    {
        if (!is_array($data)
            || !is_string($data['status'] ?? null)
            || !is_string($data['recommendation'] ?? null)
            || !is_numeric($data['score'] ?? null)
            || !is_finite((float) $data['score'])
            || !is_array($data['checks'] ?? null)
            || !is_array($data['quota'] ?? null)) {
            return $this->result('review', 'unexpected_schema');
        }

        $evidence = Arr::only($data, [
            'status', 'score', 'recommendation', 'checks', 'quota',
        ]);

        $policy = config('services.email_validator.policy', []);
        $configured = is_array($policy)
            && is_string($policy['status'] ?? null)
            && is_string($policy['recommendation'] ?? null)
            && is_numeric($policy['minimum'] ?? null)
            && is_numeric($policy['maximum'] ?? null)
            && is_array($policy['checks'] ?? null)
            && $policy['checks'] !== [];

        if (!$configured) {
            return $this->result('review', 'policy_missing', $evidence);
        }

        $matches = $data['status'] === $policy['status']
            && $data['recommendation'] === $policy['recommendation']
            && (float) $data['score'] >= (float) $policy['minimum']
            && (float) $data['score'] <= (float) $policy['maximum'];

        foreach ($policy['checks'] as $path => $expected) {
            $matches = $matches
                && Arr::has($data['checks'], (string) $path)
                && Arr::get($data['checks'], (string) $path) === $expected;
        }

        return $this->result(
            $matches ? 'accepted' : 'review',
            $matches ? 'policy_match' : 'policy_mismatch',
            $evidence
        );
    }

    private function result(
        string $state,
        string $reason,
        array $evidence = []
    ): array {
        Log::info('newsletter.validation', compact('state', 'reason'));

        return compact('state', 'reason', 'evidence');
    }
}

The array requirements for checks and quota are explicit adapter expectations, not claims about undocumented nested fields. An incompatible response goes to review. Quota evidence accompanies each decision; HTTP 429 suspends subsequent calls. Add proactive quota suspension only after confirming the documented quota representation.

Retries cover connection failures and selected server errors, with one short randomized backoff. Authentication and other client errors are never blindly retried. A lost response can still consume quota, so checkpointing cannot guarantee exactly one billable check.

Stream, checkpoint, and produce the review list

Replace the generated command with:

<?php

namespace App\Console\Commands;

use App\Services\EmailValidator;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use RuntimeException;

final class TriageNewsletter extends Command
{
    protected $signature =
        'newsletter:triage {file} {--batch=} {--review=}';

    protected $description = 'Triage a newsletter CSV safely';

    public function handle(EmailValidator $validator): int
    {
        $batch = $this->option('batch');
        $review = $this->option('review');

        if (!is_string($batch) || !Str::isUuid($batch)
            || !is_string($review) || $review === '') {
            $this->error('Supply --batch=UUID and --review=PATH.');
            return self::FAILURE;
        }

        $input = fopen($this->argument('file'), 'rb');
        if ($input === false) {
            throw new RuntimeException('Cannot open input.');
        }

        $paused = false;

        try {
            $header = fgetcsv($input, 0, ',', '"', '');
            if ($header !== ['email']) {
                throw new RuntimeException('Expected one column: email');
            }

            while (($row = fgetcsv($input, 0, ',', '"', '')) !== false) {
                if (count($row) !== 1) {
                    throw new RuntimeException('Expected one field per row.');
                }

                $email = trim((string) $row[0]);
                $hash = hash('sha256', $email);
                $key = ['batch' => $batch, 'address_hash' => $hash];
                $existing = DB::table('newsletter_contacts')
                    ->where($key)->first();

                if ($existing && $existing->state !== 'deferred') {
                    continue;
                }

                if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
                    $result = [
                        'state' => 'rejected',
                        'reason' => 'local_syntax',
                        'evidence' => [],
                    ];
                } elseif ($paused) {
                    $result = [
                        'state' => 'deferred',
                        'reason' => 'batch_paused',
                        'evidence' => [],
                    ];
                } else {
                    $result = $validator->check($email);
                    $paused = $result['state'] === 'deferred';
                }

                DB::table('newsletter_contacts')->updateOrInsert($key, [
                    'email' => $email,
                    'state' => $result['state'],
                    'reason' => $result['reason'],
                    'evidence' => json_encode(
                        $result['evidence'], JSON_THROW_ON_ERROR
                    ),
                    'created_at' => $existing?->created_at ?? now(),
                    'updated_at' => now(),
                ]);
            }
        } finally {
            fclose($input);
        }

        $output = fopen($review, 'wb');
        if ($output === false) {
            throw new RuntimeException('Cannot open review output.');
        }

        try {
            fputcsv($output, ['email', 'reason'], ',', '"', '');

            foreach (DB::table('newsletter_contacts')
                ->where('batch', $batch)->where('state', 'review')
                ->orderBy('id')->cursor() as $contact) {
                $safe = preg_match('/^[=+\-@\t\r\n]/', $contact->email)
                    ? "'".$contact->email : $contact->email;

                if (fputcsv(
                    $output, [$safe, $contact->reason], ',', '"', ''
                ) === false) {
                    throw new RuntimeException('Review export failed.');
                }
            }
        } finally {
            fclose($output);
        }

        $this->info("Review export: {$review}");
        return $paused ? self::FAILURE : self::SUCCESS;
    }
}

Deduplication preserves local-part spelling; silently lowercasing or rewriting addresses can merge distinct contacts. Reusing the batch UUID skips settled decisions and retries deferred rows. Use an immutable input file per batch.

The export prefixes spreadsheet formula characters, while the database retains the original address. Reviewers should consult stored evidence and record corrections or approval through their existing authorized process. Only accepted records belong in the downstream sending list, and validation never substitutes for subscription consent.

Test decisions and failure boundaries

Create tests/Feature/EmailValidatorTest.php. The following values are synthetic fixtures, not documented provider enums or a claimed score scale.

<?php

namespace Tests\Feature;

use App\Services\EmailValidator;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

final class EmailValidatorTest extends TestCase
{
    public function test_verified_policy_accepts_matching_evidence(): void
    {
        config([
            'services.email_validator.token' => 'TEST_PLACEHOLDER',
            'services.email_validator.policy' => [
                'status' => 'fixture-ok',
                'recommendation' => 'fixture-pass',
                'minimum' => 6,
                'maximum' => 8,
                'checks' => ['fixture_gate' => true],
            ],
        ]);

        Http::preventStrayRequests();
        Http::fake(['ai.mihajlo.mk/*' => Http::response([
            'status' => 'fixture-ok',
            'recommendation' => 'fixture-pass',
            'score' => 7,
            'checks' => ['fixture_gate' => true],
            'quota' => [],
        ])]);

        $result = app(EmailValidator::class)->check('[email protected]');

        $this->assertSame('accepted', $result['state']);
        Http::assertSent(fn ($request) =>
            $request->method() === 'GET'
            && $request['token'] === 'TEST_PLACEHOLDER'
            && $request['email'] === '[email protected]'
        );
    }

    public function test_rate_limit_defers_without_retry(): void
    {
        config(['services.email_validator.token' => 'TEST_PLACEHOLDER']);
        Http::preventStrayRequests();
        Http::fake(['ai.mihajlo.mk/*' => Http::response([], 429)]);

        $result = app(EmailValidator::class)->check('[email protected]');

        $this->assertSame('deferred', $result['state']);
        Http::assertSentCount(1);
    }

    public function test_invalid_response_requires_review(): void
    {
        config(['services.email_validator.token' => 'TEST_PLACEHOLDER']);
        Http::preventStrayRequests();
        Http::fake(['ai.mihajlo.mk/*' => Http::response('broken', 200)]);

        $this->assertSame(
            'review',
            app(EmailValidator::class)->check('[email protected]')['state']
        );
    }
}

Before rollout, extend coverage to exhausted server retries, authentication failures, policy mismatches, duplicate rows, and resuming a deferred batch. Those cases protect the operational contract as much as the happy path.

Deploy and verify the whole import

Run migrations, tests, and the importer. Create an input CSV headed email, with one address per subsequent row. Keep input and output paths distinct.

php artisan migrate
php artisan test
php artisan config:cache

flock -n storage/newsletter-import.lock \
  php artisan newsletter:triage storage/app/private/contacts.csv \
  --batch=90adc492-d9e2-4d48-b92e-0cf71a2e38a7 \
  --review=storage/app/private/review.csv

This deployment command uses the Linux flock utility to serialize imports on one host. Multiple hosts require a shared lock instead. Keep imports, exports, and database backups private, restrict operator access, and define a retention period for addresses and validation evidence.

Monitor decision counts by batch and reason. Alert on deferred results and sudden increases in schema failures. Logs deliberately omit addresses, tokens, URLs, and response bodies. After token rotation, rebuild cached configuration before restarting any long-running application processes.

Common failures have distinct remedies: authentication errors require checking activation and credentials; rate limits require waiting for documented availability; schema failures require inspecting the official response contract; an empty acceptance policy intentionally routes contacts to review.

  • Confirm local syntax failures produce rejected rows without external calls.
  • Confirm uncertain responses appear in the review CSV.
  • Enable acceptance only after verifying policy values against official documentation.
  • Repeat the same batch and confirm settled rows make no additional calls.
  • Simulate HTTP 429 and confirm subsequent valid rows become deferred.
  • Verify downstream selection includes only accepted, consented contacts.

A trustworthy import does more than identify promising addresses. It preserves uncertainty, makes interruptions recoverable, and leaves a clear explanation for every contact that reaches the sending list.

Blog author portrait

Mihajlo

I’m Mihajlo — a developer driven by curiosity, discipline, and the constant urge to create something meaningful. I share insights, tutorials, and free services to help others simplify their work and grow in the ever-evolving world of software and AI.