Hi everyone, this is my first post. I will try tell you about Laravel Notification Mail Sender change on runtime.
First Question, why we need change on runtime mail sender?
My company working on backup solutions and sell to another company this system, i call next time as 'tenant'
Another company using own email and sms sender services.
In laravel mail senderer information in config > mail.php.
Tenant SMTP information in DB.
First JOB;
Create a Provider.
You need a Helper php file for tenant settings and call in provider. Like This;
This provider run a started project.
Second Step:
Create a Helper
You need a helper for get tenants information from repository ( db )
Last in notification set mailer with tenant id.
First Question, why we need change on runtime mail sender?
My company working on backup solutions and sell to another company this system, i call next time as 'tenant'
Another company using own email and sms sender services.
In laravel mail senderer information in config > mail.php.
Tenant SMTP information in DB.
First JOB;
Create a Provider.
You need a Helper php file for tenant settings and call in provider. Like This;
This provider run a started project.
PHP:
public function boot(): void
{
if (Schema::hasTable('tenants')) {
$tenantSetting = app(TenantMailersHelper::class);
$tenantSetting->tenantSMTPSettings();
}
}
Second Step:
Create a Helper
You need a helper for get tenants information from repository ( db )
PHP:
public function tenantSMTPSettings()
{
$tenants = $this->tenantRepository->all();
$defaultMailersConfig = config('mail.mailers');
$addedMailerConfigs = [];
foreach ($tenants as $tenant) {
if ($tenant->setting) {
if (!isset($defaultMailersConfig['t' . $tenant->id]) && !isset($addedMailerConfigs['t' . $tenant->id])) {
$newMailer = $this->addNewMailer($tenant);
$addedMailerConfigs = array_merge($addedMailerConfigs, $newMailer);
}
continue;
}
}
$defaultMailersConfig = array_merge($defaultMailersConfig, $addedMailerConfigs);
Config::set('mail.mailers', $defaultMailersConfig);
}
PHP:
private function addNewMailer($tenant)
{
$newMailer = [
't' . $tenant->id => [
'transport' => 'smtp',
'host' => $tenant->setting->smtp_host,
'port' => strval($tenant->setting->smtp_port),
'encryption' => $tenant->setting->smtp_encryption,
'username' => $tenant->setting->smtp_username,
'password' => $tenant->setting->smtp_password,
'timeout' => null,
'auth_mode' => null,
'stream' => [
'ssl' => [
'allow_self_signed' => true,
'verify_peer' => false,
'verify_peer_name' => false,
],
],
]
];
return $newMailer;
}
Last in notification set mailer with tenant id.
PHP:
$this->mailer('t' . $tenant->id);