首页 > 解决方案 > Laravel:是否可以延迟发送通知,但动态更改 smtp 设置?

问题描述

我正在使用 Laravel v5.7 开发多租户(多数据库),并且成功发送队列电子邮件。

在某些特定情况下,我想发送带有“延迟”的按需通知,类似于指南On-Demand Notifications,但会在发送前告知应使用的 SMTP 设置。

我开发了一个更改 config() 值的类。

应用程序/租户/SmtpConfig.php

class SmtpConfig
{
    public static function setConnection(SmtpConta $conta = null)
    {
        // get connection default settings
        $config = config()->get("mail");

        // populate connection default settings
        foreach ($config as $key => $value) {
            if ( $key == 'host' )      { $config[$key] = $conta->mail_host ?? $config[$key]; }
            if ( $key == 'from' )      { $config[$key] = [
                'address' => ( $conta->mail_host === 'smtp.mailtrap.io' ) ? $config[$key]['address'] : $conta->mail_username,
                'name' => $conta->conta ?? $config[$key]['name']
            ]; }
            if ( $key == 'username' )  { $config[$key] = $conta->mail_username ?? $config[$key]; }
            if ( $key == 'password' )  { $config[$key] = !empty($conta->mail_password) ? $conta->mail_password : $config[$key]; }
        }

        $config['encryption'] = ( $conta->mail_host === 'smtp.mailtrap.io' ) ? null : 'ssl';

        // set connection default settings
        config()->set("mail", $config);
    }

}

...我在通知中调用这个 SmtpConfig 类:

/**
  * Create a new notification instance.
  *
  * @param $conta
  * @param $subject
  * @return void
  */
  public function __construct(SmtpConta $conta = null, $subject = null)
  {
        $this->conta = $conta;
        $this->subject = $subject;

        $when = \Carbon\Carbon::now()->addSecond(100);

        $this->delay($when);

        app(\App\Tenant\SmtpConfig::class)::setConnection($this->conta);
  }

我可以成功发送“延迟”通知,但显然它总是使用.env文件的默认值。

现在我不确定我在哪里调用这个类是否有意义,甚至我如何告诉通知它应该使用什么 SMTP 配置。

标签: laravellaravel-maillaravel-notification

解决方案


我目前在使用 Notification backport library 的 Laravel 5.2 代码库上面临着类似的挑战。

这是我的解决方案的一个示例,类似于 Kit Loong 的建议。我们只是扩展Illuminate\Notifications\Channels\MailChannel类并覆盖send()方法。

您需要能够从收件人或通知对象中确定 SMTP 配置,因此您需要根据需要编辑我的示例。

这也假设您的应用程序使用默认值Swift_Mailer,因此 YMMV ...

<?php

declare (strict_types = 1);

namespace App\Notifications\Channels;

use Illuminate\Notifications\Channels\MailChannel;
use Illuminate\Notifications\Notification;

class DynamicSmtpMailChannel extends MailChannel
{
    /**
     * Send the given notification.
     *
     * @param  mixed  $notifiable
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return void
     */
    public function send($notifiable, Notification $notification)
    {
        //define this method on your model (note $notifiable could be an array or collection of notifiables!)
        $customSmtp = $notifiable->getSmtpConfig(); 

        if ($customSmtp) {
            $previousSwiftMailer = $this->mailer->getSwiftMailer();

            $swiftTransport = new \Swift_SmtpTransport(
                $customSmtp->smtp_server, 
                $customSmtp->smtp_port,
                $customSmtp->smtp_encryption
            );
            $swiftTransport->setUsername($customSmtp->smtp_user);
            $swiftTransport->setPassword($customSmtp->smtp_password);

            $this->mailer->setSwiftMailer(new \Swift_Mailer($swiftTransport));
        }

        $result = parent::send($notifiable, $notification);

        if (isset($previousSwiftMailer)) {
            //restore the previous mailer
            $this->mailer->setSwiftMailer($previousSwiftMailer);
        }

        return $result;
    }
}

保留自定义快速邮件程序的临时存储也可能是有益的,这样您就可以在相同的调用/请求中重新使用它们(考虑长期运行的工作人员) - 就像一个集合类,其中使用 smtp 配置的哈希作为项目键。

祝你好运。

编辑:我可能应该提到你可能需要在服务容器中绑定它。像这样的东西就足够了:

// in a service provider
public function register()
{
    $this->app->bind(
        \Illuminate\Notifications\Channels\MailChannel::class
        \App\Notifications\Channels\DynamicSmtpMailChannel::class
    );
}

或者,将其注册为单独的通知渠道。


推荐阅读