PHP code example of naijacloud / email

1. Go to this page and download the library: Download naijacloud/email 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/ */

    

naijacloud / email example snippets


use NaijaCloud\Email\Naijamail;

$nm = new Naijamail();                       // reads NAIJAMAIL_API_KEY

$sent = $nm->emails->send([
    'from' => 'Acme <[email protected]>',
    'to' => '[email protected]',
    'subject' => 'Your receipt',
    'html' => '<p>Thanks.</p>',
]);

echo $sent->id;                              // 5b1e0000-...
echo $nm->emails->get($sent->id)->status;    // queued | delivered | bounced | ...

$sent = $nm->emails->send([
    'from' => 'Acme <[email protected]>',        // m',
    'bcc' => '[email protected]',
    'reply_to' => '[email protected]',
    'subject' => 'Invoice #1024',
    'html' => '<p>Attached.</p>',
    'text' => 'Attached.',
    'headers' => ['X-Campaign' => 'invoices'],
    'attachments' => [[
        'filename' => 'invoice-1024.pdf',
        'content' => file_get_contents('/tmp/invoice.pdf'),   // raw bytes
        'content_type' => 'application/pdf',
    ]],
    'tags' => ['campaign' => 'invoices'],
    'idempotency_key' => 'invoice-1024',      // optional; generated if omitted
]);

foreach ($sent->rejected as $recipient) {
    $log->info("not sent to {$recipient->address}: {$recipient->reason}");
}

use NaijaCloud\Email\MessageStatus;

if ($email->status === MessageStatus::BOUNCED) { /* ... */ }
if (!MessageStatus::isKnown($email->status))   { /* newer than this SDK */ }

$nm = new Naijamail($apiKey, [
    'base_url' => 'https://api.naijacloud.com',  // or env NAIJAMAIL_BASE_URL
    'timeout' => 30.0,                           // seconds, per attempt
    'max_retries' => 2,                          // retries after the first try
    'user_agent_suffix' => 'acme-billing/2.1',
]);

use NaijaCloud\Email\Exception\{NaijamailException, PermissionException, RateLimitException};

try {
    $nm->emails->send($message);
} catch (PermissionException $e) {
    // Unverified domain, a key without the right scope, or the daily quota.
    $log->error($e->getMessage(), ['request_id' => $e->requestId]);
} catch (RateLimitException $e) {
    $queue->later($e->getRetryAfter() ?? 60, $job);
} catch (NaijamailException $e) {
    $log->error('naijamail: ' . $e->getMessage(), ['status' => $e->statusCode]);
}

'naijamail' => [
    'key' => env('NAIJAMAIL_API_KEY'),
    'from' => env('NAIJAMAIL_FROM', 'Acme <[email protected]>'),
],

use NaijaCloud\Email\Naijamail;

public function register(): void
{
    // Singleton: one client per process, resolved from config rather than from
    // the environment directly, so `php artisan config:cache` keeps working.
    $this->app->singleton(Naijamail::class, fn () => new Naijamail(
        config('services.naijamail.key'),
        ['user_agent_suffix' => 'laravel/' . app()->version()],
    ));
}

public function __invoke(Naijamail $nm, Order $order)
{
    $nm->emails->send([
        'from' => config('services.naijamail.from'),
        'to' => $order->customer->email,
        'subject' => "Receipt for order #{$order->id}",
        'html' => view('mail.receipt', compact('order'))->render(),
        // The order id, so a retried queue job cannot mail the customer twice.
        'idempotency_key' => "receipt-{$order->id}",
    ]);
}

use NaijaCloud\Email\Webhooks;
use NaijaCloud\Email\Exception\WebhookVerificationException;

try {
    $event = Webhooks::verify(
        $request->getContent(),                    // raw body, byte for byte
        $request->header('NC-Signature'),
        config('services.naijamail.webhook_secret'),
    );
} catch (WebhookVerificationException $e) {
    return response('', 400);
}

match ($event->type) {
    'email.delivered' => /* ... */,
    'email.bounced' => /* ... */,
    default => null,
};