ThinkPHP5.*使用PHPMailer發送郵件的使用及發送失敗解決辦法

1.安裝:composer require phpmailer/phpmailer

2.引入:use PHPMailer\PHPMailer\PHPMailer;(composer安裝不需要引入)

3.調用:$mail = new PHPMailer ();

寫一個方法調用發送文件接口

/**
 * 系統郵件發送函數
 * @param string $tomail 接收郵件者郵箱
 * @param string $name 接收郵件者名稱
 * @param string $subject 郵件主題
 * @param string $body 郵件內容
 * @param string $attachment 附件列表
 * @return boolean
 * @author static7 <[email protected]>
 */
function send_mail($tomail, $name, $subject = '', $body = '', $attachment = null) {
     $mail = new PHPMailer;          //實例化PHPMailer對象
    $mail->CharSet = 'UTF-8';           //設定郵件編碼,默認ISO-8859-1,如果發中文此項必須設置,否則亂碼
    $mail->IsSMTP();                    // 設定使用SMTP服務
    $mail->SMTPDebug =0;               // SMTP調試功能 0=關閉 1 = 錯誤和消息 2 = 消息
    $mail->SMTPAuth = true;             // 啓用 SMTP 驗證功能
    $mail->SMTPSecure = 'ssl';          // 使用安全協議
    $mail->Host = "smtp.163.com"; // SMTP 服務器
    $mail->Port = 465;                  // SMTP服務器的端口號
    $mail->Username = "[email protected]";    // SMTP服務器用戶名
    $mail->Password = "xxxx";     // SMTP服務器密碼 這裏是授權碼不是郵箱密碼真的很坑
    $mail->SetFrom('[email protected]', '小明');
    $replyEmail = '小明';                   //留空則爲發件人EMAIL
    $replyName = '';                    //回覆名稱(留空則爲發件人名稱)
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($tomail, $name);
    if (is_array($attachment)) { // 添加附件
        foreach ($attachment as $file) {
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
}

測試的時候可能會出現兩個問題,導致發送失敗,顯示"SMTP connect() failed",請按如下不走檢查

1.首先檢查php是否安裝openssl模塊

找到php.ini文件並打開,將extension=php_openssl.dll這個句代碼前的“;”去掉就OK了

2.就是$mail->Password = "xxxx";   這裏是授權碼不是郵箱密碼請務必注意,我就是失敗在這裏  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章