【问题标题】:dynamic mail configuration using Laravel使用 Laravel 进行动态邮件配置
【发布时间】:2021-01-18 21:38:05
【问题描述】:

在我的 Laravel 应用程序中,我尝试根据登录用户的 company_id 发送邮件通知:

我有这个:

$mail=DB::table('mail_settings')->first();
$config = array(
           'driver' => $mail->driver,
           'host' => $mail->host,
           'port' => $mail->port,
           'from' => array('address' => $mail->from_address, 'name' => $mail->from_name),
           'encryption' => $mail->encryption,
           'username' => $mail->username,
           'password' => $mail->password,
           'sendmail' => '/usr/sbin/sendmail -bs',
           'pretend' => false
       );
Config::set('mail',$config);

型号

class Company extends Model
{
   protected $table = 'companies';
   protected $fillable = [
    'id',
    'organization_name'
  ];
}

class User extends Authenticatable
{
   protected $fillable = [
    'name',
    'company_id',
    'email',
 ];
}

有没有办法在创建邮件传输之前即时覆盖默认邮件配置(在 app/config/mail.php 中)(例如,配置存储在数据库中)?

谢谢

有没有办法重新创建 laravel swiftmailer 传输,以便它可以获取更新的配置值?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    Mailer 类是在Illuminate\Mail\MailManager 类的resolve() 方法中创建的。如果你想动态创建一个邮件程序,你需要在你的控制器中调整这个函数来使用你的$config数组并返回一个Mailer,你可以从中链接常用的方法。

    protected function resolve($name)
    {
        $config = $this->getConfig($name);
    
        if (is_null($config)) {
            throw new InvalidArgumentException("Mailer [{$name}] is not defined.");
        }
    
        // Once we have created the mailer instance we will set a container instance
        // on the mailer. This allows us to resolve mailer classes via containers
        // for maximum testability on said classes instead of passing Closures.
        $mailer = new Mailer(
            $name,
            $this->app['view'],
            $this->createSwiftMailer($config),
            $this->app['events']
        );
    
        if ($this->app->bound('queue')) {
            $mailer->setQueue($this->app['queue']);
        }
    
        // Next we will set all of the global addresses on this mailer, which allows
        // for easy unification of all "from" addresses as well as easy debugging
        // of sent messages since these will be sent to a single email address.
        foreach (['from', 'reply_to', 'to', 'return_path'] as $type) {
            $this->setGlobalAddress($mailer, $config, $type);
        }
    
        return $mailer;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-22
      • 1970-01-01
      • 2022-07-26
      • 2018-11-18
      • 1970-01-01
      • 2014-04-12
      • 2015-12-07
      • 1970-01-01
      • 2019-02-22
      相关资源
      最近更新 更多