PHP code example of julienramel / cloudflare-mailer

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

    

julienramel / cloudflare-mailer example snippets


use Symfony\Component\Mime\Email;
use Symfony\Component\Mailer\MailerInterface;

class MyService
{
    public function __construct(private readonly MailerInterface $mailer) {}

    public function sendWelcome(string $to): void
    {
        $email = (new Email())
            ->from(new Address('[email protected]', 'My App'))
            ->to($to)
            ->subject('Welcome!')
            ->text('Thanks for signing up.')
            ->html('<h1>Thanks for signing up.</h1>');

        $this->mailer->send($email);
    }
}

use JulienRamel\CloudflareMailer\Event\CloudflareBounceEvent;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;

#[AsEventListener]
final class CloudflareBounceListener
{
    public function __construct(
        private readonly ContactRepository $contacts,
    ) {}

    public function __invoke(CloudflareBounceEvent $event): void
    {
        foreach ($event->getBouncedAddresses() as $address) {
            // The address does not exist or is permanently unreachable.
            // Common reactions: mark as invalid, remove from mailing list,
            // alert your ops team, increment a counter, etc.
            $this->contacts->markAsUndeliverable($address);
        }
    }
}

use JulienRamel\CloudflareMailer\Event\CloudflareBounceEvent;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\Mailer\Exception\TransportException;

#[AsEventListener]
final class StrictBounceListener
{
    public function __invoke(CloudflareBounceEvent $event): void
    {
        $result = $event->getSentMessage()->getDebug();
        // Check if anything was delivered by inspecting the debug output,
        // or keep track of delivered/bounced counts in your own logic.

        // Throw to propagate the failure up the call stack:
        throw new TransportException(\sprintf(
            'Email permanently bounced for: %s',
            implode(', ', $event->getBouncedAddresses()),
        ));
    }
}