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 Laravel Laravel Package

resend/resend-laravel

Resend integration for Laravel and Symfony Mailer. Send emails via the Resend API using a simple facade, or switch to the bundled Laravel mailer transport. Configure your RESEND_API_KEY and set MAIL_MAILER=resend to get started.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require resend/resend-laravel
    

    Ensure your project uses PHP 8.1+ and Laravel 10.x+ (or 11.x+).

  2. Configure API Key Add your Resend API key to .env:

    RESEND_API_KEY=re_123456789
    
  3. First Email (Direct API Call) Use the Resend facade to send a simple email:

    use Resend\Laravel\Facades\Resend;
    
    Resend::emails()->send([
        'from' => 'onboarding@resend.dev',
        'to' => 'user@example.com',
        'subject' => 'Hello from Resend!',
        'html' => '<p>This is a test email.</p>',
    ]);
    
  4. Laravel Mailer Integration Configure config/mail.php:

    'resend' => [
        'transport' => 'resend',
    ],
    

    Update .env:

    MAIL_MAILER=resend
    

    Now use Laravel’s Mail facade as usual:

    Mail::to('user@example.com')->send(new WelcomeEmail());
    

Implementation Patterns

Core Workflows

1. Sending Emails

  • Direct API Calls (for non-Mailable use cases):

    Resend::emails()->send([
        'from' => 'team@yourdomain.com',
        'to' => ['user1@example.com', 'user2@example.com'],
        'subject' => 'Your Order Confirmation',
        'html' => view('emails.order', ['order' => $order]),
        'attachments' => [
            ['filename' => 'invoice.pdf', 'content' => file_get_contents('path/to/invoice.pdf')],
        ],
        'headers' => ['X-Custom-Header' => 'value'],
    ]);
    
    • Key Methods:
      • send(): Send immediately.
      • create(): Prepare a draft (useful for queuing).
      • sendLater(): Schedule for later (requires resend/resend-php v1+).
  • Laravel Mailable Integration: Extend Laravel’s Mailable class and attach files:

    public function build()
    {
        return $this->subject('Welcome!')
                    ->markdown('emails.welcome')
                    ->with(['name' => $user->name])
                    ->attach('path/to/file.pdf', [
                        'as' => 'document.pdf',
                        'mime' => 'application/pdf',
                    ]);
    }
    

2. Webhook Handling

  • Middleware for Incoming Webhooks: Add to app/Http/Kernel.php:
    protected $middleware = [
        // ...
        \Resend\Laravel\Http\Middleware\VerifyWebhookSignature::class,
    ];
    
    • Route Webhook Endpoint:
      Route::post('/resend-webhook', [ResendWebhookController::class, 'handle']);
      
    • Controller Logic:
      public function handle(Request $request)
      {
          $event = Resend::webhooks()->parse($request->getContent());
          // Handle event (e.g., email.delivered, contact.created)
          return response()->json(['status' => 'success']);
      }
      

3. Advanced Features

  • Tags and Idempotency:
    Resend::emails()->send([
        'from' => 'team@yourdomain.com',
        'to' => 'user@example.com',
        'subject' => 'Newsletter',
        'html' => '<p>Monthly update</p>',
        'tags' => ['marketing', 'newsletter'],
        'idempotency_key' => 'unique-key-123', // Prevent duplicate sends
    ]);
    
  • Inline Attachments (e.g., images in HTML):
    Resend::emails()->send([
        'from' => 'team@yourdomain.com',
        'to' => 'user@example.com',
        'html' => '<p><img src="cid:logo" /></p>',
        'attachments' => [
            [
                'filename' => 'logo.png',
                'content' => file_get_contents('path/to/logo.png'),
                'content_id' => 'logo', // Matches `cid:` in HTML
            ],
        ],
    ]);
    

4. Queued Emails

Use Laravel’s queue system with the Resend mailer:

Mail::to('user@example.com')->queue(new WelcomeEmail());
  • Queue Worker: Run php artisan queue:work to process emails asynchronously.

Integration Tips

  1. Environment-Specific Configs: Publish the config file for customization:

    php artisan vendor:publish --tag="resend"
    

    Modify config/resend.php for:

    • Default from address.
    • API key fallback (e.g., for staging).
  2. Testing:

    • Use Resend::emails()->mock() to intercept calls in tests:
      Resend::emails()->mock()
          ->shouldReceive('send')
          ->once()
          ->withArgs([...]);
      
    • Test webhooks with:
      $event = Resend::webhooks()->parse($rawPayload);
      $this->assertEquals('email.delivered', $event->type);
      
  3. Error Handling: Wrap API calls in try-catch:

    try {
        Resend::emails()->send([...]);
    } catch (\Resend\Exceptions\ResendException $e) {
        Log::error('Resend error: ' . $e->getMessage());
        // Retry or notify admin
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure:

    • Never commit .env to version control. Use Laravel’s .env.example for templates.
    • Restrict API keys to specific IPs in Resend’s dashboard if possible.
  2. Attachment Size Limits:

    • Resend’s free tier has a 30MB attachment limit. Validate file sizes before sending:
      if ($file->getSize() > 30 * 1024 * 1024) {
          throw new \Exception('File too large for Resend.');
      }
      
  3. Webhook Delays:

    • Resend webhooks are eventually consistent. Avoid relying on real-time updates for critical actions (e.g., order fulfillment). Use retries with exponential backoff:
      $attempts = 0;
      while ($attempts < 3) {
          try {
              $event = Resend::webhooks()->parse($payload);
              break;
          } catch (\Exception $e) {
              $attempts++;
              sleep(2 ** $attempts); // Exponential backoff
          }
      }
      
  4. HTML Email Rendering:

    • Resend strips inline CSS by default. Use tools like Premailer to inline styles in your Blade/Mailable templates:
      $html = Premailer::instance()->transform($html);
      
  5. Idempotency Key Conflicts:

    • Reusing the same idempotency_key for duplicate sends may silently fail. Generate unique keys for critical emails:
      $idempotencyKey = Str::uuid()->toString();
      

Debugging Tips

  1. Enable Resend Debugging: Add to .env:

    RESEND_DEBUG=true
    

    Logs will include request/response payloads for troubleshooting.

  2. Inspect Raw API Calls: Use Laravel’s logging to dump the payload before sending:

    $payload = [
        'from' => '...',
        'to' => '...',
        // ...
    ];
    Log::debug('Resend payload', $payload);
    Resend::emails()->send($payload);
    
  3. Webhook Signature Verification: If webhooks fail with signature errors:

    • Verify the RESEND_WEBHOOK_SECRET in .env matches Resend’s dashboard.
    • Ensure the request includes the Resend-Signature header.
  4. Rate Limiting: Resend enforces rate limits (~1,000 emails/hour for free tier). Monitor usage via:

    $usage = Resend::usage()->get();
    Log::info('Resend usage:', $usage->toArray());
    

Extension Points

  1. Custom Transport: Extend the ResendTransport class to add domain-specific logic:
    namespace App\Mail\Transports;
    
    use Resend\Laravel\Transports\ResendTransport;
    
    class CustomResendTransport extends ResendTransport
    
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager