一、首先需要你開啟smtp 服務,登錄qq郵箱,進入設置 -》 賬戶
注意: 開啟后會生成授權碼,一定要記下,兩個都記下,登錄郵件客戶端需要。這里配置郵件發送也需要這個授權碼
二、 下載phpmailer, 然后在thinkphp5 目錄下的 擴展類庫 extend目錄下 新建phpmailer目錄。。
把你下載的phpmailer里的class.phpmailer.PHP和class.smtp.php文件復制到phpmailer目錄下。
注意:thinkphp5的擴展類的定義是,類文件命名為:phpmailer.php而不是class.phpmailer.php。所以要把class.phpmailer.php重命名為phpmailer.php。 另一個不用改。
三、代碼實現:
1。 開啟openssl擴展
2 。extend下的擴展類庫使用的是命名空間必須在phpmailer.php和class.smtp.php最開頭加上
namespace phpmailer;
3。在phpmailer.php中的2315行使用到了php的Exception異常類,在thinkphp框架中直接繼承,thinkphp找不到Exception所以要修改如下;
4。 在使用phpmailer時,實例化PHPMailer(),需要使用命名空間
use phpmailer\phpmailer;
5。 然后在index模塊下新建Mail.php控制器,代碼如下
<?php namespace app\index\controller; use think\Controller; use phpmailer\phpmailer; class Mail extends Base { function __construct(){ parent::__construct(); } //qq public function index(){ $sendmail = ''; //發件人郵箱 $sendmailpswd = ""; //客戶端授權密碼,而不是郵箱的登錄密碼! $send_name = '';// 設置發件人信息,如郵件格式說明中的發件人, $toemail = '';//定義收件人的郵箱 $to_name = '';//設置收件人信息,如郵件格式說明中的收件人 $mail = new PHPMailer(); $mail->isSMTP();// 使用SMTP服務 $mail->CharSet = "utf8";// 編碼格式為utf8,不設置編碼的話,中文會出現亂碼 $mail->Host = "smtp.qq.com";// 發送方的SMTP服務器地址 $mail->SMTPAuth = true;// 是否使用身份驗證 $mail->Username = $sendmail;//// 發送方的 $mail->Password = $sendmailpswd;//客戶端授權密碼,而不是郵箱的登錄密碼! $mail->SMTPSecure = "ssl";// 使用ssl協議方式 $mail->Port = 465;// qq端口465或587) $mail->setFrom($sendmail,$send_name);// 設置發件人信息,如郵件格式說明中的發件人, $mail->addAddress($toemail,$to_name);// 設置收件人信息,如郵件格式說明中的收件人, $mail->addReplyTo($sendmail,$send_name);// 設置回復人信息,指的是收件人收到郵件后,如果要回復,回復郵件將發送到的郵箱地址 //$mail->addCC("xxx@qq.com");// 設置郵件抄送人,可以只寫地址,上述的設置也可以只寫地址(這個人也能收到郵件) //$mail->addBCC("xxx@qq.com");// 設置秘密抄送人(這個人也能收到郵件) //$mail->addAttachment("bug0.jpg");// 添加附件 $mail->Subject = "這是一個測試郵件";// 郵件標題 $mail->Body = "郵件內容是 <b>您的驗證碼是:123456</b>,哈哈哈!";// 郵件正文 //$mail->AltBody = "This is the plain text純文本";// 這個是設置純文本方式顯示的正文內容,如果不支持Html方式,就會用到這個,基本無用 if(!$mail->send()){// 發送郵件 echo "Message could not be sent."; echo "Mailer Error: ".$mail->ErrorInfo;// 輸出錯誤信息 }else{ echo '發送成功'; } } }