PHP code example of teracrafts / huefy-laravel

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

    

teracrafts / huefy-laravel example snippets


'providers' => [
    // ...
    TeraCrafts\HuefyLaravel\HuefyServiceProvider::class,
],

'aliases' => [
    // ...
    'Huefy' => TeraCrafts\HuefyLaravel\Facades\Huefy::class,
],

use TeraCrafts\HuefyLaravel\Facades\Huefy;

// Send a single email
$response = Huefy::sendEmail('welcome-email', [
    'name' => 'John Doe',
    'company' => 'Acme Corp'
], '[email protected]');

// Send with specific provider
$response = Huefy::sendEmail('newsletter', [
    'name' => 'Jane Smith',
    'unsubscribe_url' => 'https://example.com/unsubscribe'
], '[email protected]', 'sendgrid');

// Send bulk emails
$emails = [
    [
        'template_key' => 'welcome-email',
        'data' => ['name' => 'John'],
        'recipient' => '[email protected]'
    ],
    [
        'template_key' => 'welcome-email', 
        'data' => ['name' => 'Jane'],
        'recipient' => '[email protected]',
        'provider' => 'mailgun'
    ]
];

$results = Huefy::sendBulkEmails($emails);

use TeraCrafts\HuefyLaravel\HuefyClient;

class EmailService
{
    public function __construct(private HuefyClient $huefy)
    {
    }

    public function sendWelcomeEmail(User $user): void
    {
        $this->huefy->sendEmail('welcome-email', [
            'name' => $user->name,
            'email' => $user->email,
            'login_url' => route('login')
        ], $user->email);
    }
}

'mailers' => [
    'huefy' => [
        'transport' => 'huefy',
        'template_key' => env('HUEFY_DEFAULT_TEMPLATE_KEY'),
        'provider' => env('HUEFY_DEFAULT_PROVIDER', 'ses'),
    ],
],

use Illuminate\Mail\Mailable;
use Illuminate\Support\Facades\Mail;

class WelcomeMail extends Mailable
{
    public function __construct(
        public User $user
    ) {}

    public function build()
    {
        return $this->view('emails.welcome')
                    ->with([
                        'name' => $this->user->name,
                        'login_url' => route('login')
                    ])
                    ->subject('Welcome to our platform!');
    }

    public function envelope()
    {
        return new Envelope(
            subject: 'Welcome!',
            using: [
                fn (Message $message) => $message
                    ->getHeaders()
                    ->addTextHeader('X-Template-Key', 'welcome-email')
                    ->addTextHeader('X-Template-Data', json_encode([
                        'name' => $this->user->name,
                        'login_url' => route('login')
                    ]))
                    ->addTextHeader('X-Email-Provider', 'sendgrid')
            ]
        );
    }
}

// Send the email
Mail::to('[email protected]')->send(new WelcomeMail($user));

use Illuminate\Notifications\Notification;
use TeraCrafts\HuefyLaravel\Notifications\HuefyChannel;
use TeraCrafts\HuefyLaravel\Notifications\HuefyMessage;

class WelcomeNotification extends Notification
{
    public function __construct(
        private User $user
    ) {}

    public function via($notifiable): array
    {
        return [HuefyChannel::class];
    }

    public function toHuefy($notifiable): HuefyMessage
    {
        return HuefyMessage::create('welcome-email')
            ->data([
                'name' => $this->user->name,
                'email' => $this->user->email,
                'activation_url' => route('activation', $this->user->id)
            ])
            ->provider('sendgrid');
    }
}

// Send the notification
$user->notify(new WelcomeNotification($user));

// In your User model
public function routeNotificationForHuefy()
{
    return $this->email;
}

// Or return an array for more complex routing
public function routeNotificationForHuefy()
{
    return [
        'email' => $this->email,
        'name' => $this->name
    ];
}

use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Mail\Mailables\Headers;

class CustomHuefyMail extends Mailable
{
    public function __construct(
        private string $templateKey,
        private array $templateData,
        private ?string $provider = null
    ) {}

    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Custom Huefy Email',
        );
    }

    public function content(): Content
    {
        return new Content(
            text: 'emails.empty', // Dummy view since we're using templates
        );
    }

    public function headers(): Headers
    {
        return new Headers(
            text: [
                'X-Template-Key' => $this->templateKey,
                'X-Template-Data' => json_encode($this->templateData),
                'X-Email-Provider' => $this->provider ?: config('huefy.default_provider'),
            ],
        );
    }
}

use TeraCrafts\HuefyLaravel\Facades\Huefy;

class NewsletterService
{
    public function sendNewsletter(Collection $subscribers, string $templateKey): array
    {
        $emails = $subscribers->map(function ($subscriber) use ($templateKey) {
            return [
                'template_key' => $templateKey,
                'data' => [
                    'name' => $subscriber->name,
                    'preferences_url' => route('preferences', $subscriber->id),
                    'unsubscribe_url' => route('unsubscribe', $subscriber->token),
                ],
                'recipient' => $subscriber->email,
                'provider' => $subscriber->preferred_provider ?? 'ses',
            ];
        })->toArray();

        return Huefy::sendBulkEmails($emails);
    }
}

use TeraCrafts\HuefyLaravel\Exceptions\HuefyException;
use TeraCrafts\HuefyLaravel\Exceptions\TemplateNotFoundException;
use TeraCrafts\HuefyLaravel\Exceptions\ValidationException;
use TeraCrafts\HuefyLaravel\Facades\Huefy;

try {
    Huefy::sendEmail('welcome-email', $data, $email);
} catch (TemplateNotFoundException $e) {
    Log::error('Template not found', [
        'template' => $e->getTemplateKey(),
        'message' => $e->getMessage()
    ]);
} catch (ValidationException $e) {
    Log::error('Validation failed', [
        'errors' => $e->getErrors(),
        'message' => $e->getMessage()
    ]);
} catch (HuefyException $e) {
    Log::error('Huefy API error', [
        'code' => $e->getCode(),
        'message' => $e->getMessage(),
        'context' => $e->getContext()
    ]);
}

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use TeraCrafts\HuefyLaravel\Facades\Huefy;

class SendHuefyEmailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(
        private string $templateKey,
        private array $data,
        private string $recipient,
        private ?string $provider = null
    ) {}

    public function handle(): void
    {
        Huefy::sendEmail(
            $this->templateKey,
            $this->data,
            $this->recipient,
            $this->provider
        );
    }
}

// Dispatch the job
SendHuefyEmailJob::dispatch('welcome-email', $data, $email)->onQueue('emails');

return [
    // API Configuration
    'api_key' => env('HUEFY_API_KEY'),
    'timeout' => env('HUEFY_TIMEOUT', 30),
    'retry_attempts' => env('HUEFY_RETRY_ATTEMPTS', 3),
    'default_provider' => env('HUEFY_DEFAULT_PROVIDER', 'ses'),

    // Mail Integration
    'mail' => [
        'default_template_key' => env('HUEFY_DEFAULT_TEMPLATE_KEY'),
        'auto_extract_data' => env('HUEFY_AUTO_EXTRACT_DATA', true),
    ],

    // Notification Integration
    'notifications' => [
        'default_template_key' => env('HUEFY_NOTIFICATION_TEMPLATE_KEY'),
        '

use TeraCrafts\HuefyLaravel\Facades\Huefy;

// Mock the Huefy facade for testing
public function test_sends_welcome_email()
{
    Huefy::shouldReceive('sendEmail')
        ->once()
        ->with('welcome-email', ['name' => 'John'], '[email protected]', null)
        ->andReturn(['message_id' => 'test-123', 'status' => 'sent']);

    $result = $this->emailService->sendWelcome('[email protected]', 'John');

    $this->assertTrue($result);
}
bash
php artisan vendor:publish --tag=huefy-config
bash
php artisan huefy:health
bash
php artisan huefy:providers