Files

64 lines
2.3 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
namespace ywxapp\library;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as PHPMailerException;
use think\facade\Log;
/**
* 基于 PHPMailer 的简单邮件发送封装。
* 未配置 SMTP 时静默返回 false(不阻断主流程)。
*/
class Mailer
{
/**
* 发送邮件
* @param string $to 收件人
* @param string $subject 主题
* @param string $body 正文(支持 HTML
* @param bool $isHtml 是否为 HTML 正文
* @return bool
*/
public static function send(string $to, string $subject, string $body, bool $isHtml = true): bool
{
$cfg = config('mail', []);
if (empty($cfg['host']) || empty($cfg['username']) || empty($cfg['password'])) {
Log::warning('[Mailer] 未配置 SMTP,跳过发送 -> ' . $to);
return false;
}
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = $cfg['host'];
$mail->SMTPAuth = true;
$mail->Username = $cfg['username'];
$mail->Password = $cfg['password'];
$mail->SMTPSecure = $cfg['secure'] ?? 'ssl';
$mail->Port = (int) ($cfg['port'] ?? 465);
$mail->CharSet = 'UTF-8';
$mail->setFrom($cfg['from'] ?: $cfg['username'], $cfg['from_name'] ?? 'YwxApp');
$mail->addAddress($to);
$mail->isHTML($isHtml);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->send();
return true;
} catch (PHPMailerException $e) {
Log::error('[Mailer] 发送失败 -> ' . $mail->ErrorInfo);
return false;
} catch (\Exception $e) {
Log::error('[Mailer] 异常 -> ' . $e->getMessage());
return false;
}
}
}