PHP code example of mailvex / mailvex-php

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

    

mailvex / mailvex-php example snippets


use Mailvex\Mailvex;
use Mailvex\Client;

$client = Mailvex::client(
    apiKey: 'mvx_live_a89f30b2c1409f921df048bbef8001a1',
    baseUrl: 'https://api.mailvex.yourdomain.com' // Explicit URL 

use Mailvex\Models\EmailMessage;
use Mailvex\Models\Attachment;

$message = EmailMessage::create()
    ->from('Security Alert <[email protected]>')
    ->to('[email protected]')
    ->cc('[email protected]')
    ->replyTo('[email protected]')
    ->subject('Action Required: Security Audit Report')
    ->html('<h2>Security Audit Complete</h2><p>Please find your security report attached.</p>')
    ->text("Security Audit Complete\nPlease find your security report attached.")
    ->attachFromPath('/path/to/report.pdf', 'security-audit.pdf', 'application/pdf')
    ->attachFromData('Col1,Col2\nVal1,Val2', 'metrics.csv', 'text/csv')
    ->header('X-Agent-Origin', 'worker-4')
    ->tag('security-report')
    ->metadata('report_id', 'rep_001')
    ->idempotencyKey('b8b3d6cb-0e9e-4e31-893d-4c3d82a17f22');

$response = $client->send($message);

echo "Message Queued! ID: " . $response['id'];

$message = EmailMessage::create()
    ->from('Team <[email protected]>')
    ->to([
        '[email protected]',
        '[email protected]',
        '[email protected]'
    ])
    ->subject('Project Update')
    ->html('<p>Hi Team, weekly sprint update is ready.</p>');

$response = $client->send($message);

use Mailvex\Models\BatchMessage;
use Mailvex\Models\BatchRecipient;

$batch = BatchMessage::create()
    ->from('Billing <[email protected]>')
    ->subject('Your Monthly Statement')
    ->template('tmpl_monthly_statement')
    ->stream('broadcast')
    ->addRecipient('[email protected]', [
        'name' => 'Alice',
        'amount' => '$49.00',
        'due_date' => 'Nov 1, 2026'
    ], ['customer_tier' => 'pro'])
    ->addRecipient('[email protected]', [
        'name' => 'Bob',
        'amount' => '$99.00',
        'due_date' => 'Nov 3, 2026'
    ], ['customer_tier' => 'enterprise'])
    ->attachFromPath('/path/to/terms.pdf');

$response = $client->sendBatch($batch);

echo "Batch queued! Total: {$response['total']}, Accepted: {$response['accepted']}\n";
print_r($response['message_ids']);

     // In a Mailable:
     public function headers(): Headers
     {
         return new Headers(text: ['X-Mailvex-Stream' => 'broadcast']);
     }

     // Or via Mail::send() callback:
     Mail::send([], [], function ($message) {
         $message->getHeaders()->addTextHeader('X-Mailvex-Stream', 'broadcast');
     });
     

     $email->stream('broadcast');
     

'mailers' => [
    'mailvex' => [
        'transport' => 'mailvex',
    ],
],

use Illuminate\Support\Facades\Mail;
use App\Mail\AdmissionOfferMailable;

// 1. Using Mailable
Mail::to(['[email protected]', '[email protected]'])
    ->send(new AdmissionOfferMailable($offer));

// 2. Using inline Mail::send with attachment
Mail::send([], [], function ($message) {
    $message->to('[email protected]')
        ->from('[email protected]', 'Krea Admissions')
        ->subject('Offer Letter - Krea University')
        ->html('<p>Congratulations! Please find your offer letter attached.</p>')
        ->attach('/path/to/offer-letter.pdf', [
            'as' => 'Krea-Offer-Letter.pdf',
            'mime' => 'application/pdf',
        ]);
});

use Illuminate\Support\Facades\Route;

// Registers POST /api/mailvex/webhook with signature verification
Route::mailvexWebhooks('mailvex/webhook');

namespace App\Listeners;

use Mailvex\Laravel\Events\WebhookReceived;
use Illuminate\Support\Facades\Log;

class HandleMailvexWebhook
{
    public function handle(WebhookReceived $event): void
    {
        $webhook = $event->event;

        // 1. De-duplicate using stable Event ID
        $eventId = $webhook->getId(); // "evt_01HZX..."

        // 2. Handle outcome
        if ($webhook->isBounced()) {
            $email = $webhook->getRecipient();
            $type = $webhook->getBounceType(); // "hard_bounce", "soft_bounce", etc.

            if ($webhook->isHardBounce()) {
                // Unrecoverable hard bounce: Mark contact as invalid in CRM
                Log::warning("Hard bounce for {$email}: " . $webhook->getBounceReason());
            } elseif ($webhook->isSoftBounce()) {
                // Transient bounce: Mailvex will auto-retry up to 72 hours
                Log::info("Transient soft bounce ({$type}) for {$email}");
            }
        } elseif ($webhook->isDelivered()) {
            $messageId = $webhook->getMessageId();
            // Update CRM message delivery record
        } elseif ($webhook->isComplained()) {
            // Unsubscribe user immediately
        }
    }
}
bash
composer 
bash
php artisan vendor:publish --tag=mailvex-config
bash
php tests/run_tests.php