laravel10中使用队列发送邮件,每一封邮件都需要从数据库读取单独的邮件服务配置,目前只能通过发送前设置config解决,寻求更优的解决方案
1. 运行环境
1). 当前使用的 Laravel 版本?
laravel 10
2). 当前使用的 php/php-fpm 版本?
php8.1
3). 当前系统
debian12
4). 业务环境
开发环境
5). 相关软件版本
nginx redis mysql docker
2. 问题描述?
laravel10中使用队列发送邮件,每一封邮件都需要从数据库读取单独的邮件服务配置,目前只能通过发送前设置config解决,寻求更优的解决方案。在laravel6版本解决过相同问题,重写了Illuminate\Mail\Mailable类解决了此问题。laravel10中同样的思路无法实现,寻求指点
<?php
namespace App\Mail;
use Illuminate\Container\Container;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Mail\Mailable;
use Swift_Mailer;
use Swift_SmtpTransport;
use Exception;
class ConfigurableMailable extends Mailable
{
public function send(Mailer $mailer)
{
try {
// 配置邮件服务器
$smtp_tls = $this->config['smtp_tls'] == 'none' ? null : $this->config['smtp_tls'];
$transport = new Swift_SmtpTransport($this->config['smtp_server'], $this->config['smtp_port'], $smtp_tls);
//设置认证方式
$transport->setAuthMode($this->config['authentication']);
if ($this->config['authentication'] == 'login') {
if ($this->config['smtp_username']) {
$transport->setUsername($this->config['smtp_username']);
$transport->setPassword($this->config['smtp_password']);
}
}
// 注意看,这里是修改为用户邮箱的配置,$this->config是用户传的数据。
if ($this->config['smtp_tls'] == "tls") {
$https['ssl']['verify_peer'] = FALSE;
$https['ssl']['verify_peer_name'] = FALSE;
$transport->setStreamOptions($https);
}
$mailer->setSwiftMailer(new Swift_Mailer($transport));
// 重启Swift_SmtpTransport中ssl的连接要不然会报错
$mailer->getSwiftMailer()->getTransport()->stop();
Container::getInstance()->call([$this, 'build']);
$mailer->send($this->buildView(), $this->buildViewData(), function ($message) {
$this->buildFrom($message)
->buildRecipients($message)
->buildSubject($message)
->buildAttachments($message)
->runCallbacks($message);
});
} catch (\Swift_TransportException $swift_TransportException) {
// $content = mb_convert_encoding( $swift_TransportException->getMessage(), 'UTF-8', 'UTF-8,GBK,GB2312,BIG5' );
$content = iconv("gb2312", "utf-8//IGNORE", $swift_TransportException->getMessage());
throw new Exception($content);
}
}
}
问题已解决,重写mailable类并重写send方法,具体代码如下: