MailFun.php 8.9 KB
<?php
namespace Lib\Mail;


use Lib\UploadFile;
use Model\bodySql;
use Model\folderSql;
use Model\listsSql;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;

/**
 * 函数
 * @time 2022/8/1 16:02
 * Class MailFun
 * @package App\Mail\lib
 */
class MailFun {


    /**
     * json encode
     * @param $data
     * @param int $option
     * @return false|string
     * @time 2022/8/2 15:57
     */
    public static function json_en($data,$option=\JSON_UNESCAPED_UNICODE){
        return \json_encode($data,$option);
    }

    /**
     * @param $str
     * @param string $encode
     * @return string
     * @author:dc
     * @time 2023/3/27 13:55
     */
    public static function mb_coding(string $str,array $appcode=[]){
        try {
            $encode = @mb_detect_encoding($str, array_merge(array("ASCII",'UTF-8',"GB2312","GBK",'BIG5'),$appcode));
            if($encode){
                return @mb_convert_encoding($str, 'UTF-8', $encode);
            }
        }catch (\Throwable $e){

        }

        return $str;
    }


    /**
     * 验证是否有附件 BODYSTRUCTURE值
     * @param $BODYSTRUCTURE
     * @return int
     * @author:dc
     * @time 2022/11/1 10:57
     */
    public static function isFile($BODYSTRUCTURE):int {
//        foreach ($BODYSTRUCTURE as $item){
//            if($item[0] === 'APPLICATION'){
//                return 1;
//            }
//        }
//        return 0;
        $json = is_array($BODYSTRUCTURE) ? implode(' ',$BODYSTRUCTURE) : $BODYSTRUCTURE;
        return str_contains(mb_strtolower($json), '"attachment"');
    }

    /**
     * 验证body里面是否有附件
     * @param array $body
     * @return bool
     * @author:dc
     * @time 2023/6/25 15:03
     */
    public static function isBodyFile(array $body){
        foreach ($body as $item){
//            if(v.name && v.filename && v.signName && !v['content-id']){
            if(!empty($item['name']) && !empty($item['filename']) && !empty($item['signName']) && empty($item['content-id'])){
                return 1;
            }
        }
        return 0;
    }

    /**
     * 匹配邮箱
     * @param $str
     * @return mixed|string
     * @author:dc
     * @time 2023/11/24 10:04
     */
    public static function pregEmail($str){
        preg_match('/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/',$str,$email);
        if(empty($email[0])){
            // 邮箱2
            preg_match('/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/',$str,$email);
        }
        return $email[0]??'';
    }


    /**
     * 邮件收件人/发件人
     * @param $str
     * @return array
     * @author:dc
     * @time 2022/11/8 9:36
     */
    public static function toOrFrom($str){

        $strs = explode(',',$str);
        foreach ($strs as $k=>$s){
            $email = self::pregEmail($s);

            if(empty($email)){
                $s = [
                    'email' =>  '',
                    'name'  =>  $s
                ];
            }else{
                $s = str_replace([$email,'"','<','>','&gt;','&lt;'],'',$s);
                $s = trim($s);
                $s = [
                    'email' =>  $email,
                    'name'  =>  $s
                ];
            }
            if(empty($s['name'])){
                $s['name'] = explode('@',$s['email'])[0]??'';
            }

            if(!empty($s['email'])){
                $strs[$k] = $s;
            }else{
                unset($strs[$k]);
            }

        }

        return array_values($strs);


    }


