v2board/app/Jobs/SendEmailJob.php

71 lines
2.3 KiB
PHP
Raw Normal View History

2019-12-26 23:46:09 +08:00
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
2020-08-22 14:28:47 +08:00
use Illuminate\Support\Facades\Config;
2019-12-26 23:46:09 +08:00
use Illuminate\Support\Facades\Mail;
2019-12-30 17:48:26 +08:00
use App\Models\MailLog;
2019-12-26 23:46:09 +08:00
2020-03-18 18:12:19 +08:00
class SendEmailJob implements ShouldQueue
2019-12-26 23:46:09 +08:00
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $params;
2020-01-11 13:36:52 +08:00
2019-12-26 23:46:09 +08:00
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($params)
{
2020-04-07 01:10:14 +08:00
$this->delay(now()->addSecond(2));
2020-03-20 13:57:09 +08:00
$this->onQueue('send_email');
2019-12-26 23:46:09 +08:00
$this->params = $params;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
2020-08-22 14:28:47 +08:00
if (config('v2board.email_host')) {
Config::set('mail.host', config('v2board.email_host', env('mail.host')));
Config::set('mail.port', config('v2board.email_port', env('mail.port')));
Config::set('mail.encryption', config('v2board.email_encryption', env('mail.encryption')));
Config::set('mail.username', config('v2board.email_username', env('mail.username')));
Config::set('mail.password', config('v2board.email_password', env('mail.password')));
Config::set('mail.from.address', config('v2board.email_from_address', env('mail.from.address')));
Config::set('mail.from.name', config('v2board.app_name', 'V2Board'));
}
2019-12-26 23:46:09 +08:00
$params = $this->params;
$email = $params['email'];
$subject = $params['subject'];
2020-03-18 18:12:19 +08:00
$params['template_name'] = 'mail.' . config('v2board.email_template', 'default') . '.' . $params['template_name'];
2019-12-30 17:48:26 +08:00
try {
Mail::send(
2020-01-11 13:36:52 +08:00
$params['template_name'],
2019-12-30 17:48:26 +08:00
$params['template_value'],
2020-01-11 13:36:52 +08:00
function ($message) use ($email, $subject) {
$message->to($email)->subject($subject);
2019-12-30 17:48:26 +08:00
}
);
} catch (\Exception $e) {
$error = $e->getMessage();
}
MailLog::create([
'email' => $params['email'],
'subject' => $params['subject'],
'template_name' => $params['template_name'],
'error' => isset($error) ? $error : NULL
]);
2019-12-26 23:46:09 +08:00
}
}