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

Mailgun Php Laravel Package

mailgun/mailgun-php

Official Mailgun PHP SDK (PSR-18/PSR-7 compatible) for sending email and managing Mailgun API features like domains, IPs/pools, analytics, and subaccounts. Works with your chosen HTTP client; supports US/EU endpoints.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require mailgun/mailgun-php symfony/http-client nyholm/psr7
    

    Laravel users can skip symfony/http-client if using Laravel's built-in HTTP client.

  2. Initialize the SDK:

    use Mailgun\Mailgun;
    
    $mg = Mailgun::create(config('mail.mailgun.api_key'), config('mail.mailgun.endpoint'));
    

    Store your API key and endpoint in Laravel's .env:

    MAIL_MAILGUN_API_KEY=your-api-key
    MAIL_MAILGUN_ENDPOINT=https://api.mailgun.net
    
  3. First Use Case: Send a test email via Laravel's Mail facade (if using Laravel):

    Mail::to('recipient@example.com')->send(new TestEmail());
    

    Or directly via the SDK:

    $mg->messages()->send('example.com', [
        'from'    => 'sender@example.com',
        'to'      => 'recipient@example.com',
        'subject' => 'Test Email',
        'text'    => 'Hello from Mailgun!'
    ]);
    

Implementation Patterns

Daily Workflows

  1. Sending Emails:

    • Transactional Emails: Use Laravel's Mail facade with the Mailgun driver.
      Mail::to('user@example.com')->send(new OrderConfirmation($order));
      
    • Bulk Emails: Use the batch() method for large campaigns.
      $mg->messages()->batch('example.com', [
          'from' => 'newsletter@example.com',
          'to'   => ['user1@example.com', 'user2@example.com'],
          'subject' => 'Weekly Newsletter',
          'text' => 'Your weekly updates...'
      ]);
      
  2. Tracking and Analytics:

    • Fetch email metrics for a specific domain:
      $metrics = $mg->metrics()->loadMetrics([
          'start' => '2023-01-01',
          'end'   => '2023-01-31',
          'metrics' => ['delivered_count', 'opened_rate']
      ]);
      
    • Integrate with Laravel's scheduling for periodic reports:
      // app/Console/Commands/EmailReport.php
      public function handle() {
          $metrics = $mg->metrics()->loadMetrics([...]);
          // Process and log metrics
      }
      
  3. IP Management:

    • Assign a dedicated IP to a domain:
      $mg->ips()->assign('example.com', '1.2.3.4');
      
    • Automate IP rotation in Laravel's booted method:
      public function booted() {
          $mg->ips()->rotate('example.com');
      }
      
  4. Dynamic IP Pools (DIPP):

    • Create a pool and link it to a domain:
      $mg->ips()->createIpPool('Primary Pool', 'Main sending pool');
      $mg->ips()->updateIpPool('pool-id', ['link_domain' => 'example.com']);
      
  5. Subaccounts:

    • Create a subaccount for a marketing team:
      $mg->subaccounts()->create('marketing-team');
      
    • Use the subaccount for sending emails:
      $subMg = Mailgun::create(config('mail.mailgun.api_key'), null, 'marketing-team');
      

Integration Tips

  • Laravel Service Provider: Bind the Mailgun client in AppServiceProvider:

    public function register() {
        $this->app->singleton('mailgun', function ($app) {
            return Mailgun::create(
                $app['config']['mail.mailgun.api_key'],
                $app['config']['mail.mailgun.endpoint']
            );
        });
    }
    

    Inject it into controllers:

    public function __construct(private Mailgun $mailgun) {}
    
  • Event Listeners: Trigger Mailgun actions on Laravel events (e.g., registered):

    public function handle($event) {
        $this->mailgun->messages()->send('example.com', [
            'from'    => 'welcome@example.com',
            'to'      => $event->user->email,
            'subject' => 'Welcome!',
            'text'    => 'Thank you for registering!'
        ]);
    }
    
  • Queue Jobs: Offload email sending to Laravel queues:

    // app/Jobs/SendWelcomeEmail.php
    public function handle() {
        $this->mailgun->messages()->send('example.com', [...]);
    }
    

