Search by

yiisoft / yii2-symfonymailer

samdarkcebeSilverFirehiqsol

The SymfonyMailer integration for the Yii framework

Package info

github.com/yiisoft/yii2-symfonymailer

Forum

Wiki

Type:yii2-extension

pkg:composer/yiisoft/yii2-symfonymailer

Fund package maintenance!

Open Collective

yiisoft

Tidelift

Statistics

Installs: 5 222 773

Dependents: 90

Suggesters: 6

Stars: 47

Open Issues: 1

4.0.0 2024-01-29 14:13 UTC

This package is auto-updated.

Last update: 2026-11-25 10:14:02 UTC


README

Yii Framework

Yii2 Symfony Mailer Extension


This extension provides a Symfony Mailer mail solution for Yii framework 2.0.

Latest Stable Version Total Downloads Build Status codecov Static Analysis

Installation

Important

  • The minimum required PHP version is PHP 8.1.

The preferred way to install this extension is through composer:

php composer.phar require --prefer-dist yiisoft/yii2-symfonymailer

Usage

To use this extension, simply add the following code in your application configuration:

return [
    //....
    'components' => [
        'mailer' => [
            'class' => \yii\symfonymailer\Mailer::class,
            'transport' => [
                'scheme' => 'smtps',
                'host' => '',
                'username' => '',
                'password' => '',
                'port' => 465,
                'dsn' => 'native://default',
            ],
            'viewPath' => '@common/mail',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure transport
            // for the mailer to send real emails.
            'useFileTransport' => false,
        ],
    ],
];

or

return [
    //....
    'components' => [
        'mailer' => [
            'class' => \yii\symfonymailer\Mailer::class,
            'transport' => [
                'dsn' => 'smtp://user:pass@smtp.example.com:25',
            ],
        ],
    ],
];

You can then send an email as follows:

Yii::$app->mailer->compose('contact/html')
     ->setFrom('from@domain.com')
     ->setTo($form->email)
     ->setSubject($form->subject)
     ->send();

DI Container

The Mailer component will automatically use the DI container when it is available. This allows you to easily override the transport factory configurations or their dependencies.

Serializing messages

A message can be passed to PHP's serialize() function, for example to store it or to hand it to a queue job, and sent after it is restored with unserialize():

$message = Yii::$app->mailer->compose('contact/html')
    ->setFrom('from@domain.com')
    ->setTo($form->email)
    ->setSubject($form->subject);

$payload = serialize($message);
// Later, possibly in another process.
$message = unserialize($payload);

$message->send();

The payload holds the Symfony email and the charset. The mailer property is not serialized, so a restored message is sent through the mailer application component unless you pass a mailer to send().

Important

  • Only unserialize payloads that come from a trusted source.
  • Files added with attach() or embed() are stored as a path and read when the message is sent, so the file must still exist at that path. Content added with attachContent() or embedContent() is stored in the payload.

Extending the message class

A class that extends Message without adding state is serialized as is. A class that adds its own state must include it in the payload: override __serialize() and __unserialize(), and call the parent implementation in both.

namespace app\mail;

use yii\symfonymailer\Message;

final class TenantMessage extends Message
{
    public string $tenant = '';

    public function __serialize(): array
    {
        return parent::__serialize() + ['tenant' => $this->tenant];
    }

    public function __unserialize(array $data): void
    {
        parent::__unserialize($data);

        $this->tenant = $data['tenant'];
    }
}

Then set the class in the mailer configuration:

'mailer' => [
    'class' => \yii\symfonymailer\Mailer::class,
    'messageClass' => \app\mail\TenantMessage::class,
],

Upgrading from 4.x

Version 5.0 replaces Message::__sleep() with __serialize() and __unserialize().

  • Payloads written by earlier versions for the Message class can still be unserialized.
  • If a subclass defines __sleep() or __wakeup(), move that logic to __serialize() and __unserialize(). PHP no longer calls the old hooks, and the base implementation does not restore subclass state.
  • If a subclass already implements the new hooks, make sure its signatures are compatible with __serialize(): array and __unserialize(array $data): void.
  • If subclass messages are already queued, drain them with 4.x workers before upgrading, or make the subclass's __unserialize() read its state from both the old and new payload formats.

Migrating from yiisoft/yii2-swiftmailer

To migrate from the deprecated yiisoft/yii2-swiftmailer to this extension you need to update the application config.

Swiftmailer default transport was the SendmailTransport, while with this extension it will default to a NullTransport (sends no mail). You can use the swiftmailer default like the following:

'mailer' => [
    'class' => yii\symfonymailer\Mailer::class,
    'transport' => [
        'dsn' => 'sendmail://default',
    ],
],

With this extension, you do not have an ability of directly setting timeout, or other configurations that were possible with Swiftmailer extension. The reason is, the underlying Symfony package defines its classes as final thereby discouraging inheritance and pushing towards composition.

To achieve timeout, for example (and other transport configurations supported), you will need to define factory class and override default transport factory you are interested to replace through Yii DI container definitions.

Below is an example that shows you how to override timeout.

First define your custom factory class.

namespace app\utils;

use Symfony\Component\Mailer\Transport\Dsn;
use Symfony\Component\Mailer\Transport\Smtp\SmtpTransport;
use Symfony\Component\Mailer\Transport\TransportFactoryInterface;
use Symfony\Component\Mailer\Transport\TransportInterface;
use yii\base\BaseObject;

final class CustomSmtpFactory extends BaseObject implements TransportFactoryInterface
{
    public float $timeout;

    public function create(Dsn $dsn): TransportInterface
    {
        $transport = $this->create($dsn);
        if ($transport instanceof SmtpTransport) {

            /** @var SocketStream $stream */
            $stream = $transport->getStream();
            $stream->setTimeout($this->timeout);
        }
        return $transport;
    }

    public function supports(Dsn $dsn): bool
    {
        return $dsn->getScheme() == 'smtp';
    }
}

Then in the root of web configuration, set the factory class in container definitions, thereby overriding the default class.

'container' => [
    'definitions' => [
        EsmtpTransportFactory::class => [
            'class' => \app\utils\CustomSmtpFactory::class,
            'timeout' => 143, //Configure it to your own timeout
        ],
        // ... other definitions
    ],
],

That is all you need to do. The extension should use your new class and its configuration settings.

Security implications of the DSN

While the DSN might seem like a simple way to allow user configurable mailer settings it should be noted that the sendmail transport allows for execution of local executables. If you need to have a user configurable DSN (which is easier to build and more powerful to use than creating a GUI) you should probably disable the sendmail transport. Any user who has the power to configure a DSN essentially has shell access to wherever the code is running.

Documentation

Security

Zizmor OpenSSF Scorecard

GitHub Actions workflows are analyzed by zizmor for supply-chain vulnerabilities and workflow misconfigurations. Supply-chain security is tracked via the OpenSSF Scorecard, which evaluates security practices across the repository.

Support the project

Open Collective

Follow updates

Official website Follow on X Telegram Slack

License

License