PHP code example of pyzit / tempmail

1. Go to this page and download the library: Download pyzit/tempmail library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pyzit / tempmail example snippets


$client = new TempMailClient('YOUR_API_TOKEN');
$result = $client->check('[email protected]');

if ($result->isDisposable) {
    throw new \RuntimeException('Disposable emails are not allowed.');
}



yzit\TempMail\TempMailClient;

$client = new TempMailClient('YOUR_API_TOKEN');

$result = $client->check('[email protected]');

echo $result->email;        // "[email protected]"
echo $result->isDisposable; // false
echo $result->status;       // "clean"
echo $result->isClean();    // true

$client = new TempMailClient('YOUR_API_TOKEN');

$client = new TempMailClient($_ENV['PYZIT_TOKEN']);
// or
$client = new TempMailClient(getenv('PYZIT_TOKEN'));

$result = $client->check('[email protected]');

$result = $client->check('[email protected]');

echo $result->email;         // "[email protected]"
echo $result->isDisposable;  // true
echo $result->status;        // "disposable"
echo $result->isClean();     // false  (convenience method)

$result = $client->detailed('[email protected]');

$result = $client->detailed('[email protected]');

echo $result->reputationScore;  // 0.0 – 1.0
echo $result->riskLevel;        // "low" | "medium" | "high"
echo $result->recommendation;   // "accept" | "review" | "reject"

if ($result->shouldReject()) {
    throw new \RuntimeException('Email rejected: ' . $result->riskLevel);
}

// DNS intelligence
$dns = $result->details->dnsIntelligence;
echo $dns->hasMx;     // true/false
echo $dns->hasSpf;    // true/false
echo $dns->hasDmarc;  // true/false

foreach ($dns->mxRecords as $mx) {
    echo $mx->priority;    // 5
    echo $mx->exchange;    // "mail.example.com"
    echo implode(', ', $mx->ips); // "1.2.3.4"
}

// Signals — what triggered the result
$signals = $result->details->signals;
print_r($signals->positive); // ["established_domain", "has_spf"]
print_r($signals->negative); // ["no_mx_records", "new_domain"]
print_r($signals->neutral);  // ["limited_history"]

// Domain stability
$stability = $result->details->stability;
echo $stability->domainAgeDays;   // 0
echo $stability->isNewDomain;     // true
echo $stability->stabilityScore;  // 0.0 – 1.0
print_r($stability->riskFactors); // ["newly_observed_domain"]

$result = $client->bulk(['[email protected]', '[email protected]', '[email protected]']);

$result = $client->bulk([
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
]);

echo $result->processed; // 4

// Full map: email → is_disposable
var_dump($result->results);
// [
//   "[email protected]"       => false,
//   "[email protected]" => true,
//   "[email protected]" => false,
//   "[email protected]" => true,
// ]

// Convenience helpers
$blocked = $result->disposableEmails(); // ["[email protected]", "[email protected]"]
$allowed = $result->cleanEmails();      // ["[email protected]", "[email protected]"]

use Pyzit\TempMail\Exceptions\PyzitException;
use Pyzit\TempMail\Exceptions\AuthenticationException;
use Pyzit\TempMail\Exceptions\ScopeException;
use Pyzit\TempMail\Exceptions\PlanRequiredException;
use Pyzit\TempMail\Exceptions\RateLimitException;
use Pyzit\TempMail\Exceptions\ApiException;
use Pyzit\TempMail\Exceptions\TimeoutException;

try {
    $result = $client->check('[email protected]');
} catch (AuthenticationException $e) {
    // HTTP 401 — invalid or missing API token
    // Fix: check your token in the Pyzit dashboard
    log_error($e->getMessage());

} catch (ScopeException $e) {
    // HTTP 403 — token is missing a  implement retry logic
    log_error('Request timed out');

} catch (ApiException $e) {
    // Unexpected HTTP error (5xx, unknown 4xx)
    log_error('API error ' . $e->getStatusCode() . ': ' . $e->getResponseBody());

} catch (PyzitException $e) {
    // Catch-all for any other SDK error
    log_error($e->getMessage());
}

function isEmailAllowed(TempMailClient $client, string $email): bool
{
    try {
        $result = $client->check($email);
        return !$result->isDisposable;
    } catch (PyzitException) {
        // API error — let the request through rather than blocking real users
        return true;
    }
}

// AppServiceProvider::register()
$this->app->singleton(TempMailClient::class, fn() =>
    new TempMailClient(config('services.pyzit.token'))
);


// app/Http/Middleware/BlockDisposableEmails.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Pyzit\TempMail\TempMailClient;
use Pyzit\TempMail\Exceptions\PyzitException;

