PHP code example of wisedata / mail-php

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

    

wisedata / mail-php example snippets


use WiseData\Mail\Client;

$mail = new Client('wdm_abc_def');

$mail->contacts()->upsert([
    'external_id' => 'usr_9',          // o id desta pessoa NO SEU sistema
    'email'       => '[email protected]',
    'first_name'  => 'Ana',
    'fields'      => ['plano_atual' => 'pro'],
    'lists'       => [3],
]);

$mail->contacts()->find('usr_9');                       // por external_id
$mail->contacts()->findByEmail('[email protected]');      // null se não achar
$mail->contacts()->list(page: 1, perPage: 25);
$mail->contacts()->delete('usr_9');
$mail->contacts()->deleteByEmail('[email protected]');    // para quem não tem external_id

$mail->contacts()->upsert([
    'external_id' => 'usr_9',
    'email' => '[email protected]',
    'add_lists' => ['clientes-finances'],
]);

// ou, para um contato que já existe:
$mail->contacts()->addToLists('usr_9', ['clientes-finances']);
$mail->contacts()->removeFromLists('usr_9', ['clientes-finances']);

$mail->catalog()->fields();   // [['key' => 'plano_atual', 'type' => 'text', ...], ...]
$mail->catalog()->lists();    // [['key' => 'clientes-finances', 'id' => 3, 'name' => 'Clientes'], ...]

$marcaB = $mail->forSpace('marca-b');
$marcaB->contacts()->upsert([...]);

// 1. O cliente do seu sistema vira um espaço. Repetir atualiza, não duplica.
$espaco = $mail->spaces()->upsert(externalId: 'cliente_812', name: 'Avcom');

// Guarde o slug que VOLTOU: é o valor do forSpace().
$doCliente = $mail->forSpace($espaco['slug']);

// 2. O domínio dele. Devolve os registros DNS para você mostrar ao cliente.
$dominio = $doCliente->domains()->register('avcom.com.co');
foreach ($dominio['records'] as $r) {
    // $r['type'], $r['name'], $r['value'], $r['priority'], $r['status']
}

// 3. Quando o webhook avisar domain.verified, o remetente:
$doCliente->senders()->upsert('[email protected]', 'Avcom', label: 'Pesquisas');

// 4. E o envio sai com o nome do cliente.
$doCliente->emails()->send([
    'to' => '[email protected]',
    'from' => '[email protected]',
    'subject' => '¿Cómo fue su experiencia?',
    'html' => '<p>...</p>',
]);

$mail->emails()->send([
    'to' => '[email protected]',
    'to_name' => 'Ana',
    'subject' => 'Seu código de acesso',
    'html' => '<p>Seu código é <strong>123456</strong>.</p>',
    'text' => 'Seu código é 123456.',
], idempotencyKey: 'codigo-usr9-2026-09-24');

$mail->emails()->send([
    'to' => '[email protected]',
    'subject' => 'Seu relatório de setembro',
    'html' => '<p>Segue em anexo.</p>',
    'attachments' => [[
        'filename' => 'relatorio-setembro.pdf',
        'content' => base64_encode(file_get_contents($caminho)),
        'content_type' => 'application/pdf',
    ]],
]);

'attachments' => [[
    'filename' => 'logo.png',
    'content' => base64_encode($png),
    'content_type' => 'image/png',
    'disposition' => 'inline',
    'content_id' => 'logo123',
]],
// no HTML: <img src="cid:logo123">

$mail->emails()->send([
    'to' => '[email protected]',
    'template' => 'boas-vindas',
    'variables' => ['nome' => 'Ana', 'plano' => 'Crescimento'],
]);

$resultados = $mail->emails()->sendBatch([
    [
        'to' => '[email protected]',
        'subject' => 'Como foi seu atendimento?',
        'html' => $html,
        'message_type' => 'marketing',
        'idempotency_key' => 'convite-81',
        'metadata' => ['invitation_id' => 81],
    ],
    // ...
]);

foreach ($resultados as $item) {
    if (isset($item['error'])) {
        // $item['index'], $item['status'] (o HTTP do envio avulso), $item['error']['error']
        continue;
    }

    // $item['index'], $item['id'], $item['status'] ('pending' ou 'suppressed'), $item['replayed']
}

'message_type' => 'marketing',
'headers' => [
    'List-Unsubscribe' => '<https://app.exemplo.com/sair/TOKEN>, <mailto:[email protected]>',
    'List-Unsubscribe-Post' => 'List-Unsubscribe=One-Click',
],

app(\WiseData\Mail\Client::class)->contacts()->upsert([...]);

