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

Email Bundle Laravel Package

azine/email-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation

    composer require azine/email-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Azine\EmailBundle\AzineEmailBundle::class => ['all' => true],
        Knp\Bundle\PaginatorBundle\KnpPaginatorBundle::class => ['all' => true],
    ];
    

    Add routes in config/routes.yaml:

    azine_email_bundle:
        resource: "@AzineEmailBundle/Resources/config/routing.yml"
    
  2. Configure Swiftmailer Ensure swiftmailer is configured in config/packages/swiftmailer.yaml (e.g., SMTP or Mailgun).

  3. Set Up Recipient Class Define your user entity (e.g., App\Entity\User) as the recipient_class in config/packages/azine_email.yaml:

    azine_email:
        recipient_class: App\Entity\User
        no_reply:
            email: no-reply@example.com
            name: 'Your App'
        template_provider: azine_email.example.template_provider  # Custom service (see below)
    
  4. Create a Custom Notifier Service Extend AzineNotifierService (e.g., src/Service/CustomNotifierService.php) and implement methods like:

    public function getVarsForNotificationsEmail() { ... }
    public function getRecipientVarsForNotificationsEmail($recipient) { ... }
    

    Register it as a service in config/services.yaml:

    services:
        App\Service\CustomNotifierService:
            tags: ['azine_email.notifier_service']
    
  5. Send Your First Email Use the AzineEmailBundle in a controller:

    use Azine\EmailBundle\Service\AzineNotifierService;
    
    public function sendWelcomeEmail(User $user)
    {
        $notifier = $this->container->get('azine_email.notifier_service');
        $notifier->sendNotificationEmail($user, 'welcome', ['name' => $user->getName()]);
    }
    

Implementation Patterns

Core Workflows

  1. Transactional Emails (Notifications)

    • Use sendNotificationEmail() for one-off emails (e.g., password resets, order confirmations).
    • Pass recipient-specific data via the $params array:
      $notifier->sendNotificationEmail($user, 'order_confirmation', [
          'order_id' => $order->getId(),
          'total' => $order->getTotal(),
      ]);
      
    • Override getRecipientVarsForNotificationsEmail() to customize per-recipient content.
  2. Newsletters

    • Schedule emails via cron (see Operations).
    • Use sendNewsletter() for bulk emails:
      $notifier->sendNewsletter('weekly_update', [
          'promo_code' => 'SUMMER20',
      ]);
      
    • Implement getRecipientSpecificNewsletterContentItems() to personalize content.
  3. Template Customization

    • Extend AzineTemplateProvider to modify styles/images:
      class CustomTemplateProvider extends AzineTemplateProvider
      {
          public function getStyles()
          {
              return [
                  'header' => 'font-family: Arial; color: #333;',
                  // Override default styles
              ];
          }
      }
      
    • Register the service in config/services.yaml:
      services:
          azine_email.example.template_provider:
              class: App\Service\CustomTemplateProvider
              tags: ['azine_email.template_provider']
      
  4. Tracking and Analytics

    • Enable open tracking via email_open_tracking_url in config:
      azine_email:
          email_open_tracking_url: 'https://your-piwik.com/tracker.php'
      
    • Add campaign parameters to links automatically:
      {% addCampaignParamsForTemplate link path='utm_source=newsletter' %}
      <a href="{{ link }}">Click here</a>
      
  5. Web Preview

    • Store sent emails for 90 days (configurable via web_view_retention).
    • Access previews via /azine/email/webview/{id}.
    • Implement WebViewServiceInterface to customize storage/rendering.

Integration Tips

  • Queue Emails for Background Processing Use Symfony Messenger or a cron job to process spooled emails:
    php bin/console azine:email:send-spooled
    
  • Dynamic Recipient Lists Implement RecipientProviderInterface to fetch recipients dynamically (e.g., from a database query).
  • Multi-Mailer Setup Configure separate mailers for "normal" vs. "urgent" emails:
    azine_email:
        template_twig_swift_mailer:
            urgent: azine_email.urgent_mailer
            normal: azine_email.default_mailer
    
  • Local Testing Use a local SMTP server (e.g., MailHog) to preview emails:
    swiftmailer:
        transport: smtp://mailhog:1025
    

Gotchas and Tips

Pitfalls

  1. X-Frame-Options Header Ensure X-Frame-Options is set to SAMEORIGIN in .htaccess or nginx.conf to avoid iframe errors in the web preview:

    Header set X-Frame-Options "SAMEORIGIN"
    
  2. Image Embedding

    • Gmail/Thunderbird may block embedded images if:
      • Multiple recipients are visible.
      • The "From" address doesn’t match the recipient’s account.
    • Fix: Design emails to work without images (use inline styles).
  3. Cron Job Dependencies

    • Newsletters rely on cron jobs for scheduling. Test locally with:
      php bin/console azine:email:send-newsletter --dry-run
      
  4. Template Caching

    • Clear Twig cache after modifying templates:
      php bin/console cache:clear
      
  5. Doctrine Migrations

    • Run migrations after installing the bundle to create notification and sent_email tables:
      php bin/console doctrine:migrations:diff
      php bin/console doctrine:migrations:migrate
      

Debugging Tips

  • Check Spooled Emails View pending emails in the database:
    SELECT * FROM notification WHERE status = 'spooled';
    
  • Test Email Rendering Use the preview feature at /azine/email/preview/{id} to debug HTML/TXT rendering.
  • Log Swiftmailer Errors Enable Swiftmailer logging in config/packages/monolog.yaml:
    handlers:
        swiftmailer:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.swiftmailer.log"
            level: debug
    

Extension Points

  1. Custom Tracking Codes Extend AzineEmailOpenTrackingCodeBuilder to support custom analytics tools:

    class CustomTrackingBuilder implements AzineEmailOpenTrackingCodeBuilderInterface
    {
        public function buildTrackingCode($emailId, $recipientEmail)
        {
            return '<img src="https://your-tool.com/track?email=' . $emailId . '" width="1" height="1" />';
        }
    }
    

    Register it in config/services.yaml:

    services:
        azine.email.open.tracking.code.builder.custom:
            class: App\Service\CustomTrackingBuilder
            tags: ['azine_email.email_open_tracking_code_builder']
    
  2. Override Default Templates Copy templates from vendor/azine/email-bundle/Azine/EmailBundle/Resources/views/ to templates/azine_email/ to customize without extending the bundle.

  3. Add Custom Email Types Extend the Notification entity or create a new entity to support additional email categories (e.g., "promotions").

  4. Batch Processing Use the AzineEmailBundle’s batch API to send emails in chunks:

    $notifier->sendBatchNotificationEmail($recipients, 'promotion', $params, 100);
    

Configuration Quirks

  • Newsletter Interval The interval in azine_email.newsletter is in days. Set to 0 for immediate sending (not recommended for production).
  • Allowed Images Folders Use allowed_images_folders to restrict embedded images to specific paths (security):
    azine_email:
        allowed_images_folders:
            - '%kernel.project_dir%/public/uploads/email_images'
    
  • No-Reply Address The no_reply config must include both email and name fields. Omitting either will cause errors.

Performance Tips

  • Database Indexes Add indexes to notification and sent_email tables
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware