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

Yii2 Symfonymailer Laravel Package

yiisoft/yii2-symfonymailer

Yii2 extension integrating Symfony Mailer for reliable email sending. Configure SMTP/DSN transport, templates via viewPath, and file transport for dev. Supports PHP 8.1+ and installs via Composer for seamless Yii 2.0 mail delivery.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require yiisoft/yii2-symfonymailer
    

    Add to config/web.php (or console.php for CLI):

    'components' => [
        'mailer' => [
            'class' => 'yiisoft\yii2\symfonymailer\Mailer',
            'transport' => [
                'dsn' => 'smtp://user:pass@smtp.example.com:587',
                // OR for API-based (e.g., SendGrid):
                // 'dsn' => 'sendgrid://api_key@default',
            ],
        ],
    ],
    
  2. First Use Case Send a basic email in a controller:

    use yii\base\View;
    use yii\mail\BaseMailer;
    
    public function actionSendWelcome()
    {
        Yii::$app->mailer->compose()
            ->setTo('user@example.com')
            ->setSubject('Welcome!')
            ->setTextBody('Thanks for signing up!')
            ->send();
    }
    
  3. Key Files to Review

    • vendor/yiisoft/yii2-symfonymailer/src/Mailer.php (core class)
    • config/mail.php (Symfony Mailer config reference)
    • Symfony Mailer Docs (for transport options)

Implementation Patterns

Common Workflows

1. Dynamic Transport Switching

Use environment variables or config to toggle transports (e.g., dev/staging/prod):

'transport' => [
    'dsn' => getenv('MAILER_DSN') ?: 'smtp://localhost',
],

2. HTML + Embedded Assets

Leverage Symfony’s EmbeddedFile for CSS/JS:

$message = (new \Symfony\Component\Mime\Email())
    ->html(Yii::$app->view->render('emails/welcome', ['user' => $user]))
    ->embedFromDir(__DIR__ . '/assets', '.css');
Yii::$app->mailer->send($message);

3. Queueing Emails

Use Symfony’s MailerInterface with a queue transport (e.g., doctrine://default):

'transport' => [
    'dsn' => 'doctrine://default',
],

Note: Requires Symfony Messenger integration.

4. Attachments

$message->attachFromPath(__DIR__ . '/file.pdf');
// OR for dynamic content:
$message->attach(new \Symfony\Component\Mime\Part\StringPart(
    file_get_contents($filePath),
    'application/pdf'
));

5. Testing

Use the null transport for tests:

'transport' => ['dsn' => 'null://default'],

Capture sent emails with:

$mailer = Yii::$app->mailer;
$sent = $mailer->send($message);
$this->assertCount(1, $mailer->getSentMessages());

Integration Tips

Yii 2.x Integration

  • View Rendering: Use Yii::$app->view to render email templates (e.g., emails/welcome.php).
  • Event Handling: Attach to yii\mail\MessageEvent for pre-send modifications:
    Yii::$app->mailer->on(\yii\mail\MessageEvent::EVENT_BEFORE_SEND, function ($event) {
        $event->message->getHeaders()->addTextHeader('X-Custom', 'value');
    });
    

Symfony Mailer Features

  • Retry Logic: Configure retries in DSN (e.g., smtp://?retries=3).
  • API Transports: Use mailgun://, sendgrid://, or postmark:// for cloud providers.
  • Async Sending: Pair with Symfony Messenger for background processing.

Performance

  • Reuse Connections: Symfony Mailer pools connections by default. For high-volume, consider:
    'transport' => [
        'dsn' => 'smtp://user:pass@smtp.example.com:587',
        'options' => [
            'connection_pool' => true,
            'max_connections' => 5,
        ],
    ],
    

Gotchas and Tips

Pitfalls

  1. DSN Format Strictness

    • Incorrect DSN formats (e.g., missing //) throw cryptic errors. Validate with:
      use Symfony\Component\Mailer\Transport\Dsn;
      $dsn = new Dsn('smtp://user:pass@host:port');
      
    • Common fixes:
      • URL-encode credentials: smtp://user%40domain:pass@host.
      • Use ? for options: smtp://?encryption=ssl&auth_mode=login.
  2. Attachment Encoding

    • Binary files (e.g., PDFs) may corrupt if not base64-encoded. Use EmbeddedFile or StringPart with proper MIME types.
  3. Yii 2.x Mailer Compatibility

    • The package wraps Symfony Mailer but exposes Yii’s yii\mail\BaseMailer interface. Some methods (e.g., sendMultiple()) may behave differently. Check the source for supported methods.
  4. Queue Transports

    • doctrine:// requires Symfony Messenger. For Yii-only projects, use amqp:// or redis:// with a queue worker.
  5. HTML Email Quirks

    • Symfony’s Email class escapes HTML by default. For raw HTML, use:
      $message->html($html, 'text/html', ['charset' => 'UTF-8']);
      

Debugging

  1. Enable Symfony Mailer Debug Add to config:

    'transport' => [
        'dsn' => 'smtp://user:pass@host?debug=1',
    ],
    

    Logs appear in Symfony’s debug toolbar or var/log/dev.log.

  2. SMTP Debugging Use a local SMTP server (e.g., MailHog) for testing:

    'transport' => [
        'dsn' => 'smtp://mailhog:1025',
    ],
    

    Access MailHog at http://localhost:8025.

  3. Common Errors

    • "Connection refused": Verify DSN host/port and firewall rules.
    • "Authentication failed": Check credentials and auth_mode (e.g., ?auth_mode=cram-md5).
    • "Invalid header": Use addTextHeader() for custom headers, not add().

Tips

  1. Environment-Specific Configs Use config/params.php or environment variables to manage transports:

    'mailer' => [
        'class' => 'yiisoft\yii2\symfonymailer\Mailer',
        'transport' => ['dsn' => Yii::$app->params['mailer_dsn']],
    ],
    
  2. Template Inheritance Extend Yii’s View for email layouts:

    // views/layouts/email.php
    <html>
    <body>
        <?php echo $content; ?>
        <footer>© <?php echo date('Y'); ?></footer>
    </body>
    </html>
    
  3. Rate Limiting For API transports (e.g., SendGrid), handle rate limits with retries:

    'transport' => [
        'dsn' => 'sendgrid://key@default',
        'options' => [
            'max_retries' => 3,
            'retry_delay' => 1000, // ms
        ],
    ],
    
  4. Custom Transports Extend yiisoft\yii2\symfonymailer\Mailer to add proprietary transports:

    class CustomMailer extends \yiisoft\yii2\symfonymailer\Mailer {
        public function getTransport() {
            return new \Symfony\Component\Mailer\Transport\CustomTransport();
        }
    }
    
  5. Localization Use Symfony’s Email with locale-aware headers:

    $message->getHeaders()->addTextHeader('Content-Language', 'en-US');
    
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
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
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation
uri-template/tests