来源:慕课网教程
一、用composer安装nette/mail
composer require nette/mail
在当前文件夹下生成vendor文件夹,composer.json文件,composer.lock文件。
二、数据库
代码通过查询用户id找到email,并发送邮件。
三、写代码
controller:
<?php
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);
$content=$this->getRequest()->getPost('content',false);
if (!$uid||!$title||!$content){
echo json_encode(array(
'errno'=>-3002,
'errmsg'=>'用户ID、邮件标题、邮件内容均不得为空'
));
return false;
}
//调用Model,发邮件
$model=new MailModel();
if ($model->send(intval($uid),trim($title),trim($content))){
echo json_encode(array(
'errno'=>0,
'errmsg'=>''
));
}else{
echo json_encode(array(
'errno'=>$model->errno,
'errmsg'=>$model->errmsg,
));
}
return true;
}
}
model:
<?php
require __DIR__.'/../../vendor/autoload.php';//引用vendor里的autoload.php
use Nette\Mail\Message;
class MailModel {
public $errno=0;
public $errmsg='';
private $_db=null;
public function __construct(){
$this->_db=new PDO('mysql:host=localhost;dbname=yaf','root','');
$this->_db->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
}
public function send($uid,$title,$content){
$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('yourmail@163.com')
->addTo($userEmail)
->setSubject($title)
->setBody($content);
$mailer=new Nette\Mail\SmtpMailer([
'host'=>'smtp.163.com',
'username'=>'yourmail@163.com',
'password'=>'yourpassword',
'secure'=>'ssl'
]);
$rep=$mailer->send($mail);
return true;
}
}
提供另外一个验证非法邮箱的方法:
//验证非法邮箱
function check_mail($email){
/**
* 查询指定的主机的DNS记录的,有可能有点慢
*/
$arr=explode("@",$email);
if (checkdnsrr(array_pop($arr),"MX")){//'MX'邮件交换记录
return $email;
}
return false;
}
可以通过http://yourdomain/yaf/mail/send?submit=1验证是否能发送成功了!
可能报错:Error Msg:SMTP server did not accept PLAIN credentials with error: 550
解决方法:
到你的邮箱首页
报错:Error Msg:SMTP server did not accept PLAIN credentials with error: 550 User has no permission
将密码换成授权码即可!