从模型配置邮件程序参数 - Yii2

时间:2015-09-10 20:51:55

标签: php yii2 mailer

我正在使用Yii2,我想配置来自db的数据的邮件程序参数。

示例:

'mailer' => [ 
            'class' => 'yii\swiftmailer\Mailer',
            'enableSwiftMailerLogging' =>true,
            'useFileTransport' => false,
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => $model->getSmtpHost(),
                'username' => $model->getSmtpUser(),
                'password' => $model->getSmtpPass(),
                'port' => $model->getSmtpPort(),
                'encryption' => $model->getSmtpEncryption(),
            ],
        ]

但是从web.php无法调用模型中的方法,我试过但是抛出错误

1 个答案:

答案 0 :(得分:1)

感谢@ Onedev.Link和@arogachev的回答。这给了我一个想法,我解决了这个问题。

我解决了modyfing swiftmailer组件的问题,在 Mailer.php 中添加了这个:

use app\models\Administracion; //The model i needed for access bd
 class Mailer extends BaseMailer
{
...
...
//this parameter is for the config (web.php)
public $CustomMailerConfig = false;
...
...
...
/**
     * Creates Swift mailer instance.
     * @return \Swift_Mailer mailer instance.
     */
    protected function createSwiftMailer()
    {
        if ($this->CustomMailerConfig) {
            $model = new Administracion();

            $this->setTransport([
                'class' => 'Swift_SmtpTransport',
                'host' => $model->getSmtpHost(),
                'username' => $model->getSmtpUser(),
                'password' => $model->getSmtpPass(),
                'port' => $model->getSmtpPort(),
                'encryption' => $model->getSmtpEncryption(),
            ]);
        }

        return \Swift_Mailer::newInstance($this->getTransport());
    }

Web.php 中添加了这个:

'mailer' => [ 
            'class' => 'yii\swiftmailer\Mailer',
            'enableSwiftMailerLogging' =>true,
            'CustomMailerConfig' => true, //if its true use the bd config else set the transport here
            'useFileTransport' => false,
],