標籤:c style class blog code java
初次使用thinkphp架構,開發一個郵件發送功能,由於對架構不熟悉折騰了幾個小時終於成功了,以下是代碼記錄。
此函數只能在ThinkPHP中使用且需要phpmailer擴充的支援;
phpmail的:
https://code.google.com/a/apache-extras.org/p/phpmailer
將phpmailer解壓後放置擴充放置到第三方類庫擴充目錄下: ThinkPHP/Extend/Vendor/檔案夾下即可,並使用vendor方法來匯入。更詳細介紹參考:http://document.thinkphp.cn/manual_3_2.html#lib_extend
步驟1:建立think_send_mail方法
/** * 系統郵件發送函數 * @param string $to 內送郵件者郵箱 * @param string $name 內送郵件者名稱 * @param string $subject 郵件主題 * @param string $body 郵件內容 * @return boolean */function think_send_mail($to, $name, $subject = ‘‘, $body = ‘‘){ vendor(‘PHPMailer.class#phpmailer‘); //從PHPMailer目錄導class.phpmailer.php類檔案 $mail = new \PHPMailer;//此處必須加“\”號否則報錯 // Inform class to use SMTP $mail->IsSMTP(); // Enable this for Testing $mail->SMTPDebug = 2; // Enable SMTP Authentication $mail->SMTPAuth = true; // Host of the SMTP Server $mail->Host = ‘smtp.126.com‘;//SMTP伺服器使用者名稱 // Port of the SMTP Server $mail->Port = 25;//SMTP伺服器連接埠 // SMTP User Name $mail->Username = "[email protected]";//郵箱地址 // SMTP User Password $mail->Password = "********";//郵箱密碼 // Set From Email Address $mail->SetFrom("[email protected]", $name); // Add Subject $mail->Subject= $subject; // Add the body for mail $mail->MsgHTML($body); // Add To Address $mail->AddAddress($to, $name); // Finally Send the Mail return $mail->Send() ? true : $mail->ErrorInfo;}
步驟2:在控制器調用即可
namespace Account\Controller;use Think\Controller;class AccountController extends Controller { //調用發送郵件功能public function getPwd(){ $toEmail =$_POST[‘email‘]; $subJect=‘郵件主題‘; $body=‘郵件內容‘; $name=‘寄件者名稱‘; $result=$this->think_send_mail($toEmail,‘sever‘,$subJect,$body); if($result) echo "ok"; else echo "failed"; } }