class BlockDisposableEmails
{
    public function __construct(private TempMailClient $client) {}

    public function handle(Request $request, Closure $next): mixed
    {
        $email = $request->input('email');

        if ($email) {
            try {
                $r = $this->client->check($email);
                if ($r->isDisposable) {
                    return response()->json(
                        ['message' => 'Disposable email addresses are not allowed.'],
                        422
                    );
                }
            } catch (PyzitException) {
                // Fail open — API issues should never block real users
            }
        }

        return $next($request);
    }
}


// app/Rules/NotDisposableEmail.php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Pyzit\TempMail\TempMailClient;
use Pyzit\TempMail\Exceptions\PyzitException;

class NotDisposableEmail implements ValidationRule
{
    public function __construct(private TempMailClient $client) {}

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        try {
            $r = $this->client->check((string) $value);
            if ($r->isDisposable) {
                $fail('Disposable email addresses are not allowed.');
            }
        } catch (PyzitException) {
            // Fail open
        }
    }
}

// Usage in a form request:
// 'email' => ['


// src/Validator/NotDisposableEmailValidator.php

namespace App\Validator;

use Pyzit\TempMail\TempMailClient;
use Pyzit\TempMail\Exceptions\PyzitException;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class NotDisposableEmailValidator extends ConstraintValidator
{
    public function __construct(private TempMailClient $client) {}

    public function validate(mixed $value, Constraint $constraint): void
    {
        if (null === $value || '' === $value) {
            return;
        }

        try {
            $r = $this->client->check((string) $value);
            if ($r->isDisposable) {
                $this->context
                    ->buildViolation($constraint->message)
                    ->addViolation();
            }
        } catch (PyzitException) {
            // Fail open — do not block submissions when the API is unavailable
        }
    }
}



yzit\TempMail\TempMailClient;
use Pyzit\TempMail\Exceptions\PyzitException;

$client = new TempMailClient($_ENV['PYZIT_TOKEN']);

$email = $_POST['email'] ?? '';

try {
    $r = $client->check($email);
    if ($r->isDisposable) {
        http_response_code(422);
        echo json_encode(['error' => 'Disposable email addresses are not allowed.']);
        exit;
    }
} catch (PyzitException $e) {
    // Fail open
}

// Continue processing the valid email...

$client = new TempMailClient(
    apiToken: $_ENV['PYZIT_TOKEN'],
    timeout:  15,                              // seconds, default: 10
    baseUrl:  'https://api-tempmail.pyzit.com/v1', // default, override for testing
);



use PHPUnit\Framework\TestCase;
use Pyzit\TempMail\TempMailClient;
use Pyzit\TempMail\Models\CheckResult;

class FakeTempMailClient extends TempMailClient
{
    public function __construct(private bool $disposable = false)
    {
        // Skip parent constructor — no real HTTP
    }

    public function check(string $email): CheckResult
    {
        return new CheckResult(
            email:        $email,
            isDisposable: $this->disposable,
            status:       $this->disposable ? 'disposable' : 'clean',
        );
    }
}

class RegistrationServiceTest extends TestCase
{
    public function testDisposableEmailIsRejected(): void
    {
        $service = new RegistrationService(new FakeTempMailClient(disposable: true));
        $this->expectException(\RuntimeException::class);
        $service->register('[email protected]');
    }

    public function testCleanEmailIsAccepted(): void
    {
        $service = new RegistrationService(new FakeTempMailClient(disposable: false));
        $this->assertNull($service->register('[email protected]'));
    }
}

$mock = $this->createMock(TempMailClient::class);
$mock->method('check')->willReturn(
    new CheckResult('[email protected]', true, 'disposable')
);

src/
├── TempMailClient.php         Main client — check(), detailed(), bulk()
├── HttpClient.php             Internal cURL layer — not part of public API
├── Exceptions/
│   ├── PyzitException.php     Base — catch all SDK errors with this
│   ├── AuthenticationException.php
│   ├── ScopeException.php
│   ├── PlanRequiredException.php
│   ├── RateLimitException.php
│   ├── ApiException.php
│   └── TimeoutException.php
└── Models/
    ├── CheckResult.php
    ├── DetailedResult.php
    ├── BulkResult.php
    ├── DetailedDetails.php
    ├── DnsIntelligence.php
    ├── MxRecord.php
    ├── Signals.php
    ├── ReputationDetail.php
    └── StabilityInfo.php

tests/
├── Fixtures.php               Shared test data
├── ExceptionsTest.php
├── ModelsTest.php
├── HttpClientErrorTest.php
└── TempMailClientTest.php