當程序執行群發郵箱的時候,會出現等待程序反饋時間太長這對于用戶體驗來說是很不好的,用戶大多會在程序沒有執行完就關閉程序,這樣發送郵件也會中斷,所以我們的解決思路應該是用異步去執行發郵件的過程。
一、創建一個連接用戶操作頁面和執行發件的方法:
privatefunctionconnect($host,$path,$param=array()){
$query=isset($param)?http_build_query($param):'';
$port=80;
$errno=0;
$errstr='error';
$timeout=30;//連接超時時間(S)
$fp=@fsockopen($host,$port,$errno,$errstr,$timeout);
if(!$fp){
return'連接失敗';
}
if($errno||!$fp){
return$errstr;
}
stream_set_blocking($fp,0);//非阻塞
stream_set_timeout($fp,1);//響應超時時間(S)
$out=POST.$path.HTTP/
1.1\r\n;
$out.=host:.$host.\r\n;
$out.=content-length:.strlen($query).\r\n;
$out.=content-type:application/x-www-form-urlencoded\r\n;
$out.=connection:close\r\n\r\n;
$out.=$query;
$result=@fputs($fp,$out);
@fclose($fp);
return$result;
}
二、用戶操作方法傳遞參數頁面
publicfunctionindex(){
$param=array(
0='xxx@qq.com',
1='xxx@qq.com',
);
$url='http://'.$_SERVER['HTTP_HOST']..'/Sends/emails';
$info=parse_url($url);
/*dump($info);*/$res=$thisConnect($info[host],$info['path'],$param);
/*調用方法*/
echo'發送成功';/*提示用戶發送成功*/
}
三、發送郵件
publicfunctionemails(){
set_time_limit(0);/*設置程序運行時間沒有限制防止運行超時*/
ignore_user_abort(true);//設置與客戶機斷開是否會終止執行
$data=I('post.');
$email='';
$sendTitle=郵件標題;
$sendinfo='郵件內容';
$send=array(
'title'=$sendTitle,
'detail'=$sendinfo,
);
$mail=newService\SendemailService();
foreach($dataas$k=$v){
$email.=$v.'|';
$toMail=$v;
$info=$mail-sendEmail($send,$toMail);
/*執行發送郵箱*/
}
$log_name=Public/notify_url.log;//log文件路徑
$thislog_result($log_name,$email.date(time(),'H:i:s').';');
/*記錄一下日志看程序是否執行發件*/
}
用戶運行結果(以上是測試)
日志查看
測試的兩個郵箱都已經收到郵件