<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\service;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use app\service\ConfigService;


/**
 * 邮件服务
 * @package app\service
 */
class EmailService
{
     /**
     * 获取邮箱配置
     * @return array
     */
    private static function getConfig()
    {
        return [
            'email_smtp_host' => ConfigService::getString('email_smtp_host', ''),
            'email_smtp_port' => ConfigService::getString('email_smtp_port', '465'),
            'email_smtp_user' => ConfigService::getString('email_smtp_user', ''),
            'email_smtp_pass' => ConfigService::getString('email_smtp_pass', ''),
            'email_sender_name' => ConfigService::getString('email_sender_name', ''),
        ];
    }

     /**
     * 发送邮件
     * @param string $to
     * @param string $subject
     * @param string $body
     * @return bool
     * @return \Exception
     */
    public static function send($to, $subject, $body)
    {
        $config = self::getConfig();
        $host = $config['email_smtp_host'] ?? '';
        $port = $config['email_smtp_port'] ?? '465';
        $user = $config['email_smtp_user'] ?? '';
        $pass = $config['email_smtp_pass'] ?? '';
        $senderName = $config['email_sender_name'] ?? '';

        if (!$host || !$user || !$pass) {
            throw new \Exception('');
        }

        $mail = new PHPMailer(true);

        try {
            $mail->isSMTP();
            $mail->Host       = $host;
            $mail->SMTPAuth   = true;
            $mail->Username   = $user;
            $mail->Password   = $pass;
            $mail->SMTPSecure = ($port == 465) ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port       = $port;
            $mail->CharSet    = 'UTF-8';

            $mail->setFrom($user, $senderName);
            $mail->addAddress($to);

            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = $body;

            $mail->send();
            return true;
        } catch (Exception $e) {
            throw new \Exception("{$mail->ErrorInfo}");
        }
    }
}
