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


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=[]){
        $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);
        }
        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"');
    }


    /**
     * 邮件收件人/发件人
     * @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){
            preg_match('/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/',$s,$email);
            if(empty($email[0])){
                $s = [
                    'email' =>  '',
                    'name'  =>  $s
                ];
            }else{
                $s = str_replace([$email[0],'"','<','>','&gt;','&lt;'],'',$s);
                $s = trim($s);
                $s = [
                    'email' =>  $email[0],
                    'name'  =>  $s
                ];
            }
            if(empty($s['name'])){
                $s['name'] = explode('@',$s['email'])[0]??'';
            }

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

        }

        return $strs;


    }


    /**
     * 发送邮件
     * @param string $smtp smtp服务器地址
     * @param string $username 发件人
     * @param string $password 发件人密码
     * @param string $nickname 昵称
     * @param string|array $to_email 收件人,邮件或['email'=>'','name'=>'']
     * @param string $subject 标题,主题
     * @param string $body 文本内容
     * @param array $files 文件 ['origin_name'=>'','path'=>'']
     * @param false $receipt 是否回执
     * @param int $priority 是否紧急 1紧急 3正常 5慢
     * @return array
     * @throws \PHPMailer\PHPMailer\Exception
     * @author:dc
     * @time 2023/2/18 17:45
     */
    public static function sendEmail(string $smtp,string $username,string $password,string $nickname,string|array $to_email,string $subject,string $body,$files=[],$receipt=false,$priority=3){

        // 邮件对象
        $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;                     //Set the SMTP server to send through
        $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
        $mail->Username   = $username;                     //SMTP username
        $mail->Password   = $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($username, $nickname);// 显示邮件来自谁
        // //Add a recipient,设置收件人 这里必须是一对一发送
        if(is_array($to_email)){
            $mail->addAddress($to_email['email'], $to_email['name']);
        }else{
            $mail->addAddress($to_email, '');
        }

//        //回复到那个邮件
//        $mail->addAddress($reply_to['email'], $reply_to['name']);     //Add a recipient
//        // 抄送
//        $mail->addCC($cc['email'],$cc['name']);//
//        // 密送
//        $mail->addBCC($bcc['email'],$bcc['name']);


        //Attachments 附件
        if($files){
            foreach ($files as $file){
                // 添加到邮箱中
                $mail->addAttachment($file['path'], $file['origin_name']);         //Add attachments
            }
        }

        // 回执,阅读后收回执的邮箱
        if($receipt){
            $mail->ConfirmReadingTo = $receipt;
        }
        // 是否紧急邮件
//      Options: null (default), 1 = High, 3 = Normal, 5 = low.
        $mail->Priority = $priority;

        //Content 主题,标题
        $mail->Subject = $subject;

        $mail->isHTML(true);                                  //Set email format to HTML
        $mail->Body    = $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 == base64_encode(base64_decode($str));
    }

}