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 Mailcoach Sendgrid Setup Laravel Package

spatie/laravel-mailcoach-sendgrid-setup

Helps Mailcoach prepare Sendgrid accounts to handle campaign feedback events (bounces, complaints, etc.) for emails sent via Sendgrid. Intended for internal use by Mailcoach; code is usable but has no standalone docs or support.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require spatie/laravel-mailcoach-sendgrid-setup
    

    Ensure spatie/laravel-mailcoach is also installed (this package is a dependency for SendGrid integration).

  2. Publish Configuration

    php artisan vendor:publish --provider="Spatie\MailcoachSendgridSetup\MailcoachSendgridSetupServiceProvider"
    

    This publishes the mailcoach-sendgrid-setup.php config file to config/.

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

    SENDGRID_API_KEY=your_sendgrid_api_key_here
    

    Configure the required SendGrid settings in config/mailcoach-sendgrid-setup.php:

    'api_key' => env('SENDGRID_API_KEY'),
    'from_email' => 'noreply@yourdomain.com',
    'from_name' => 'Your Company',
    
  4. Run Setup Command Execute the setup command to configure SendGrid for Mailcoach:

    php artisan mailcoach:sendgrid:setup
    

    This creates necessary SendGrid templates, categories, and API configurations.


First Use Case: Sending a Campaign

  1. Create a campaign in Mailcoach via the admin panel.
  2. Configure the campaign to use SendGrid as the mail driver in config/mail.php:
    'default' => env('MAIL_MAILER', 'mailcoach'),
    'mailers' => [
        'mailcoach' => [
            'transport' => 'sendgrid',
        ],
    ],
    
  3. Trigger the campaign via the Mailcoach UI or API. The package ensures SendGrid is pre-configured to handle Mailcoach’s tracking and feedback loops.

Implementation Patterns

Workflow: Integrating SendGrid with Mailcoach

  1. Pre-Setup

    • Verify SendGrid API key permissions include:
      • mail.send (for sending emails).
      • suppression (for managing bounces/unsubscribes).
      • templates (for dynamic template management).
    • Ensure your SendGrid account has subuser access if using shared accounts.
  2. Dynamic Template Management The package automates the creation of SendGrid dynamic templates for Mailcoach campaigns.

    • Templates are named after Mailcoach campaign IDs (e.g., mailcoach_campaign_123).
    • Use the mailcoach:sendgrid:create-template command to generate templates manually if needed:
      php artisan mailcoach:sendgrid:create-template --campaign-id=123
      
    • Template Variables: Map Mailcoach’s merge tags (e.g., {{ name }}) to SendGrid’s template variables in the config:
      'template_variables' => [
          'name' => 'Name',
          'email' => 'Email',
      ],
      
  3. Feedback Loop Configuration

    • The package sets up SendGrid’s event webhook to forward bounce/unsubscribe events to Mailcoach.
    • Configure the webhook URL in SendGrid’s Settings > Mail Settings > Event Notifications:
      https://your-app.com/mailcoach/sendgrid/webhook
      
    • Ensure your Laravel app routes the webhook to Mailcoach’s handler:
      Route::post('/mailcoach/sendgrid/webhook', [\Spatie\Mailcoach\Mailcoach::class, 'handleSendgridWebhook']);
      
  4. Batch Sending

    • Mailcoach uses SendGrid’s Async API for batch sending.
    • Configure the batch size in config/mailcoach-sendgrid-setup.php:
      'batch_size' => 100, // Emails per batch
      'delay_between_batches' => 60, // Seconds
      
  5. Testing

    • Use SendGrid’s sandbox mode for testing:
      SENDGRID_SANDBOX_MODE=true
      
    • Send test emails to verified SendGrid sandbox addresses (e.g., yourusername@yourdomain.com.sandboxXXXX.sendgrid.net).

