PHP code example of stechstudio / laravel-postmaster

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

    

stechstudio / laravel-postmaster example snippets


use STS\Postmaster\EmailEvent;

Event::listen(function (EmailEvent $event) {
    if ($event->isBounced()) {
        // the address bounced; act on it
    }
});

use Illuminate\Support\Facades\Event;
use STS\Postmaster\EmailBounced;

Event::listen(function (EmailBounced $event) {
    // The address bounced. Pause sends, flag the account, alert the team.
    logger()->warning("Email permanently failed for {$event->toAddress()}");
});

use STS\Postmaster\EmailEvent;

Event::listen(function (EmailEvent $event) {
    logger()->info("[{$event->provider()}] {$event->status()} for {$event->toAddress()}");
});

use Illuminate\Support\Facades\Notification;
use STS\Postmaster\EmailBounced;
use STS\Postmaster\Notifications\EmailDeliveryFailed;

Event::listen(function (EmailBounced $event) {
    if ($event->isPermanent()) {
        Notification::route('mail', config('ops.alerts_to'))
            ->notify(new EmailDeliveryFailed($event));
    }
});

$event->provider();           // "SendGrid", "Postmark", "Mailgun", "SES", "Resend"
$event->status();             // one of the EmailEvent::STATUS_* constants
$event->toAddress();          // the recipient email address
$event->providerMessageId();  // the provider's message id
$event->occurredAt();         // when the event happened (DateTimeImmutable, UTC)
$event->bounceType();         // normalized bounce severity, or null
$event->isPermanent();        // true for a hard bounce or a block
$event->response();           // the provider's response/diagnostic detail
$event->reason();             // the provider's reason string
$event->code();               // the provider's status code
$event->clickedUrl();         // the URL clicked on a click event (else null)
$event->tags();               // Collection of tags/categories
$event->data();               // Collection of custom data
$event->payload();            // the raw provider payload
$event->toArray();            // everything above as an array

if ($event->isBounced())    { /* … */ }
if ($event->isDelivered())  { /* … */ }
if ($event->isFailed())     { /* bounced, dropped, or complained */ }

if ($message->isFailed())   { /* the latest event was a failure */ }

use STS\Postmaster\EmailBounced;

Event::listen(function (EmailBounced $event) {
    $event->toAddress();       // works
    $event->bounceType();      // works
    $event->emailMessage();    // same EmailMessage the umbrella listener saw
});

use STS\Postmaster\Models\EmailMessage;

EmailMessage::bounced()->count();
EmailMessage::delivered()->where('sent_at', '>', now()->subDay())->get();

use Illuminate\Support\Facades\Event;
use STS\Postmaster\EmailEvent;

Event::listen(function (EmailEvent $event) {
    $order = $event->emailMessage?->related;   // the Order, User, ... it was sent for
});

foreach ($message->activity as $entry) {
    // $entry->status:      sent, delivered, opened, bounced, ...
    // $entry->occurred_at: when it happened
    // $entry->bounce_type, $entry->response, $entry->reason, $entry->code
}

foreach ($address->activity as $entry) {
    // Every event that touched this address: message lifecycle events
    // from messages sent to it, plus suppressed/unsuppressed entries
    // for the address itself.
}

use STS\Postmaster\Facades\Postmaster;

if (! Postmaster::isSuppressed($email)) {
    Mail::to($email)->send(new Invoice($order));
}

Postmaster::suppress($email);     // optional second arg: a reason string
Postmaster::unsuppress($email);

// in a Mailable's postmaster() method
return new Tracking(related: $this->user, storeContent: false);

// on a notification MailMessage
return (new MailMessage)->subject('Your login code')->dontStoreContent();

$message->resend();

// or equivalently
Postmaster::resend($message);
Postmaster::resend($messageId);

$message->resentFrom;                  // BelongsTo — the original, or null
$message->resends;                     // HasMany — direct resends of this row
$message->resendChain();               // the whole lineage, ordered by sent_at

// Did any retry of this bounced message eventually deliver?
$message->resends()->delivered()->exists();

return new Tracking(
    related:     $this->order,
    recipient:   $this->customer,
    resent_from: $originalMessage,
);

use Illuminate\Mail\Mailable;
use STS\Postmaster\Concerns\TracksMailable;
use STS\Postmaster\Tracking;

class OrderConfirmation extends Mailable
{
    use TracksMailable;

    public function __construct(public Order $order) {}

    public function postmaster(): Tracking
    {
        return new Tracking(
            related: $this->order,              // what the email is about
            recipient: $this->order->customer,  // who the email is for
            tenant: $this->order->account_id,   // optional; see Multitenancy below
            tags: ['billing'],                  // optional; see below
        );
    }

    public function envelope(): Envelope { /* ... */ }
    public function content(): Content { /* ... */ }
}

use STS\Postmaster\Facades\Postmaster;

Postmaster::resolveRecipientByEmail(User::class);

Postmaster::resolveRecipientUsing(
    fn ($address) => Contact::query()
        ->where('primary_email', $address)
        ->orWhere('billing_email', $address)
        ->first()
);

return new Tracking(
    related: $this->order,
    recipients: [
        '[email protected]' => $alice,
        '[email protected]'   => $bob,
    ],
);

EmailMessage::taggedWith('billing')->bounced()->get();

use STS\Postmaster\Concerns\HasEmailMessages;
use STS\Postmaster\Concerns\IsEmailRecipient;

class Order extends Model
{
    use HasEmailMessages;   // emails this order is *about*
}

class User extends Model
{
    use IsEmailRecipient;   // emails this user has *received*
}

$order->emailMessages;                        // every email about this order
$order->emailMessages()->failed()->exists();  // did any of them fail?

$user->emailMessages;                         // every email this user received
$user->latestEmailMessage();                  // the most recent one, or null

use STS\Postmaster\Notifications\TrackedMailMessage;

public function toMail($notifiable)
{
    return (new MailMessage)
        ->subject('Your order shipped')
        ->line('Your order is on its way.')
        ->relatedTo($this->order)
        ->forTenant($this->order->tenant);
}

use STS\Postmaster\Facades\Postmaster;

return (new MailMessage)
    ->subject('Your order shipped')
    ->line('Your order is on its way.')
    ->withSymfonyMessage(Postmaster::relatedTo($this->order))
    ->withSymfonyMessage(Postmaster::forTenant($this->order->tenant));

use STS\Postmaster\Facades\Postmaster;

Postmaster::resolveTenantUsing(fn () => tenant());

class OrderConfirmation extends Mailable
{
    use TracksMailable;

    public function postmaster(): Tracking
    {
        return new Tracking(
            related: $this->order,
            tenant: $this->order->tenant,
        );
    }
}

EmailMessage::forTenant($tenant)->bounced()->get();

use STS\Postmaster\Facades\Postmaster;

Postmaster::useTenantModel(App\Models\Tenant::class);

use STS\Postmaster\Facades\Postmaster;

Postmaster::auth(fn ($request) => $request->user()?->isSuperAdmin());

EmailMessage::sandbox()->get();   // everything intercepted in sandbox mode

use STS\Postmaster\Facades\Postmaster;
use STS\Postmaster\Provider;

Postmaster::extend('myprovider', function (array $config) {
    return new Provider('myprovider', MyAdapter::class, fn ($request) => true);
});
bash
php artisan postmaster:install
bash
php artisan postmaster:verify
bash
php artisan vendor:publish --tag=postmaster.migrations
php artisan migrate
bash
php artisan postmaster:sync                    # all configured providers
php artisan postmaster:sync --provider=sendgrid
php artisan postmaster:sync --dry-run          # report without writing
bash
php artisan vendor:publish --tag=postmaster.config