Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Resend Php Laravel Package

resend/resend-php

Resend PHP is an official PHP 8.1+ client for the Resend email API. Install via Composer and send transactional emails with a clean, simple interface (e.g., $resend->emails->send) in PHP or Laravel.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install the package:

    composer require resend/resend-php
    
  2. Initialize the client (e.g., in config/services.php):

    'resend' => [
        'api_key' => env('RESEND_API_KEY'),
        'api_url' => env('RESEND_API_URL', 'https://api.resend.com'),
    ],
    

    Then create a helper in app/Providers/AppServiceProvider.php:

    public function boot()
    {
        $this->app->singleton(Resend::class, function ($app) {
            return Resend::client($app['config']['services.resend.api_key'], [
                'api_url' => $app['config']['services.resend.api_url'],
            ]);
        });
    }
    
  3. First email send (e.g., in a controller):

    use Resend\Resend;
    
    public function sendWelcomeEmail()
    {
        $resend = app(Resend::class);
        $response = $resend->emails->send([
            'from' => 'onboarding@example.com',
            'to' => 'user@example.com',
            'subject' => 'Welcome!',
            'html' => '<strong>Welcome to our platform!</strong>',
        ]);
        return response()->json($response);
    }
    

Key First-Use Cases

  • Transactional emails: Password resets, order confirmations.
  • Marketing emails: Newsletters via templates.
  • Webhook testing: Verify events or logs endpoints.

Implementation Patterns

Core Workflows

  1. Email Sending

    • Basic: Use emails->send() with from, to, subject, and html/text.
    • Templates: Reference a Resend template ID:
      $resend->emails->send([
          'from' => 'team@example.com',
          'to' => 'user@example.com',
          'template_id' => 'abc123',
          'template_data' => ['name' => 'John'],
      ]);
      
    • Batch Emails: For bulk sends (e.g., newsletters):
      $resend->emails->batch([
          'emails' => [
              ['to' => 'user1@example.com', 'subject' => 'Hello'],
              ['to' => 'user2@example.com', 'subject' => 'Hi'],
          ],
          'options' => ['batch_validation' => true],
      ]);
      
  2. Contacts Management

    • CRUD Operations: Use contacts->create(), contacts->get(), etc.
    • Segments: Add users to segments for targeted campaigns:
      $resend->contacts->segments->add([
          'segment_id' => 'segment_123',
          'contact_ids' => ['contact_456'],
      ]);
      
  3. Webhooks & Events

    • Verify Signatures: Use the WebhookSignature verifier:
      $verifier = new \Resend\WebhookSignature($this->request->header('X-Resend-Signature'));
      if ($verifier->verify($this->request->getContent(), env('RESEND_WEBHOOK_SECRET'))) {
          // Process event
      }
      
    • Listen for Events: Poll events->list() or subscribe to topics.
  4. Templates & Domains

    • Template Management: Create/update templates via templates->create().
    • Domain Verification: Verify custom domains:
      $resend->domains->verify([
          'domain' => 'example.com',
          'dns_records' => ['type' => 'TXT', 'value' => 'resend=...'],
      ]);
      

Laravel-Specific Patterns

  • Service Providers: Bind the client to the container (as shown above) for dependency injection.
  • Mailables: Extend Laravel’s Mailable to use Resend:
    use Resend\Resend;
    
    public function build()
    {
        $resend = app(Resend::class);
        $this->withSwiftMessage(function ($message) use ($resend) {
            $message->setFrom('onboarding@example.com');
            $message->setTo('user@example.com');
            // Use Resend’s API for advanced features like templates
        });
    }
    
  • Jobs: Queue email sends for async processing:
    use Resend\Resend;
    use Illuminate\Bus\Queueable;
    
    class SendEmailJob implements Queueable
    {
        public function handle(Resend $resend)
        {
            $resend->emails->send([...]);
        }
    }
    

Gotchas and Tips

Common Pitfalls

  1. API Key Exposure

    • Never hardcode RESEND_API_KEY in source. Use Laravel’s .env and config/services.php.
    • Restrict the key to specific IPs in Resend’s dashboard if using shared hosting.
  2. Idempotency Keys

    • Always use idempotency_key for critical emails (e.g., payments) to avoid duplicates:
      $resend->emails->send([
          'from' => 'payments@example.com',
          'to' => 'user@example.com',
          'subject' => 'Payment Received',
          'headers' => ['Idempotency-Key' => 'unique_key_123'],
      ]);
      
  3. Template Data Validation

    • Resend templates require exact template_data keys. Validate against the template’s schema before sending.
  4. Rate Limits

    • Monitor 429 Too Many Requests errors. Implement exponential backoff:
      try {
          $resend->emails->send([...]);
      } catch (\Resend\Exception\RateLimitException $e) {
          sleep($e->getRetryAfter());
          retry();
      }
      
  5. Webhook Delays

    • Resend may take up to 5 minutes to deliver webhooks. Use events->list() for critical syncs.

Debugging Tips

  • Enable Debug Mode: Set debug: true in the client config to log requests/responses.
  • Check Response Codes: Resend returns 4xx for client errors (e.g., 400 for invalid emails). Use:
    try {
        $resend->emails->send([...]);
    } catch (\Resend\Exception\ResendException $e) {
        Log::error('Resend error: ' . $e->getMessage());
    }
    
  • Validate DNS Records: For custom domains, ensure TXT records are correctly propagated (use dig or nslookup).

Extension Points

  1. Custom HTTP Client Override the default Guzzle client for retries or middleware:

    $client = new \Resend\Client($apiKey, [
        'http_client' => new \GuzzleHttp\Client([
            'timeout' => 30,
            'headers' => ['User-Agent' => 'MyApp/1.0'],
        ]),
    ]);
    
  2. Event Handlers Extend the Event class to add custom logic:

    class CustomEvent extends \Resend\Event
    {
        public function handle()
        {
            if ($this->event === 'email.bounce') {
                // Custom bounce logic
            }
        }
    }
    
  3. Mocking for Tests Use Laravel’s Mockery to stub the client:

    $mock = Mockery::mock(Resend::class);
    $mock->shouldReceive('emails->send')->once()->andReturn(['success' => true]);
    $this->app->instance(Resend::class, $mock);
    
  4. Laravel Notifications Create a custom ResendChannel:

    use Resend\Resend;
    
    class ResendChannel implements ShouldQueue
    {
        public function __construct(protected Resend $resend) {}
    
        public function send($notifiable, Notification $notification)
        {
            $this->resend->emails->send([
                'from' => config('mail.from.address'),
                'to' => $notifiable->getEmailForNotification($notification),
                'subject' => $notification->subject(),
                'html' => $notification->toHtml($notifiable),
            ]);
        }
    }
    

Pro Tips

  • Use emails->list() to audit sent emails (filter by created_at).
  • Leverage contacts->upsert() to update user properties in bulk.
  • Schedule Emails: Use the schedule option for time-based sends:
    $resend->emails->send([
        'from' => 'reminders@example.com',
        'to' => 'user@example.com',
        'subject' => 'Your Reminder',
        'schedule' => ['send_at' => '2023-12-31T12:00:00Z'],
    ]);
    
  • **Monitor with `
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony