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

Postmark Swiftmailer Bundle Laravel Package

accord/postmark-swiftmailer-bundle

Symfony2 bundle adding a Postmark transport for SwiftMailer. Configure your Postmark API key (and optional SSL) and set Swiftmailer transport to accord_postmark to send email through Postmark.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer

    composer require accord/postmark-swiftmailer-bundle:dev-master
    

    (Note: Use a stable version if available; dev-master is unstable.)

  2. Register the Bundle Add to app/AppKernel.php:

    new Accord\PostmarkSwiftMailerBundle\AccordPostmarkSwiftMailerBundle(),
    
  3. Configure API Key Add to app/config/config.yml:

    accord_postmark_swift_mailer:
        api_key: "%env(POSTMARK_API_KEY)%"  # Use env vars for security
        use_ssl: true
    
  4. Set SwiftMailer Transport

    swiftmailer:
        transport: accord_postmark
    
  5. First Test Send a test email in a controller:

    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    
    class MailController extends Controller
    {
        public function sendTestEmail()
        {
            $message = (new \Swift_Message('Test Email'))
                ->setFrom('sender@example.com')
                ->setTo('recipient@example.com')
                ->setBody('Hello from Postmark!');
            $this->get('mailer')->send($message);
            return new Response('Email sent!');
        }
    }
    

Implementation Patterns

Core Workflow

  1. Configuration

    • Centralize API keys in config.yml or .env (recommended).
    • Override use_ssl if needed (e.g., for testing with false).
  2. Email Sending

    • Use Symfony’s Mailer service (autowired via DI):
      public function __construct(\Swift_Mailer $mailer) { ... }
      
    • Chain SwiftMailer methods for clarity:
      $message = (new \Swift_Message('Subject'))
          ->setFrom('no-reply@domain.com')
          ->setTo(['user@example.com', 'admin@example.com'])
          ->setBody($htmlContent, 'text/html')
          ->addPart($plainText, 'text/plain');
      $mailer->send($message);
      
  3. Templates & Attachments

    • Use SwiftMailer’s built-in methods:
      $message->attach(\Swift_Attachment::fromPath('/path/to/file.pdf'));
      
    • For templates, leverage Twig with SwiftMailer:
      {# templates/emails/welcome.html.twig #}
      <p>Hello {{ user.name }}!</p>
      
      $message->setBody(
          $this->renderView('emails/welcome.html.twig', ['user' => $user]),
          'text/html'
      );
      
  4. Batch Sending

    • Use SwiftMailer's batch() for bulk emails:
      $mailer->batch(function (\Swift_Message $message, $failedRecipients) {
          $message->setTo($recipient->email);
          $message->setBody($this->renderTemplate($recipient));
      }, $recipients);
      
  5. Async Processing

    • Offload emails to a queue (e.g., Symfony Messenger or Laravel Queues) to avoid timeouts:
      $this->get('messenger')->dispatch(
          new SendEmailMessage($message)
      );
      

Gotchas and Tips

Pitfalls

  1. API Key Exposure

    • Risk: Hardcoding keys in config.yml violates security best practices.
    • Fix: Use environment variables (%env(POSTMARK_API_KEY)%) and .env files.
      # config/packages/accord_postmark.yaml
      accord_postmark_swift_mailer:
          api_key: "%env(POSTMARK_API_KEY)%"
      
  2. SSL Warnings

    • Issue: use_ssl: false may trigger Postmark’s API warnings.
    • Fix: Set use_ssl: true in production; use a local tunnel (e.g., ngrok) for testing.
  3. Rate Limits

    • Problem: Postmark throttles requests (~100 emails/sec by default).
    • Solution: Implement exponential backoff or queue emails:
      $this->get('messenger')->dispatch(
          new SendEmailMessage($message),
          ['delay' => 1000] // 1-second delay
      );
      
  4. Debugging Failures

    • Logs: Enable SwiftMailer logging in config/packages/monolog.yaml:
      handlers:
          swiftmailer:
              type: stream
              path: "%kernel.logs_dir%/swiftmailer.log"
              level: debug
      
    • Postmark API: Check the Postmark API dashboard for rejected emails.
  5. Bundle Compatibility

Tips

  1. Testing

    • Use Postmark’s sandbox mode for testing:
      accord_postmark_swift_mailer:
          api_key: "YOUR_SANDBOX_KEY"
          use_ssl: false
      
    • Mock the Swift_Mailer service in PHPUnit:
      $this->mailer = $this->createMock(\Swift_Mailer::class);
      $this->mailer->expects($this->once())
          ->method('send')
          ->with($this->isInstanceOf(\Swift_Message::class));
      
  2. Performance

    • Batch Emails: Reduce API calls by batching emails (e.g., 50 emails per request).
    • Caching: Cache templates if sending identical emails (e.g., password resets).
  3. Extensions

    • Custom Events: Subscribe to SwiftMailer events for logging/analytics:
      $mailer->getEventDispatcher()->addListener(
          'sent',
          function (\Swift_Events_SendEvent $event) {
              // Log sent emails
          }
      );
      
    • Retry Logic: Implement a retry decorator for failed emails:
      $mailer = new RetryMailerDecorator($this->mailer, 3);
      
  4. Monitoring

    • Track email metrics (opens, clicks) via Postmark’s webhooks:
      // Configure webhook URL in Postmark dashboard
      $message->getHeaders()->addTextHeader('X-Postmark-Webhook', 'https://your-app.com/webhook');
      
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.
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
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours