PHP code example of mailblastr / mailblastr

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

    

mailblastr / mailblastr example snippets


use Mailblastr\Mailblastr;

$mailblastr = Mailblastr::client('mb_xxxxxxxxx');

$sent = $mailblastr->emails->send([
    'from' => 'Acme <[email protected]>',
    'to' => ['[email protected]'],
    'subject' => 'Hello from MailBlastr',
    'html' => '<p>Your first email 🎉</p>',
]);

echo 'sent ' . $sent['id'];

use Mailblastr\Exceptions\MailblastrException;

try {
    $mailblastr->emails->send($payload);
} catch (MailblastrException $e) {
    echo $e->getStatusCode(); // 422
    echo $e->getName();       // 'validation_error'
    echo $e->getMessage();    // 'domain is 

} catch (MailblastrException $e) {
    // WHICH quota ran out, and what would clear it.
    if ($limit = $e->getLimit()) {
        echo $limit['kind'];                    // 'emails_daily'
        echo "{$limit['used']}/{$limit['limit']} used over {$limit['period']}";
        echo $limit['next_plan']['name'] ?? ''; // 'Pro'
    }

    // Reputation gates: whether waiting helps, and until when.
    if ($rep = $e->getReputation()) {
        echo $rep['scope'], $rep['retryable'] ? " until {$rep['retry_at']}" : ' (not retryable)';
    }

    // A batch that failed part way through — do NOT resend these.
    if ($sent = $e->getSent()) {
        echo "{$e->getSentCount()} already went out: " . implode(', ', array_column($sent, 'id'));
    }
}

$mailblastr->emails->send([
    'from' => 'Acme <[email protected]>',
    'to' => ['[email protected]'],
    'subject' => 'Your invoice',
    'html' => '<p>Invoice attached.</p>',
    'attachments' => [
        ['filename' => 'invoice.pdf', 'path' => 'https://yourdomain.com/invoices/invoice.pdf'],
        ['filename' => 'report.csv', 'content' => $base64Content, 'content_type' => 'text/csv'],
    ],
]);

$mailblastr = Mailblastr::client('mb_xxxxxxxxx', [
    'baseUrl' => 'https://www.mailblastr.com/api', // override your API host
    'timeout' => 30,     // per-request timeout in seconds (0 = no timeout)
    'maxRetries' => 2,   // automatic retries on 429/503 (0 disables)
    // 'transport' => $fake, // any TransportInterface — see Testing
]);

// Emails
$mailblastr->emails->send(['from' => …, 'to' => …, 'subject' => …, 'html' => …]);
$mailblastr->emails->list(['limit' => 20, 'after' => $cursor]); // cursor pagination
$mailblastr->emails->list(['status' => 'bounced', 'search' => 'ada@']); // server-side filters
$mailblastr->emails->list(['folder' => 'scheduled']); // outbox | sent | scheduled | failed — any other value is rejected (422)
$mailblastr->emails->get($id);
$mailblastr->emails->sources();                                 // per-campaign/automation send metrics
$mailblastr->emails->listAttachments(id: $id);
$mailblastr->emails->getAttachment(id: $id, attachmentId: $attachmentId);
$mailblastr->emails->update($id, ['scheduled_at' => $ts]);      // reschedule
$mailblastr->emails->cancel($id);

// Inbound email
$mailblastr->emails->receiving->list();
$mailblastr->emails->receiving->listAddresses();                    // per-address inbound stats
$mailblastr->emails->receiving->get($id);
$mailblastr->emails->receiving->forward($id, ['from' => '[email protected]', 'to' => '[email protected]']);
$mailblastr->emails->receiving->reply($id, ['from' => '[email protected]', 'text' => 'Thanks!']);
$bytes = $mailblastr->emails->receiving->getAttachment($id, $attachmentId); // raw bytes
$mime = $mailblastr->emails->receiving->getRaw($id);                        // raw RFC822

// Batch send (alias of $mailblastr->emails->batch())
$res = $mailblastr->batch->send([ /* up to 100 email payloads */ ]);
// 1-40 are sent inline (HTTP 200, no 'queued' key). 41-100 are QUEUED (HTTP 202):
// $res['queued'] === true and $res['queued_count'] === count($res['data']), and
// the mail has NOT gone out yet — the worker sends it on its next tick.
if ($res['queued'] ?? false) { /* not transmitted yet — poll $mailblastr->emails->get($id) */ }

// Domains (incl. claiming a domain verified elsewhere + one-click DNS)
$mailblastr->domains->create(['name' => 'example.com']);
$mailblastr->domains->verify($id);
$mailblastr->domains->claim(['name' => 'example.com']);
$mailblastr->domains->verifyClaim($id);
$mailblastr->domains->detectDns($id);
$mailblastr->domains->applyCloudflareDns($id, ['token' => $cfToken]);
$mailblastr->domains->mxCheck('example.com');   // live MX lookup
$csv = $mailblastr->domains->recordsCsv($id);   // DNS records as CSV text

// Contacts are DOMAIN-FIRST: each sending domain has its own contact pool
// (the same address on two domains is two records with separate consent).
$mailblastr->contacts->create(['domain' => 'example.com', 'email' => $email, 'first_name' => 'Ada']);
$mailblastr->contacts->list(['domain' => 'example.com']);
$mailblastr->contacts->get(['id' => $contactId]);                            // by contact id (exact) …
$mailblastr->contacts->get(['id' => $email, 'domain' => 'example.com']);     // … or by email + domain
$mailblastr->contacts->update(['id' => $contactId, 'unsubscribed' => true]);
$mailblastr->contacts->remove(['id' => $contactId]);
$mailblastr->contacts->batch(['audienceId' => $audienceId, 'contacts' => [ … ]]);
$mailblastr->contacts->batch(['domain' => 'example.com', 'contacts' => [ … ]]); // domain-first
$mailblastr->contacts->import(['audienceId' => $audienceId, 'csv' => $csvText]);
// Large files: mint a presigned slot, PUT the file to $slot['upload_url']
// yourself (it is a bearer credential — do not log it), then import by key.
$slot = $mailblastr->contacts->createImportUpload(['audienceId' => $audienceId, 'filename' => 'leads.csv', 'size' => $bytes]);
$mailblastr->contacts->import(['audienceId' => $audienceId, 'storage_key' => $slot['storage_key']]);
$mailblastr->contacts->addToSegment($contactId, $segmentId);
$mailblastr->contacts->updateTopics($contactId, ['topics' => [['id' => 'top_1', 'subscription' => 'opt_in']]]);

// Contact properties (custom fields)
$mailblastr->contactProperties->create(['key' => 'plan', 'type' => 'string']);

// Campaigns, Segments — also domain-first: 'domain' picks the contact pool the
// campaign/segment targets. Segment names are unique per domain (reusable
// across domains), and every domain carries an auto-created "General" segment.
$mailblastr->campaigns->create(['domain' => 'example.com', 'from' => …, 'subject' => …, 'html' => …, 'segment_id' => $segmentId]);
$mailblastr->campaigns->send($id, ['scheduled_at' => $ts]);
$mailblastr->campaigns->stats($id);       // counts, rates, top links
$mailblastr->campaigns->engagement($id);  // who opened / clicked / replied
$mailblastr->segments->create(['domain' => 'yourdomain.com', 'name' => 'VIP']);
$mailblastr->segments->list(['domain' => 'yourdomain.com']);
$mailblastr->segments->contacts($id);   // preview who matches

// Templates
$mailblastr->templates->create(['name' => $name, 'subject' => $subject, 'html' => $html]);
$mailblastr->templates->duplicate($id);
$mailblastr->templates->publish($id);
$mailblastr->emails->send(['from' => …, 'to' => …, 'template_id' => $templateId, 'variables' => ['first_name' => 'Ada']]);

