Home > Article > PHP Framework > Laravel6 elegantly switches sending accounts
##Preface
When making a notification system, According to business needs, use different accounts to send emails according to different scenarios. Laravel only supports sending emails from one email address by default. Unsatisfied with the actual situation, after using the Config::set() method to dynamically set the account, the email can be successfully sent, but the sending account cannot be modified again by setting again.Recommended tutorial: "Laravel Tutorial"
##The method is as follows: Create email account configuration file/config/my_emails.php
<?php return [ 'emails' => [ 'a' => [ 'email' => 'a@188.com', 'password' => '专属客户端密码', 'smtp' => 'smtp.188.com', 'port' => '465', 'encryption' => 'ssl', 'name' => '靓仔A', ], 'b' => [ 'email' => 'b@188.com', 'password' => '专属客户端密码', 'smtp' => 'smtp.188.com', 'port' => '994', 'encryption' => 'ssl', 'name' => '靓女b', ], ], ];
<?php namespace App\Mail; use Illuminate\Support\Facades\Mail; class MailHelper { public static function setAccount($accountName) { $transport = new \Swift_SmtpTransport( config("my_emails.emails.{$accountName}.smtp"), config("my_emails.emails.{$accountName}.port"), config("my_emails.emails.{$accountName}.encryption") ); $transport->setUsername(config("my_emails.emails.{$accountName}.email")); $transport->setPassword(config("my_emails.emails.{$accountName}.password")); $mailer = new \Swift_Mailer($transport); Mail::setSwiftMailer($mailer); Mail::alwaysFrom(config("my_emails.emails.{$accountName}.email"), config("my_emails.emails.{$accountName}.name")); } }
The actual usage is as follows:
<?php MailHelper::setAccount('a'); Mail::to('boy@163.com')->send(new TestMail()); MailHelper::setAccount('b'); Mail::to('girl@163.com')->send(new TestMail());
SummaryThis concludes this article on how to elegantly switch sending accounts in Laravel 6.18.19
Related recommendations: "
PHP Tutorial
The above is the detailed content of Laravel6 elegantly switches sending accounts. For more information, please follow other related articles on the PHP Chinese website!