Gotchas and Tips

Pitfalls

  1. Domain Verification:

    • Ensure the domain is verified in Mailgun's dashboard before sending emails. Unverified domains will fail silently or return errors.
    • Fix: Use $mg->domains()->verify('example.com') in a Laravel command or observer.
  2. Rate Limits:

    • Mailgun enforces rate limits (e.g., 100 emails/minute for shared IPs). Exceeding limits may cause temporary bans.
    • Fix: Implement exponential backoff in your sending logic or use dedicated IPs for high-volume senders.
  3. Async Operations:

    • Bulk IP operations (e.g., assignIpToAllDomains) are async. Check the status with:
      $ref = $mg->ips()->assignIpToAllDomains('1.2.3.4');
      $status = $mg->ips()->getAsyncOperationStatus($ref->getReferenceId());
      
  4. Time Zones in Scheduling:

    • Scheduled emails use UTC. Ensure o:deliverytime is in UTC format:
      'o:deliverytime' => '2023-12-25 12:00:00 UTC'
      
  5. Subaccount Scoping:

    • Forgetting to pass the subaccount ID to Mailgun::create() will default to the root account.
    • Fix: Always specify the subaccount if needed:
      $mg = Mailgun::create('api-key', null, 'subaccount-id');
      

Debugging

  1. Enable Debugging:

    • Use Postbin to inspect raw requests:
      $configurator = new HttpClientConfigurator();
      $configurator->setEndpoint('http://bin.mailgun.net/your-bin-id');
      $configurator->setDebug(true);
      $mg = new Mailgun($configurator, new NoopHydrator());
      
  2. Handle Exceptions:

    • Wrap Mailgun calls in try-catch blocks:
      try {
          $mg->messages()->send('example.com', [...]);
      } catch (Mailgun\Exception\MailgunException $e) {
          Log::error('Mailgun error: ' . $e->getMessage());
          // Retry or notify admin
      }
      
  3. Logging Responses:

    • Log raw responses for troubleshooting:
      $response = $mg->messages()->send('example.com', [...]);
      Log::debug('Mailgun response:', $response->getBody()->getContents());
      

Tips

  1. Use Hydrators for Flexibility:

    • Switch between ArrayHydrator and default model hydrators based on needs:
      $mg = new Mailgun($configurator, new ArrayHydrator());
      
  2. Leverage Laravel's Mailable Classes:

    • Combine Laravel's Mailable classes with Mailgun's features:
      // app/Mail/TestEmail.php
      public function build() {
          return $this->withSwiftMessage(function ($message) {
              $message->getHeaders()
                  ->addTextHeader('X-Tag', 'newsletter');
          });
      }
      
  3. Batch Processing:

    • Use batch() for sending to large lists efficiently:
      $users = User::where('is_active', true)->get();
      $batches = array_chunk($users->pluck('email')->toArray(), 100);
      
      foreach ($batches as $batch) {
          $mg->messages()->batch('example.com', [
              'from' => 'newsletter@example.com',
              'to'   => $batch,
              'subject' => 'Monthly Newsletter',
              'text' => 'Your updates...'
          ]);
      }
      
  4. Webhook Integration:

    • Set up webhooks in Mailgun's dashboard to trigger Laravel events:
      // routes/web.php
      Route::post('/mailgun/webhook', [MailgunWebhookController::class, 'handle']);
      
    • Use the mailgun/mailgun-php SDK to verify webhook signatures:
      use Mailgun\Webhook\Webhook;
      
      $webhook = new Webhook($request->getContent(), config('mail.mailgun.webhook_signing_key'));
      if ($webhook->isValid()) {
          //
      
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor