TP5實現郵件發送
發布時間:2020-07-31
在項目的開發中 用戶修改密碼,需要發送驗證碼到用戶郵箱,
common.php
/**
* 系統郵件發送函數
* @param string $tomail 接收郵件者郵箱
* @param string $name 接收郵件者名稱
* @param string $subject 郵件主題
* @param string $body 郵件內容
* @param string $attachment 附件列表
* @return boolean
*/function send_mail($tomail, $name, $subject = '', $body = '', $attachment = null) {
$mail = new PHPMailer\PHPMailer\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.qq.com"; // SMTP 服務器
$mail->Port = 465; // SMTP服務器的端口號
$mail->Username = "xxxxxx@qq.com"; // SMTP服務器用戶名
$mail->Password = "xxxxxx"; // SMTP服務器密碼
$mail->SetFrom('xxxx@qq.com', '發送人的名稱');
$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();}
控制器
public function email(){
//收件人的郵箱
$toemail='xxxxx@qq.com';
//收件人的名稱
$name='xxxxxxx';
$subject='QQ郵件發送測試';
$code = mt_rand(10000, 99999);
session("code",$code);
$content='你得驗證碼為'.$code;
dump(send_mail($toemail,$name,$subject,$content));
}
最后驗證是否正確 根據輸入驗證碼的去判斷取出session的 code的進行比較
TP5實現郵件發送(二)
使用 composer 命令進行安裝或下載源代碼使用。
composer require houdunwang/mail
郵件配置,以下是126郵箱配置的示例:
return [
'ssl' => false,//服務器使用ssl
'username' => 'houdunwang@126.com',//郵箱帳號
'password' => '',//登錄密碼
'host' => 'smtp.126.com',//服務器主機
'port' => '25',//服務器端口號
'fromname' => '后盾網',//發件人(會員收到郵件時顯示)
'frommail' => 'houdunwang@126.com',//發件人郵箱(會員收到郵件時顯示)];
發送郵件
函數語法
Mail::send(收件人郵箱,收件人名稱,郵件標題,郵件內容);
發送郵件
Mail::send(
'xxx@qq.com',
'xxx@qq.com',
"這是郵件標題",
"這是郵件正文");
使用閉包設置內容
Mail::send('test@xx.com', 'test@xx.com', "這是郵件標題", function () {
return View::instance()->with(['title' => '測試郵件發送成功', 'content' => '這是郵件內容'])->fetch('resource/view/email.html');});