Controler:
<?php
/**
* @name MailController
* @author pangee
* @desc 郵件處理功能
*/
class MailController extends Yaf_Controller_Abstract {
public function indexAction() {
}
public function sendAction() {
$submit = $this->getRequest()->getQuery( "submit", "0" );
if( $submit!="1" ) {
echo json_encode( array("errno"=>-3001, "errmsg"=>"請通過正確渠道提交") );
return FALSE;
}
// 獲取參數
$uid = $this->getRequest()->getPost( "uid", false );
$title = $this->getRequest()->getPost( "title", false );
$contents = $this->getRequest()->getPost( "contents", false );
if( !$uid || !$title || !$contents ) {
echo json_encode( array("errno"=>-3002, "errmsg"=>"用戶ID、郵件標題、郵件內容均不能為空。") );
return FALSE;
}
// 調用Model, 發郵件
$model = new MailModel();
if ( $model->send( intval($uid), trim($title), trim($contents) ) ) {
echo json_encode( array(
"errno"=>0,
"errmsg"=>"",
));
} else {
echo json_encode( array(
"errno"=>$model->errno,
"errmsg"=>$model->errmsg,
));
}
return TRUE;
}
}
Model:
<?php
/**
* @name MailModel
* @desc 郵件操作Model類
* @author pangee
*/
require __DIR__ . '/../../vendor/autoload.php';
use Nette\Mail\Message;
class MailModel {
public $errno = 0;
public $errmsg = "";
private $_db;
public function __construct() {
$this->_db = new PDO("mysql:host=127.0.0.1;dbname=imooc;", "root", "");
}
public function send( $uid, $title, $contents ) {
$query = $this->_db->prepare("select `email` from `user` where `id`= ? ");
$query->execute( array(intval($uid)) );
$ret = $query->fetchAll();
if ( !$ret || count($ret)!=1 ) {
$this->errno = -3003;
$this->errmsg = "用戶郵箱信息查找失敗";
return false;
}
$userEmail = $ret[0]['email'];
if( !filter_var($userEmail, FILTER_VALIDATE_EMAIL) ) {
$this->errno = -3004;
$this->errmsg = "用戶郵箱信息不符合標准,郵箱地址為:".$userEmail;
return false;
}
$mail = new Message;
$mail->setFrom('PHP實戰課程-高價值的PHP API <imooc_phpapi@126.com>')
->addTo( $userEmail )
->setSubject( $title )
->setBody( $contents );
$mailer = new Nette\Mail\SmtpMailer([
'host' => 'smtp.163.com',
'username' => '15070380105@163.com',
'password' => 'czc1234', /* smtp獨立密碼 */
'secure' => 'ssl',
]);
$rep = $mailer->send($mail);
return true;
}
}