// O mesmo endereço verificado, um nome por cliente.
$mail->emails()->send([
    'to' => '[email protected]',
    'from' => '[email protected]',
    'from_name' => 'Avcom',
    'reply_to' => '[email protected]',
    'subject' => 'Sua opinião',
    'html' => '<p>...</p>',
]);

// 2. Um remetente só para este mailer, em config/mail.php (recurso do Laravel).
'wisedatamail' => [
    'transport' => 'wisedatamail',
    'from' => ['address' => '[email protected]', 'name' => 'Seu Produto'],
],

'wisedatamail_marketing' => [
    'transport' => 'wisedatamail',
    'space' => 'marca-b',
    'message_type' => 'marketing',
],

Mail::to($cliente)->send(new RelatorioMensal($pdf));

// dentro do Mailable
public function attachments(): array
{
    return [Attachment::fromPath($caminho)->as('relatorio-setembro.pdf')];
}

public function headers(): Headers
{
    return new Headers(text: ['X-WiseData-Message-Type' => 'marketing']);
}

public function envelope(): Envelope
{
    return new Envelope(
        subject: 'Suas contas vencem amanhã',
        tags: ['due-reminders'],
        metadata: ['user_id' => $this->user->id, 'reminder_type' => 'digest'],
    );
}

use WiseData\Mail\Laravel\Facades\WiseDataMail;

public function test_o_recibo_sai_pelo_wisedata_mail(): void
{
    $mail = WiseDataMail::fake();

    $this->post('/pedidos/1234/pagar');

    $mail->assertSentTo('[email protected]', fn (array $corpo) => $corpo['subject'] === 'Seu recibo');
    $mail->assertSentCount(1);
}

use Symfony\Component\Mailer\Mailer;
use WiseData\Mail\Mailer\WiseDataMailTransport;

$mailer = new Mailer(new WiseDataMailTransport(new Client('wdm_abc_def')));

use WiseData\Mail\Exception\ApiException;
use WiseData\Mail\Exception\TransportException;

try {
    $mail->contacts()->upsert([...]);
} catch (ApiException $e) {
    // A API respondeu não.
    $e->error;    // 'unknown_field', 'insufficient_scope', 'space_

use WiseData\Mail\Laravel\Events\WiseDataMailBounced;

final class SuprimirEnderecoDevolvido implements ShouldQueue
{
    public function handle(WiseDataMailBounced $e): void
    {
        $e->event->email;                 // quem
        $e->event->messageId;             // o id devolvido no envio
        $e->event->bounceClassification;  // 'invalid_address', 'mailbox_full', ...
    }
}

public function handle(WiseDataMailDomainVerified $e): void
{
    Cliente::where('mail_space', $e->event->space)
        ->update(['remetente_proprio_liberado' => $e->event->domain->readyToSend]);
}

use WiseData\Mail\Laravel\Webhook\VerifyWebhookSignature;
use WiseData\Mail\Laravel\Webhook\WebhookController;

Route::post('/webhooks/wisedata-mail', WebhookController::class)
    ->middleware(VerifyWebhookSignature::class)
    ->withoutMiddleware(\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class);

use WiseData\Mail\Webhook\WebhookPayload;
use WiseData\Mail\Webhook\WebhookSignature;

$corpo = file_get_contents('php://input');

if (! WebhookSignature::verify(
    $corpo,
    $_SERVER['HTTP_X_WISEDATA_TIMESTAMP'] ?? '',
    $_SERVER['HTTP_X_WISEDATA_SIGNATURE'] ?? '',
    $segredo,
)) {
    http_response_code(401);
    exit;
}

foreach (WebhookPayload::parse($corpo)->events as $evento) {
    // $evento->type, $evento->email, $evento->messageId, $evento->subject, ...
}

// AppServiceProvider::register()
$this->app->singleton(\WiseData\Mail\Contracts\Transport::class, fn () => new MeuTransporte);

new Client(token: '...', transport: new MeuTransporte);
bash
composer 
bash
php artisan wisedata-mail:test [email protected]
php artisan wisedata-mail:test [email protected] --mailer=wisedatamail_marketing
dotenv
WISEDATA_MAIL_WEBHOOK_SECRET=o-segredo-exibido-na-criacao
WISEDATA_MAIL_WEBHOOK_PATH=webhooks/wisedata-mail
json
{
  "events": [
    {
      "id": 8821,
      "type": "delivered",
      "occurred_at": "2026-09-25T14:03:11+00:00",
      "email": "[email protected]",
      "message_id": 991,
      "campaign_id": null,
      "message_type": "transactional",
      "url": null,
      "reason": null,
      "bounce_classification": null,
      "machine_open": false,
      "is_test": false,
      "space": null
    }
  ],
  "sent_at": "2026-09-25T14:03:21+00:00"
}