ThinkPHP6結合PHPMailer傳送郵件

TechKoga發表於2020-08-18
composer require phpmailer/phpmailer
<?php
namespace app\admin\service;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class MailService
{
    /**
     * @param $to
     * @param string $subject
     * @param string $content
     * @param string $addAttachment
     * @return array
     * @throws Exception
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @describe:傳送郵件
     */
    public static function sendEmail($to,$subject='',$content='',$addAttachment=''){
        //判斷openssl是否開啟
        $openssl_funcs = get_extension_funcs('openssl');
        if(!$openssl_funcs){
            return ['code'=>0 , 'msg'=>'請先開啟openssl擴充套件'];
        }
        $config=sysconfig("mail");
        $mail = new PHPMailer;
        $mail->CharSet  = 'UTF-8'; //設定郵件編碼,預設ISO-8859-1,如果發中文此項必須設定,否則亂碼
        $mail->isSMTP();
        $mail->SMTPDebug = 0;
        //Whether to use SMTP authentication
        $mail->SMTPAuth = true;
        //除錯輸出格式
        $mail->Debugoutput = 'html';
        //smtp伺服器
        $mail->Host = $config['mail_smtp_host'];
        //埠 - likely to be 25, 465 or 587
        $mail->Port = $config['mail_smtp_port'];
        $mail->SMTPSecure =$config['mail_secure'];// 使用安全協議 tls,ssl
        //使用者名稱
        $mail->Username = $config['mail_smtp_user'];
        //密碼
        $mail->Password = $config['mail_smtp_pass'];
        //Set who the message is to be sent from
        $mail->setFrom($config['mail_smtp_user'],$config['mail_smtp_name']);
        //回覆地址
        //$mail->addReplyTo('replyto@example.com', 'First Last');
        //接收郵件方
        if(is_array($to)){
            foreach ($to as $v){
                $mail->addAddress($v);
            }
        }else{
            $mail->addAddress($to);
        }
        $mail->isHTML(true);// send as HTML
        //標題
        $mail->Subject = $subject;
        //郵箱正文
        $mail->Body = $content;
        //新增附件
        if (!empty($addAttachment)){
            $mail->addAttachment($addAttachment);
        }
        try {
            $mail->send();
            return ['code'=>1 , 'msg'=>'傳送成功'];
        }catch (Exception $e){
            return ['code'=>0 , 'msg'=>$e->getMessage()];
        }
    }

}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
愛程式碼,不愛程式設計的小夥子 ^v^

相關文章