Rumah >rangka kerja php >Laravel >Laravel6 优雅的切换发件账户

Laravel6 优雅的切换发件账户

Guanhui
Guanhuike hadapan
2020-06-20 17:41:513455semak imbas

Laravel6 优雅的切换发件账户

前言

在做一个通知系统时,业务需求,根据不同场景使用不同的账户发送邮件,laravel默认只支持一个邮箱发邮件。不满实际情况,使用Config::set()方法动态设置账户后,可以成功发送邮件,再次set无法再次修改发件账户。

推荐教程:《Laravel教程

方法如下:

创建邮箱账户配置文件/config/my_emails.php


<?php
return [
 &#39;emails&#39; => [
  &#39;a&#39; => [
   &#39;email&#39; => &#39;a@188.com&#39;,
   &#39;password&#39; => &#39;专属客户端密码&#39;,
   &#39;smtp&#39; => &#39;smtp.188.com&#39;,
   &#39;port&#39; => &#39;465&#39;,
   &#39;encryption&#39; => &#39;ssl&#39;,
   &#39;name&#39; => &#39;靓仔A&#39;,
  ],
  &#39;b&#39; => [
   &#39;email&#39; => &#39;b@188.com&#39;,
   &#39;password&#39; => &#39;专属客户端密码&#39;,
   &#39;smtp&#39; => &#39;smtp.188.com&#39;,
   &#39;port&#39; => &#39;994&#39;,
   &#39;encryption&#39; => &#39;ssl&#39;,
   &#39;name&#39; => &#39;靓女b&#39;,
  ],
 ],
];

接下来创建切换助手类

<?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"));
 }
}

实际使用如下:

<?php
MailHelper::setAccount(&#39;a&#39;);
Mail::to(&#39;boy@163.com&#39;)->send(new TestMail());
MailHelper::setAccount(&#39;b&#39;);
Mail::to(&#39;girl@163.com&#39;)->send(new TestMail());

总结

到此这篇关于Laravel6.18.19如何优雅的切换发件账户的文章就介绍到这了

相关推荐:《PHP教程

Atas ialah kandungan terperinci Laravel6 优雅的切换发件账户. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Artikel ini dikembalikan pada:jb51.net. Jika ada pelanggaran, sila hubungi admin@php.cn Padam