Files
fdesk/app/common/utils/email/MailSend.php
T
2025-08-04 14:03:57 +08:00

69 lines
2.3 KiB
PHP
Raw 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
namespace app\common\utils\email;
use app\common\model\InquiryLog;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use support\Db;
use support\Log;
class MailSend
{
/**
* 发送邮件
*
* @param string|array $to 收件人邮箱(单个字符串或多个数组)
* @param string $subject 邮件主题
* @param string $body 邮件内容(HTML)
* @param array $attachments 附件路径数组 [['path' => '/path/file', 'name' => '文件名']]
* @return bool
*/
public static function send($to, $subject, $body, $attachments = [])
{
$mail = new PHPMailer(true);
try {
// 服务器配置
$mail->isSMTP();
$mail->Host = config('imap.smtp_xyh.host'); // SMTP服务器
$mail->SMTPAuth = true;
$mail->Username = config('imap.smtp_xyh.username'); // 邮箱账号
$mail->Password = config('imap.smtp_xyh.password'); // 邮箱密码/授权码
$mail->SMTPSecure = config('imap.smtp_xyh.encryption'); // 加密方式 tls/ssl
$mail->Port = config('imap.smtp_xyh.port'); // 端口
// 发件人
$mail->setFrom(config('imap.smtp_xyh.from_address'), config('imap.smtp_xyh.from_name'));
// 收件人(支持单个或多个)
if (is_string($to)) {
$mail->addAddress($to);
} elseif (is_array($to)) {
foreach ($to as $email) {
$mail->addAddress($email);
}
}
// 附件
foreach ($attachments as $file) {
$mail->addAttachment($file['path'], $file['name'] ?? '');
}
// 内容
$mail->isHTML(true);
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
$mail->Subject = mb_encode_mimeheader($subject, 'UTF-8', 'B', "\r\n");
$mail->Body = $body;
// $mail->AltBody = strip_tags($body); // 纯文本备用
// $mail->AltBody = $altbody;
$mail->send();
return true;
} catch (Exception $e) {
Log::error("邮件发送失败: " . $e->getMessage());
return false;
}
}
}