    /**
     * 发送邮件
     * @param array $data 数据
     * @param array $email 邮箱信息
     * @return array
     * @throws \Lib\Err
     * @throws \PHPMailer\PHPMailer\Exception
     * @author:dc
     * @time 2023/4/11 9:12
     */
    public static function sendEmail(array $data, array $email){

        // 邮件对象
        $mail = new PHPMailer();
        //Server settings
        $mail->SMTPDebug = SMTP::DEBUG_OFF;//调试输出  SMTP::DEBUG_SERVER;                    //Enable verbose debug output
        $mail->isSMTP();                                            //Send using SMTP
        $mail->Host       = $email['smtp'];                     //Set the SMTP server to send through
        $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
        $mail->Username   = $email['email'];                     //SMTP username
        $mail->Password   = base64_decode($email['password']);                               //SMTP password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
        $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
        $mail->CharSet = 'utf-8';
        $mail->Encoding = PHPMailer::ENCODING_QUOTED_PRINTABLE;

        //Recipients,设置发件人
        $mail->setFrom($email['email'], $data['nickname']??'');// 显示邮件来自谁
        // //设置收件人
        foreach ($data['tos'] as $to){
            $mail->addAddress($to['email'], $to['name']??'');
        }

        //回复到那个邮件
        if(!empty($data['reply_to'])){
            if(is_string($data['reply_to'])){
                $mail->addReplyTo($data['reply_to']);
            }else{
                $mail->addReplyTo($data['reply_to']['email'], $data['reply_to']['name']);     //Add a recipient
            }
        }

        // 抄送
        if(!empty($data['cc'])){
            foreach ($data['cc'] as $to){
                $mail->addCC($to['email'], $to['name']??'');
            }
        }
        // 密送
        if(!empty($data['bcc'])){
            foreach ($data['bcc'] as $to){
                $mail->addBCC($to['email'], $to['name']??'');
            }
        }

        //Attachments 附件
        if(!empty($data['attachment'])){
            foreach ($data['attachment'] as $file){
                $mail->addAttachment($file['path'], $file['filename']);
            }
        }

        // 回执,阅读后收回执的邮箱
        if(!empty($data['receipt'])){
            $mail->ConfirmReadingTo = $email['email'];
        }

        // 是否紧急邮件
//      Options: null (default), 1 = High, 3 = Normal, 5 = low.
        $mail->Priority = $data['priority']??3;

        //Content 主题,标题
        $mail->Subject = $data['subject'];

        $mail->isHTML(true);                                  //Set email format to HTML
        $mail->Body    = $data['body'];// html格式的内容

        // 发送
        if($mail->send()){
            return [true,$mail->getLastMessageID()];
        }

        return [false,$mail->ErrorInfo];

    }

    /**
     * 文件夹名 编译
     * @param $folder
     * @return string
     * @author:dc
     * @time 2023/3/14 9:37
     */
    public static function folderEncoding($folder):string {
        return mb_convert_encoding($folder,'UTF7-IMAP','UTF-8');
    }

    /**
     * 是否是base64
     * @param $str
     * @return bool
     * @author:dc
     * @time 2023/4/3 10:24
     */
    public static function isBase64($str){
        $oldStr = str_replace(["\n","\r"],'',rtrim($str,'='));
        return $oldStr == rtrim(base64_encode(base64_decode($str)),'=');
    }


    /**
     * 测试登录
     * @param $smtp
     * @param $email
     * @param $password
     * @return bool
     * @author:dc
     * @time 2023/11/7 10:47
     */
    public static function smtpLoginTest($smtp,$email,$password){
        $smtp = self::getHostPort($smtp,465);
        // 邮件对象
        $mail = new PHPMailer();
        //Server settings
        $mail->SMTPDebug = SMTP::DEBUG_OFF;//调试输出  SMTP::DEBUG_SERVER;                    //Enable verbose debug output
        $mail->isSMTP();                                            //Send using SMTP
        $mail->Host       = $smtp['host'];                     //Set the SMTP server to send through
        $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
        $mail->Username   = $email;                     //SMTP username
        $mail->Password   = $password;                               //SMTP password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
        $mail->Port       = $smtp['port'];                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
        $mail->CharSet = 'utf-8';
        $mail->Encoding = PHPMailer::ENCODING_QUOTED_PRINTABLE;

        try {
            return $mail->smtpConnect();
        }catch (\Throwable $e){}

        return false;

    }


    /**
     * @param $host
     * @param int $port
     * @return array
     * @author:dc
     * @time 2024/3/6 9:21
     */
    public static function getHostPort($host,$port = 465){
        list($h,$p) = explode(":",$host.':'.$port);
        return [
            'host'  =>  $h,
            'port'  =>  $p,
        ];
    }


}