// Audiences (incl. Google Sheet import)
$mailblastr->audiences->importSheet($audienceId, ['url' => $sheetUrl]);

// API keys (listing only — creating, re-scoping and revoking is dashboard-only)
$mailblastr->apiKeys->list();

// Custom events (the triggers for automations)
$mailblastr->events->create(['name' => 'signup.completed', 'schema' => ['plan' => 'string']]);
$mailblastr->events->update($eventId, ['schema' => ['plan' => 'string', 'seats' => 'number']]);

// Polls (read-only results of the in-email poll widget)
$mailblastr->polls->list();
$mailblastr->polls->get($emailId);

$topic = $mailblastr->topics->create([
    'domain' => 'example.com', // topics belong to a sending domain
    'name' => 'Product updates',
    'description' => 'New features and releases',
    'default_subscription' => 'opt_in',
]);

$mailblastr->topics->list(['domain' => 'example.com', 'limit' => 50]);
$mailblastr->topics->update($topic['id'], ['visibility' => 'private']);
$mailblastr->topics->remove($topic['id']);

$automation = $mailblastr->automations->create([
    'name' => 'Welcome series',
    'domain' => 'yourdomain.com',
    'trigger' => 'contact.created',
]);

// Steps are only editable while the automation is disabled — new ones start
// that way, so build first and enable last (call stop() to edit a live one).
$mailblastr->automations->addStep($automation['id'], [
    'type' => 'send_email',
    'config' => ['template_id' => 'tmpl_welcome'],
]);
// A step update REPLACES the step rather than merging into it: send 'type' plus
// the complete 'config' every time — omitting 'type' is a 422, not "leave the
// type unchanged", and anything left out of 'config' is dropped, not preserved.
$mailblastr->automations->updateStep($automation['id'], $stepId, ['type' => 'delay', 'config' => ['duration' => '3 days']]);

// Or let AI draft the steps instead — also 

$hook = $mailblastr->webhooks->create([
    // The endpoint must be https:// and must not resolve to a private address.
    'endpoint' => 'https://yourapp.com/hooks/mailblastr',
    'events' => ['email.delivered', 'email.bounced', 'email.unsubscribed'],
]);
// $hook['signing_secret'] is shown ONCE — store it now.

$mailblastr->webhooks->list();
$mailblastr->webhooks->update($hook['id'], ['status' => 'disabled']);
$mailblastr->webhooks->rotate($hook['id']); // new signing_secret, revealed once

// A failed delivery still returns HTTP 200 and does NOT throw — the outcome is
// $result['ok'], with $result['status'] (your endpoint's HTTP status, when it
// responded) and $result['error'] (e.g. 'lookup_failed').
$result = $mailblastr->webhooks->test($hook['id']);
if (!$result['ok']) {
    error_log("test delivery failed: {$result['error']}");
}

$payload = file_get_contents('php://input'); // do NOT re-serialize parsed JSON

$result = $mailblastr->webhooks->verify($payload, [
    'svix-id' => $_SERVER['HTTP_SVIX_ID'] ?? '',
    'svix-timestamp' => $_SERVER['HTTP_SVIX_TIMESTAMP'] ?? '',
    'svix-signature' => $_SERVER['HTTP_SVIX_SIGNATURE'] ?? '',
], $signingSecret);

if (!$result['valid']) {
    http_response_code(401); // $result['reason'] says why
}

$mailblastr->logs->list(['limit' => 100, 'method' => 'POST', 'status' => 429]);
$mailblastr->logs->get($logId);

$mailblastr->campaigns->list(['limit' => 25, 'after' => 'cursor_abc']);

$mailblastr->emails->send($payload, ['idempotencyKey' => 'order-123']);
$mailblastr->batch->send($payloads, ['idempotencyKey' => 'batch-2026-08-08']);
bash
php tests/run.php