I did that. Try it. Should help.
Override base class for better usability.
use Yii; use yii\base\InvalidConfigException; use yii\base\InvalidParamException; use yii\mail\MessageInterface; use yii\swiftmailer\Mailer; class SwiftMailer extends Mailer { public $defaultLayout = "main"; public $layoutsPath; public $viewsPath; /** @inheritdoc */ public function compose($view = null, array $params = []) { if (empty($view['view']) || !is_string($view['view'])) { throw new InvalidParamException(print_r($view, true)); } if (!empty($view['layout']) && is_string($view['layout'])) { $this->setTemplate($view['layout']); } else { $this->setTemplate($this->defaultLayout); } $view = $this->setPresentation($view['view']); return parent::compose($view, $params); } private function setTemplate($template) { $this->htmlLayout = "{$this->layoutsPath}/html/{$template}"; $this->textLayout = "{$this->layoutsPath}/text/{$template}"; } private function setPresentation($view) { $result = [ 'html' => "{$this->viewsPath}/html/{$view}", 'text' => "{$this->viewsPath}/text/{$view}", ]; if (!is_readable(Yii::getAlias("{$result['text']}"))) { unset($result['text']); } return $result; } }
In config
'mailer' => [ 'class' => 'common\components\overload\SwiftMailer', 'defaultLayout' => 'main', 'layoutsPath' => '@common/mail/layouts', 'viewsPath' => '@common/mail/views', 'useFileTransport' => false, 'transport' => [ 'class' => 'Swift_SmtpTransport', ]
],
The templates and views of the letters are in
common mail layouts html main.php text main.php views html recoveryPassword.php text recoveryPassword.php
Well, use.
Yii::$app->mailer->compose(['layout' => 'main', 'view' => 'recoverPassword'], [ 'user' => $exist_user, ]) ->setFrom([Yii::$app->params['adminEmail'] => Yii::$app->name . ' robot']) ->setTo($exist_user->email) ->setSubject(Yii::t('mail', 'Linked to your account {app_name}', ['app_name' => Yii::$app->name])) ->send();