Yii2: using Swiftmailer Plugin (Openbuildings\Swiftmailer\CssInlinerPlugin)

945 views Asked by At

My yii2 application successfully sends out emails with the yii2 swiftmailer extension using the given default layout in \app\mail\layouts named html.php like

Yii::$app->mailer->compose('@app/mail/templates/myTemplate', [
    'param1' => $param1, 'param2' => $param2
])->setFrom($senderAdress)->setTo($reveiverAdress)->setSubject('Subject')->send();

Unfortunately that way css within style tags in the header is not included in the html.php as suggested by the official yii2 guide yiiframework.com/doc-2.0/guide-tutorial-mailing.html (the given example was:

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=<?= Yii::$app->charset ?>" />
    <style type="text/css">
        .heading {...}
        .list {...}
        .footer {...}
    </style>
    <?php $this->head() ?>
</head>

So I tried to include the OpenBuildings swiftmailer css-inliner-plugin by installing it via composer and including it as suggested in this tutorial by extending my web.php to:

'mailer' => [
    'class' => 'yii\swiftmailer\Mailer',
    'transport' => [
        'class'      => 'Swift_SmtpTransport', 
        'host' => 'smtp.xyz.com',
        'username'   => 'username',
        'password' => 'password',
        'port' => '587',
        'encryption' => 'tls',
        'plugins'    => [
            [
                'class' => 'Openbuildings\Swiftmailer\CssInlinerPlugin',
            ],
        ],
    ],
],

Mails are still sent without the included <style> tags content. Has anyone experience with including plugins into the yii2 swiftmailer extension? Or is there another way of using the extension so that there is no need to use swiftmailer plugins at all?

1

There are 1 answers

1
karpy47 On

A bit late, but it might help someone finding this later...

I used the same code for including the CssInlinerPlugin plugin and it worked right away. I registered some css in my mail view, like this.

$this->registerCss("
    p, td, th {text-align: left; font-size: 12px; }
    .classname {color: blue; }
"); 

...and in the mail that was sent and all html tags now had the same styles inline. So the plugin seems to work just fine.

Regarding your last question. I have not found a better way to quickly handle this for Yii2 than using this plugin. The plugin is based on the package tijsverkoyen/css-to-inline-styles, that is used in other frameworks as well.

Noticed in the source code for TijsVerkoyen\CssToInlineStyles that css-classnames are stripped from the style-tag in the mail, but the css-content is passed on to the correct tag. Maybe that could explain part of what you saw? (This behaviour is configurable of course.)