fuc-new/src/Services/Mail/Smtp.php
2025-12-30 19:11:03 +08:00

77 lines
2.2 KiB
PHP
Executable File

<?php
declare(strict_types=1);
namespace App\Services\Mail;
use App\Models\Config;
use Exception;
use PHPMailer\PHPMailer\PHPMailer;
final class Smtp extends Base
{
private PHPMailer $mail;
/**
* @throws Exception
*/
public function __construct()
{
$configs = Config::getClass('email');
// $configs['smtp_username'] = "gemcode.jp@gmail.com";
// $configs['smtp_password'] = "nzgardpoxxuzexfg";
// $configs['smtp_sender'] = "gemcode.jp@gmail.com";
$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = $configs['smtp_host'];
$mail->Port = $configs['smtp_port'];
$mail->SMTPAuth = ! ($configs['smtp_username'] === '' && $configs['smtp_password'] === '');
$mail->CharSet = 'UTF-8';
$mail->Username = $configs['smtp_username'];
$mail->Password = $configs['smtp_password'];
$mail->setFrom($configs['smtp_sender'], $configs['smtp_name']);
if ($configs['smtp_ssl']) {
$mail->SMTPSecure = ($configs['smtp_port'] === '587' ? 'tls' : 'ssl');
}
if ($configs['smtp_bbc'] !== '') {
$mail->addBCC($configs['smtp_bbc']);
}
$this->mail = $mail;
}
/**
* @throws Exception
*/
public function send($to, $subject, $body): void
{
$mail = $this->mail;
$mail->addAddress($to); // Add a recipient
$mail->isHTML();
$mail->Subject = $subject;
$mail->Body = $body;
$mail->send();
$sMsg = "";
if (!$mail->send()) {
$sMsg = '发送失败: ' . $mail->ErrorInfo;
// file_put_contents('mail_log.txt', date('Y-m-d H:i:s') . " - $sMsg" . $to . PHP_EOL, FILE_APPEND);
// echo '发送失败: ' . $mail->ErrorInfo;
} else {
// 每次成功后,将记录写入 log.txt
$sMsg = date('Y-m-d H:i:s') . " - Sent to: " . $to . PHP_EOL;
// file_put_contents('mail_log.txt', , FILE_APPEND);
// echo '发送成功';
}
echo $sMsg;
file_put_contents('mail_log.txt', date('Y-m-d H:i:s') . " - $sMsg" . $to . PHP_EOL, FILE_APPEND);
}
}