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

Laravel Sendgrid Driver Laravel Package

s-ichikawa/laravel-sendgrid-driver

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require s-ichikawa/laravel-sendgrid-driver
    

    Ensure compatibility with your Laravel version (e.g., ^4.0 for Laravel 9/10/11).

  2. Configuration: Add your SendGrid API key to .env:

    SENDGRID_API_KEY=your_api_key_here
    

    Publish the config file (if needed) and update config/mail.php:

    'driver' => env('MAIL_DRIVER', 'sendgrid'),
    
  3. First Use Case: Send a test email via a Mailable class or Mail::send():

    use Illuminate\Support\Facades\Mail;
    use App\Mail\TestEmail;
    
    Mail::to('recipient@example.com')->send(new TestEmail());
    

Where to Look First


Implementation Patterns

Core Workflows

  1. Sending Emails:

    • Use Laravel’s native Mail::send(), Mailable classes, or queue() for async sends.
    • Example with attachments:
      Mail::to('user@example.com')
          ->attach($pathToFile)
          ->send(new OrderShipped($order));
      
  2. Templates and Substitutions:

    • Leverage SendGrid’s Dynamic Template support:
      Mail::send([], [], function ($message) {
          $message->to('user@example.com')
                  ->subject('Welcome!')
                  ->setBody('Hello, {name}!', 'text/html')
                  ->with([
                      'name' => 'John Doe',
                  ]);
      });
      
  3. Queueing Emails:

    • Configure MAIL_QUEUE_CONNECTION in .env (e.g., database, redis) to defer sends:
      MAIL_QUEUE_CONNECTION=database
      
    • Process queued emails with Laravel’s queue workers:
      php artisan queue:work
      
  4. Testing:

    • Use Laravel’s MailFake for unit tests:
      Mail::fake();
      Mail::to('test@example.com')->send(new TestEmail());
      Mail::assertSent(TestEmail::class);
      

Integration Tips

  • Environment-Specific Configs: Use Laravel’s .env files to switch between sendgrid and other drivers (e.g., log for testing):

    MAIL_DRIVER=sendgrid  # Production
    MAIL_DRIVER=log       # Local testing
    
  • Customizing Headers: Add SendGrid-specific headers (e.g., X-SMTPAPI for tracking):

    Mail::to('user@example.com')->withSwiftMessage(function ($message) {
        $message->getHeaders()->addTextHeader('X-SMTPAPI', json_encode([
            'track' => ['opens' => true, 'clicks' => true]
        ]));
    });
    
  • Logging and Debugging: Enable SendGrid’s Event Webhook to log email events in your app:

    // In a controller or service
    $webhookUrl = route('sendgrid.webhook');
    // Configure webhook in SendGrid dashboard
    

Gotchas and Tips

Common Pitfalls

  1. API Key Security:

    • Never commit .env or hardcode API keys. Use Laravel’s .env or a secrets manager.
    • Restrict SendGrid API key permissions to only what’s needed (e.g., "Mail Send").
  2. Rate Limits:

    • SendGrid has usage limits. Monitor via the SendGrid dashboard or API.
    • Implement exponential backoff for retries if hitting limits:
      try {
          Mail::send(...);
      } catch (Exception $e) {
          if ($e->getCode() === 429) {
              sleep(10); // Retry after 10 seconds
              Mail::send(...);
          }
      }
      
  3. Attachment Size Limits:

    • SendGrid’s file size limits apply (max ~30MB per attachment). For larger files, use a CDN or URL-based attachments:
      Mail::to('user@example.com')->attach('https://cdn.example.com/large-file.pdf');
      
  4. Queue Stuck Emails:

    • If emails are stuck in the queue, check:
      • Database connection (for database queue).
      • Queue worker logs (storage/logs/laravel.log).
      • SendGrid API status (outages: SendGrid Status).

Debugging Tips

  • Enable SendGrid Debug Mode: Add this to your .env to log API responses:

    SENDGRID_DEBUG=true
    

    Check logs in storage/logs/laravel.log for raw API calls/responses.

  • Validate API Key: Test connectivity with a simple API call:

    curl -X GET "https://api.sendgrid.com/v3/user/ip" -H "Authorization: Bearer $SENDGRID_API_KEY"
    
  • Common Errors:

    • 401 Unauthorized: Invalid API key or permissions.
    • 400 Bad Request: Invalid email format or missing required fields (e.g., to).
    • 500 Internal Server Error: Check SendGrid’s API error codes.

Extension Points

  1. Custom SendGrid Client: Override the default SendGrid client by binding a custom instance in AppServiceProvider:

    use SendGrid\Mail\Mailer;
    use SendGrid\Mail\Transport;
    
    public function register()
    {
        $this->app->singleton(Mailer::class, function ($app) {
            $transport = new Transport();
            $transport->setApiKey($app['config']['mail.sendgrid.api_key']);
            return new Mailer($transport);
        });
    }
    
  2. Event Listeners: Listen to MailSent events to log or process sent emails:

    use Illuminate\Mail\Events\MessageSent;
    
    Event::listen(MessageSent::class, function (MessageSent $event) {
        logger()->info('Email sent to: ' . $event->message->getTo()[0]['address']);
    });
    
  3. Dynamic Templates: Fetch SendGrid templates dynamically at runtime:

    use SendGrid\Mail\Template;
    
    $template = Template::getInstance()
        ->setTemplateId('your_template_id')
        ->setVersion('1.0');
    
  4. Webhook Handling: Create a route to handle SendGrid event webhooks:

    Route::post('/sendgrid/webhook', function (Request $request) {
        $payload = $request->json()->all();
        // Process events (e.g., 'processed', 'dropped')
        logger()->info('SendGrid event:', $payload);
    });
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
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