Обновление конфигурации swiftmailer на основе ввода пользователя - PullRequest
1 голос
/ 10 июля 2019

Мне нужно обновить конфигурацию SwiftMailer на основе пользовательского ввода, в частности, пользователь может решить отправлять электронные письма по протоколу SMTP или сохранять их локально (в папке определенной файловой системы).Пользователь будет использовать представление для выбора опции, затем контроллер перехватит решение и обновит сеанс var.Текущий подход состоит в том, чтобы прочитать этот сеанс var из config / web.php и затем выбрать соответствующую конфигурацию.

Я не уверен, загружается ли web.php только один раз во время выполнения приложения, на самом деле я не могупроверьте, активен ли сеанс, а затем получите информацию из var.Я не уверен, какой подход может быть подходящим.

Это мой config / web.php:

<?php
use yii\web\Session;

$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$session = Yii::$app->session;
if($session->isActive){
    $mailTransport = Yii::app()->session->get('emailtransport');    
}
else{ //session is not started
    $mailTransport = 'local';
}

if($mailTransport=='local'){
    $config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'aliases' => [
        '@bower' => '@vendor/bower-asset',
        '@npm'   => '@vendor/npm-asset',
    ],
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'a4ARdWYauHJ-UEAvVfagzk0LTyT_KEuZ',
        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@app/mail',
            'htmlLayout' => 'layouts/main-html', //template to Send Emails Html based
            'textLayout' => 'layouts/main-text', //template to Send Emails text based
            'messageConfig' => [
               'charset' => 'UTF-8',
               'from' => ['clients@ok.com' => 'OK Premiun Clients'],
             ], //end of messageConfig
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
            //'useFileTransport' => false,
            'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' => 'smtp.gmail.com',
            'username' => 'ok@gmail.com',
            'password' => "password",
            'port' => '465',
            'encryption' => 'ssl',
          ],
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => $db,
        /*
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
            ],
        ],
        */
    ],
    'params' => $params,
];
}//end of if loop
else{
    $config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'aliases' => [
        '@bower' => '@vendor/bower-asset',
        '@npm'   => '@vendor/npm-asset',
    ],
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'a4ARdWYauHJ-UEAvVfagzk0LTyT_KEuZ',
        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@app/mail',
            'htmlLayout' => 'layouts/main-html', //template to Send Emails Html based
            'textLayout' => 'layouts/main-text', //template to Send Emails text based
            'messageConfig' => [
               'charset' => 'UTF-8',
               'from' => ['ok@namesilo.com' => 'OK Premiun Clients'],
             ], //end of messageConfig
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => false,
            'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' => 'smtp.gmail.com',
            'username' => 'ok@gmail.com',
            'password' => "password",
            'port' => '465',
            'encryption' => 'ssl',
          ],
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => $db,
        /*
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
            ],
        ],
        */
    ],
    'params' => $params,
];
}//end of if else loop

Поскольку сеанс никогда не достигается на web.php, электронные письма всегда хранятся локально.

Ответы [ 2 ]

0 голосов
/ 11 июля 2019

Другое решение заключается в следующем: я сделал некоторые изменения, используя мой класс модели:

    public function sendMail($transport, $view, $subject, $params = []){
      //set layout params
      \Yii::$app->mailer->getView()->params['userName'] = $this->username;

      if($transport == 'local'){
        \Yii::$app->mailer->useFileTransport=true;
      }
      else{
        \Yii::$app->mailer->useFileTransport=false;
      }
      $result = \Yii::$app->mailer->compose([
          'html' => 'views/' . $view . '-html',
          'text' => 'views/' . $view . '-text',
      ], $params)->setTo([$this->email => $this->username])
          ->setSubject($subject)
          ->send();

      //reset layout params
      \Yii::$app->mailer->getView()->params['userName'] = null;
      return $result;
    } //end of sendMail

Это помогло мне упростить мой web.php, не было необходимости использовать переменные сессии.

0 голосов
/ 11 июля 2019

То, что вы пытаетесь сделать, требует от вас создания экземпляра класса yii\swiftmailer\Mailer из вашего кода и установки транспорта с помощью вызова setTransport(), а не использования его через определение компонентов в файле конфигурации.

Я приведу пример, где я буду использовать smtp.gmail.com в качестве хоста для транспорта и отправлю электронное письмо

public function actionTest(){

    //instantiate the mailer
    $mailer = new \yii\swiftmailer\Mailer(
        [
            'useFileTransport' => false
        ]
    );

    //set the transport params
    $mailer->setTransport(
        [
            'class' => 'Swift_SmtpTransport',
            'host' => 'smtp.gmail.com',
            'username' => 'username',
            'password' => 'password',
            'port' => '587',
            'encryption' => 'tls'
        ]
    );

    //to email 
    $to = "someemail@gmail.com";

    //email subject
    $subject = "this is a test mail";

    //email body 
    $body ="Some body text for email";

    //send the email
    $mailer->compose()->setTo($to)->setFrom(
        [
            'support@site.com' => 'Site Support'
        ]
    )->setTextBody($body)->setSubject($subject)->send();
}
...