【发布时间】:2022-01-26 01:51:08
【问题描述】:
我在电子邮件配置 SMTP 设置中从数据库动态应用了一个 foreach 循环。SMTP 服务器表中有多个 SMTP 服务器。我正在根据处理表中的smtp_server_id 从表中动态选择 SMTP 信息,并将其存储在电子邮件配置中,然后再发送电子邮件。但是在第一次迭代中,来自 dB 的 SMTP 服务器存储在电子邮件配置中,例如 config('mail.smtp.host'),但在第二次迭代中,直到循环结束,SMTP 信息不会改变。 SMTP 信息保持不变,邮件配置变量在第一次迭代时保持不变。根据foreach循环中的smtp_id一一动态更改SMTP配置应该怎么做。
我的 cron 任务是发送电子邮件。
namespace App\Console\Commands;
use App\Mail\SendEmail;
use App\Models\CronjobSetting;
use App\Models\ProcessingEmail;
use App\Models\SmtpServer;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Mail;
class SendEmailsBasedonDate extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'sendemailviadate:cron';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$cronJob = CronjobSetting::whereDate('created_at', Carbon::today())->first();
if ($cronJob->email_group_type == 1) {
$processingEmails = ProcessingEmail::all();
foreach ($processingEmails as $processingEmail) {
$smtpServer = SmtpServer::where('id', $processingEmail->smtp_id)->first();
Config::set('mail.mailers.smtp.host', $smtpServer->hostname);
Config::set('mail.mailers.smtp.port', $smtpServer->port);
Config::set('mail.mailers.smtp.username', $smtpServer->username);
Config::set('mail.mailers.smtp.password', $smtpServer->password);
$email = new SendEmail($processingEmail);
Mail::to($processingEmail->recipient_email)->send($email);
if (Mail::failures()) {
ProcessingEmail::where('id', $processingEmail->id)->update(
['status' => 3]
);
} else {
ProcessingEmail::destroy($processingEmail->id);
}
}
} else {
$processingEmails = ProcessingEmail::where('email_group_id', $cronJob->email_group_id)->get();
foreach ($processingEmails as $processingEmail) {
$smtpServer = SmtpServer::where('id', $processingEmail->smtp_id)->first();
Config::set('mail.mailers.smtp.host', $smtpServer->hostname);
Config::set('mail.mailers.smtp.port', $smtpServer->port);
Config::set('mail.mailers.smtp.username', $smtpServer->username);
Config::set('mail.mailers.smtp.password', $smtpServer->password);
$email = new SendEmail($processingEmail);
Mail::to($processingEmail->recipient_email)->send($email);
if (Mail::failures()) {
ProcessingEmail::where('email_leads_id', $processingEmail->email_lead_id)->update(
['status' => 3]
);
} else {
ProcessingEmail::where('email_leads_id', $processingEmail->email_lead_id)->delete();
}
}
return Command::SUCCESS;
}
}
}
【问题讨论】:
-
Welcome to SO ...管理器可能正在缓存邮件驱动程序,因此它会继续使用它已经创建的相同驱动程序...在设置配置值后尝试
Mail::purge(),以便新实例将创建邮件驱动程序(使用新的配置值) -
另外请检查编译器在发送邮件后没有进入of条件。电子邮件失败时,它不会删除或更新状态。请看代码。我应该为此做些什么。发送邮件后,如果 mai 失败意味着 Mail::fails 函数不会跳过该部分。
标签: php laravel email smtp laravel-8