Integration Tips

  • Laravel Queues: Ensure your queue worker is running to process Mailcoach jobs:
    php artisan queue:work
    
  • Logging: Enable SendGrid debug logging in config/mailcoach-sendgrid-setup.php:
    'debug' => env('MAILCOACH_SENDGRID_DEBUG', false),
    
  • Fallback Mailer: Configure a fallback mailer (e.g., SMTP) in config/mail.php for when SendGrid fails:
    'fallback' => [
        'transport' => 'smtp',
        'host' => env('MAIL_HOST', 'smtp.example.com'),
    ],
    
  • Webhook Verification: Verify SendGrid webhook signatures in your route handler:
    use Spatie\MailcoachSendgridSetup\Webhook\VerifySendgridWebhookSignature;
    
    Route::post('/mailcoach/sendgrid/webhook', function (Request $request) {
        if (!VerifySendgridWebhookSignature::verify($request)) {
            abort(403);
        }
        // Process webhook
    });
    

Gotchas and Tips

Pitfalls

  1. API Key Permissions

    • Issue: Missing permissions (e.g., no suppression access) cause bounces/unsubscribes to fail silently.
    • Fix: Re-generate the SendGrid API key with all required permissions or use a dedicated subuser.
  2. Template Variable Mismatches

    • Issue: Mailcoach merge tags not mapped to SendGrid template variables result in blank emails.
    • Fix: Double-check template_variables in the config and ensure SendGrid template variables match exactly (case-sensitive).
  3. Webhook Failures

    • Issue: SendGrid webhook events are ignored if the route or signature verification fails.
    • Fix:
      • Test the webhook endpoint with curl:
        curl -X POST https://your-app.com/mailcoach/sendgrid/webhook \
             -H "Content-Type: application/json" \
             -H "X-SendGrid-Signature: YOUR_SIGNATURE" \
             -d '{"event": "bounce", "email": "test@example.com"}'
        
      • Check Laravel logs for 403 Forbidden errors.
  4. Rate Limits

    • Issue: SendGrid’s rate limits (e.g., 100 emails/minute for free tier) may throttle Mailcoach campaigns.
    • Fix: Adjust batch_size and delay_between_batches in the config or upgrade your SendGrid plan.
  5. Sandbox Mode Pitfalls

    • Issue: Emails sent in sandbox mode don’t reach external recipients.
    • Fix: Disable sandbox mode before going live:
      SENDGRID_SANDBOX_MODE=false
      

Debugging Tips

  1. Enable Debug Mode Add to .env:

    MAILCOACH_SENDGRID_DEBUG=true
    

    Check logs for detailed SendGrid API responses.

  2. Inspect SendGrid Templates

    • List all SendGrid templates via API:
      curl -X GET https://api.sendgrid.com/v3/templates \
           -H "Authorization: Bearer YOUR_API_KEY"
      
    • Verify Mailcoach templates exist and are active.
  3. Test Webhook Locally Use ngrok to expose your local webhook endpoint:

    ngrok http 8000
    

    Configure SendGrid to point to https://your-ngrok-subdomain.ngrok.io/mailcoach/sendgrid/webhook.

  4. Check Mailcoach Logs Run:

    php artisan mailcoach:logs
    

    Look for Sendgrid entries to debug sending issues.


Extension Points

  1. Custom Template Naming Override the default template naming convention by extending the Spatie\MailcoachSendgridSetup\TemplateCreator class:

    namespace App\Services;
    
    use Spatie\MailcoachSendgridSetup\TemplateCreator as BaseTemplateCreator;
    
    class CustomTemplateCreator extends BaseTemplateCreator
    {
        protected function getTemplateName(int $campaignId): string
        {
            return "custom_prefix_{$campaignId}";
        }
    }
    

    Bind it in a service provider:

    $this->app->bind(
        \Spatie\MailcoachSendgridSetup\TemplateCreator::class,
        App\Services\CustomTemplateCreator::class
    );
    
  2. Additional Webhook Events Extend the webhook handler to process custom events (e.g., clicks):

    use Spatie\MailcoachSendgridSetup\Webhook\HandleSendgridWebhook;
    
    class CustomWebhookHandler extends HandleSendgridWebhook
    {
        protected function handleClickEvent(array $payload)
        {
            // Custom logic
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport