邮件发送 API接口

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;
	}

}

  

posted @ 2017-09-02 10:39  czcColud  阅读(4535)  评论(0编辑  收藏  举报