How to use database for mail settings in Laravel

后端 未结 4 790
伪装坚强ぢ
伪装坚强ぢ 2021-02-06 15:51

I\'d like to keep users away from editing configuration files, so I\'ve made web interface in admin panel for setting up Mail server, username, password, port, encryption.. I w

4条回答
  •  故里飘歌
    2021-02-06 16:31

    To archive this I created CustomMailServiceProvider by extending Illuminate\Mail\MailServiceProvider so as to overwrite this method:

    protected function registerSwiftTransport(){
        $this->app['swift.transport'] = $this->app->share(function($app)
        {
        return new TransportManager($app);
        });
    }
    

    Here is the complete solution

    1. I created CustomMailServiceProvider.php in app\Providers

    namespace App\Providers;
    
    use Illuminate\Mail\MailServiceProvider;
    use App\Customs\CustomTransportManager;
    
    class CustomMailServiceProvider extends MailServiceProvider{
    
        protected function registerSwiftTransport(){
            $this->app['swift.transport'] = $this->app->share(function($app)
            {
                return new CustomTransportManager($app);
            });
        }
    }
    
    1. I created CustomTransportManager.php in app/customs directory - NB: app/customs directory doesn't exist in default laravel 5 directory structure, I created it

    namespace App\Customs;
    
    use Illuminate\Mail\TransportManager;
    use App\Models\Setting; //my models are located in app\models
    
    class CustomTransportManager extends TransportManager {
    
        /**
         * Create a new manager instance.
         *
         * @param  \Illuminate\Foundation\Application  $app
         * @return void
         */
        public function __construct($app)
        {
            $this->app = $app;
    
            if( $settings = Setting::all() ){
    
                $this->app['config']['mail'] = [
                    'driver'        => $settings->mail_driver,
                    'host'          => $settings->mail_host,
                    'port'          => $settings->mail_port,
                    'from'          => [
                    'address'   => $settings->mail_from_address,
                    'name'      => $settings->mail_from_name
                    ],
                    'encryption'    => $settings->mail_encryption,
                    'username'      => $settings->mail_username,
                    'password'      => $settings->mail_password,
                    'sendmail'      => $settings->mail_sendmail,
                    'pretend'       => $settings->mail_pretend
               ];
           }
    
        }
    }
    
    1. And finally, I replaced 'Illuminate\Mail\MailServiceProvider', in config/app.php with 'App\Providers\CustomMailServiceProvider',

提交回复
热议问题