1、首先須要你開啓smtp 服務,登陸qq郵箱,進入設置 -》 帳戶 php
注意: 開啓後會生成受權碼,必定要記下,兩個都記下,登陸郵件客戶端須要。這裏配置郵件發送也須要這個受權碼thinkphp
2、 下載phpmailer, 而後在thinkphp5 目錄下的 擴展類庫 extend目錄下 新建phpmailer目錄。。php框架
把你下載的phpmailer裏的class.phpmailer.PHP和class.smtp.php文件複製到phpmailer目錄下。服務器
注意:thinkphp5的擴展類的定義是,類文件命名爲:phpmailer.php而不是class.phpmailer.php。因此要把class.phpmailer.php重命名爲phpmailer.php。 另外一個不用改。app
3、代碼實現:框架
1。 開啓openssl擴展thinkphp5
2 。extend下的擴展類庫使用的是命名空間必須在phpmailer.php和class.smtp.php最開頭加上測試
namespace phpmailer;
3。在phpmailer.php中的2315行使用到了php的Exception異常類,在thinkphp框架中直接繼承,thinkphp找不到Exception因此要修改以下;編碼
4。 在使用phpmailer時,實例化PHPMailer(),須要使用命名空間spa
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 '發送成功'; } } }