首頁  >  文章  >  php框架  >  Laravel6 優雅的切換寄件帳戶

Laravel6 優雅的切換寄件帳戶

Guanhui
Guanhui轉載
2020-06-20 17:41:513411瀏覽

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教學

#

以上是Laravel6 優雅的切換寄件帳戶的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:jb51.net。如有侵權,請聯絡admin@php.cn刪除