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

Fin Mail Laravel Package

finity-labs/fin-mail

FinMail adds an email template manager and composer to Filament. Create dynamic, translatable templates with token/merge-tag replacement, CTA blocks, and versioning. Send from any resource via a reusable action, with full email logging and status tracking.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require finity-labs/fin-mail
    php artisan fin-mail:install
    

    Follow prompts for locales, migrations, and plugin registration.

  2. Register Plugin:

    // app/Providers/Filament/AdminPanelProvider.php
    public function panel(Panel $panel): Panel
    {
        return $panel->plugins([
            FinMailPlugin::make(),
        ]);
    }
    
  3. First Use Case: Send an email from a Filament resource:

    use FinityLabs\FinMail\Actions\SendEmailAction;
    
    // In your resource's table actions
    SendEmailAction::make()
        ->template('welcome-email')
        ->recipient(fn ($record) => $record->user->email)
        ->models(fn ($record) => ['user' => $record->user]);
    

Where to Look First

  • Admin Panel: Navigate to Email Templates to create/edit templates.
  • Documentation: Focus on:

Implementation Patterns

Core Workflows

  1. Template Creation & Management:

    • Use the Filament UI to create templates with:
      • RichEditor (default) or Tiptap/TinyMCE (customizable).
      • Dynamic Tokens: Insert via {{ model.attribute }} or merge tags in the editor toolbar.
      • Themes: Apply color themes for consistent branding.
    • Versioning: Automatically tracks changes; restore via the UI.
  2. Sending Emails:

    • From Resources: Add SendEmailAction to table/header actions with dynamic recipients/models:
      SendEmailAction::make()
          ->template('invoice')
          ->recipient(fn ($invoice) => $invoice->customer_email)
          ->models(fn ($invoice) => ['invoice' => $invoice]);
      
    • Programmatically: Use TemplateMail with Mail::to()->send():
      Mail::to($user->email)->send(
          TemplateMail::make('welcome')
              ->models(['user' => $user])
              ->attachFile($filePath)
      );
      
  3. Token & Data Handling:

    • Tokens: Replace placeholders like {{ user.name }} or {{ config.app.name }}.
    • Extra Data: Pass variables directly to Blade templates:
      ->with('tracking_url', $tracking->url)
      // or
      ->extraData(['items' => $order->items]);
      
  4. Logging & Tracking:

    • All sent emails are logged with status (SentEmail model).
    • Add SentEmailsRelationManager to resources to view sent emails:
      public static function getRelations(): array {
          return [SentEmailsRelationManager::class];
      }
      
  5. Customization:

    • Blocks: Extend with custom RichEditor blocks (e.g., DividerBlock):
      FinMailPlugin::make()->customBlocks([\App\Mail\Blocks\MyBlock::class]);
      
    • Views: Override email layouts:
      TemplateMail::make('template')->overrideView('emails.custom');
      

Integration Tips

  • Filament Shield: Use built-in policies for access control:
    FinMailPlugin::make()->policyNamespace('App\Policies');
    
  • Multilingual: Support multiple locales via spatie/laravel-translatable.
  • Queues: Configure config/fin-mail.php for async sending:
    'queue' => [
        'connection' => 'mail',
        'queue' => 'emails',
    ],
    
  • Testing: Use php artisan fin-mail:test to send test emails.

Gotchas and Tips

Pitfalls

  1. Token Parsing Errors:

    • Issue: Tokens like {{ user.address.city }} fail if address is null.
    • Fix: Use fallbacks:
      {{ user.address.city | 'N/A' }}
      
    • Debug: Check the Tokens tab in the template editor for parsed errors.
  2. Editor Blocks Not Rendering:

    • Issue: Custom blocks appear in the editor but disappear in sent emails.
    • Fix: Ensure toHtml() returns valid HTML and implements getId().
    • Tip: Test with toPreviewHtml() first.
  3. Locale Mismatches:

    • Issue: Translated templates show [en] placeholders.
    • Fix: Run php artisan fin-mail:install with correct locales or manually publish translations:
      php artisan vendor:publish --tag=fin-mail-translations
      
  4. Attachment Limits:

    • Issue: Large attachments fail silently.
    • Fix: Configure size limits in config/fin-mail.php:
      'attachments' => [
          'max_size_mb' => 10,
      ],
      
  5. Queue Stuck Jobs:

    • Issue: Emails remain in the queue after failures.
    • Fix: Listen to EmailFailed events to retry or log:
      Event::listen(EmailFailed::class, function ($event) {
          // Retry logic or notify admins
      });
      

Debugging

  • Log Sent Emails: Enable debug mode in config/fin-mail.php:
    'debug' => env('FIN_MAIL_DEBUG', false),
    
  • Check Events: Temporarily log all events:
    Event::listen('*', function ($event) {
        logger()->debug($event::class, [$event]);
    });
    
  • Template Preview: Use the "Preview" button in the template editor to test rendering.

Extension Points

  1. Custom Token Parsers: Extend FinityLabs\FinMail\Tokens\TokenParser to add custom syntax (e.g., {{ math:add(1,2) }}):

    public function parse($token, $context): string {
        if (str_starts_with($token, 'math:')) {
            return eval("return {$token};");
        }
        return parent::parse($token, $context);
    }
    
  2. Email Validation: Override FinityLabs\FinMail\Mail\TemplateMail to add validation:

    public static function validate($template, $models, $attachments) {
        if (empty($models['user']->email)) {
            throw new \Exception('User email is required.');
        }
    }
    
  3. Dynamic Recipients: Use closures in SendEmailAction to fetch recipients dynamically:

    ->recipient(fn ($record) => $record->getEmailsForTemplate('newsletter'))
    
  4. Theme Overrides: Extend themes by publishing assets:

    php artisan vendor:publish --tag=fin-mail-themes
    

    Then modify resources/views/vendor/fin-mail/themes/custom.blade.php.

Config Quirks

  • Default Sender: Configure in config/fin-mail.php:
    'sender' => [
        'address' => 'noreply@example.com',
        'name' => 'Your App',
    ],
    
  • Attachment Rules: Restrict file types/sizes:
    'attachments' => [
        'allowed_mimes' => ['pdf', 'jpg', 'png'],
    ],
    
  • Navigation: Hide resources via plugin options:
    FinMailPlugin::make()->disableSentEmails();
    

Performance Tips

  • Cache Tokens: Pre-compile tokens for frequently used templates:
    $template->compileTokens(); // Run manually or via observer
    
  • Batch Logging: Disable logging for bulk sends:
    TemplateMail::make()->disableLogging();
    
  • Queue Batching: Use Laravel's queue batching for high-volume sends:
    Mail::later()->send($mailable);
    
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata