How to send params in compose method of mailer yii2

I'm trying to send one param ($id) to view layout\html.php using compose() method of mailer component. But i don't know how to get it

The code:

$id = 1;
Yii::$app->mailer->compose('\layouts\html.php', ['id' => $id])
->setSubject('Email sent from Yii2-Swiftmailer')

And in a line of my view layout\html.php

<div><?php echo $id ?></div>

Error is here!

2 answers

  • answered 2018-01-11 20:51 Ivan Ponomarev

    Compose method takes special alias in format '@app/mail/layouts/default.php' So if you are using absolute format, use @ and path (yii2 aliases)

    Reference to swift mailer you can see here:

  • answered 2018-01-11 20:51 Muhammad Omer Aslam

    You don't call a view file with compose() method like this, you should use alias like @common, @frontend or any other you are using

    You can use 2 ways

    1. You may pass additional view parameters to compose() method, which will be available inside the view files.Yii::$app->mailer->compose('@common/path/to/view', ['id' => $id]);

    2. Render HTML separately

    $body =Yii::$app->view->renderFile('@common/path/to/view-file.php',['id'=>$id])

    to render the HTML from the php file, pass it any parameters you want to like any normal view file and then attach it to the email body using setHtmlBody($body), use the following way

    $body = Yii::$app->view->renderFile ( '@common/mail/account-activation.php' , [
        'id' => $id 
            ] );
    ->setSubject('Email sent from Yii2-Swiftmailer')

    For more help see Documentation