PHP后台隔5分钟发送email邮件

 

1.5分钟发送email,并且邮件内容为由html模板生成的table
while(1)
  {
    //ten minute
    var_dump("check task, please don't close");
    
    //send email
    processDBData($db);
    
    //process inventory state
    processInventoryState($db,$tasks);
    
    sleep(5*60);
  }

//read table data from database
  function processDBData($db)
  {
    $testplan_id = '';
    $temp = '';
    $TotalCaseNum = 0;
    $projectName = '';
     
    //check finished testplan table->tasks
    $sql="SELECT TK.id,TK.send_email,TK.user_id,TK.build_id,TK.case_ids,TK.testplan_id,TK.flag,TK.total
    from tasks AS TK WHERE current=total and flag='2' and ISNULL(send_email)";
    $controlInfor = $db->get_recordset($sql);
    
    if(null== $controlInfor)
    {
      return;
    }

    
    foreach($controlInfor as $key =>$item)
    {  
      //open model html
      $fModel = fopen("report.model","r");
      if(null == $fModel)
      {
        var_dump("no model");
      }
      
      $Modelhandle = fread($fModel,filesize("report.model"));
    
      $test_cases = $item['case_ids'];
      
      //get total Num
      $TotalCaseNum = (int)$item['total'];

      //testplan table->testplan
      //$sql = "SELECT notes,testproject_id FROM testplans WHERE id='{$item['testplan_id']}'";
      $sql = "SELECT name from nodes_hierarchy WHERE id='{$item['testplan_id']}'";
      $result = $db->get_recordset($sql);
      $temp = str_replace("MODEL_TESLPLANE",$result[0]['name'],$Modelhandle);
      $Modelhandle = $temp;
      
      //product table->testprojects
      $sql = "SELECT notes FROM testprojects WHERE id='{$result[0]['testproject_id']}'";
      var_dump($sql);
      $result = $db->get_recordset($sql);
      
      $temp = str_replace("MODEL_PRODUCTNAME",$result[0]['notes'],$Modelhandle);
      $Modelhandle = $temp;
      
      //build table->builds
      $sql = "SELECT DB.name FROM builds AS DB WHERE testplan_id='{$item['testplan_id']}' and id='{$item['build_id']}'";
      $result = $db->get_recordset($sql);
      var_dump($sql);
      $temp = str_replace("MODEL_BUILD",$result[0]['name'],$Modelhandle);
      $projectName = $result[0]['name'];
      $Modelhandle = $temp;
      
      //test result table->executions
      $cases = explode(',',$test_cases);
      $case_infor = get_ts_name_details($db,$cases);
      
      //var_dump(sizeof($case_infor));
      
      //process html testcase content  <!--3.testcase content--> nl2br()
      //after the content added(table,body,html end flag)
      var_dump($case_infor);
      
      $BeforSuiteNam = "";
      $successNum = 0;
      $TESTNUM = 0;
      
      //var_dump($case_infor);
      //var_dump($case_infor);
      foreach($case_infor as $k=>$case)
      {
        $Modelhandle = $temp;
        
        if($case['tsuite_name'] != $BeforSuiteNam)
        {
          $Modelhandle = $temp . "<tr><td colspan='3'><b>{$case['tsuite_name']}</b></td></tr>";
          $temp = $Modelhandle;
        }

        //cese name + importance + result
        //var_dump(Integer.parseInt('c'));
        //get success number
        $sql="SELECT TK.id,TK.send_email,TK.user_id,TK.case_ids,TK.testplan_id,TK.flag,TK.total,TK.user_id from tasks AS TK WHERE current=total and flag='2'";
        
        $controlInfor = $db->get_recordset($sql);
        
        //set pass/fail information  
        //var_dump($case['status']);
        $pass = 'p';
        $finish ='c';
        
        if(($case['status'])== $finish)//$TotalCaseNum
        {
          //set case information
          $Modelhandle = $temp. "
            <tr style=\"background-color:red\">
            <td>{$case['name']}</td>
            <td>{$case['importance']}</td>
            <td>FINISH</td>
          </tr>";
        }
        else if($case['status'] == $pass)//$TotalCaseNum
        {
          $successNum++;
                    //set case information
          $Modelhandle = $temp. "
            <tr>
            <td>{$case['name']}</td>
            <td>{$case['importance']}</td>
            <td>PASS</td>
          </tr>";
        }
        else
        {
          $Modelhandle = $temp. "
            <tr style=\"background-color:red\">
            <td>{$case['name']}</td>
            <td>{$case['importance']}</td>
            <td>FAIL</td>
            </tr>";
        }
        
        $temp = $Modelhandle;
        $BeforSuiteNam = $case['tsuite_name'];
      }
      
      //set success number
      //var_dump($TotalCaseNum);
      //$TotalCaseNum
      $temp = str_replace("MODEL_SUCCESS","{$successNum}/{$TotalCaseNum}",$Modelhandle);
      $Modelhandle = $temp;
      
      $temp = str_replace("MODEL_FAIL",($TotalCaseNum-$successNum)."/".$TotalCaseNum,$Modelhandle);
      $Modelhandle = $temp;
      
      //added html end sign
      $Modelhandle = $temp . "</table>
               </body>
               </html>";
      
      $fHtml = fopen("report.html","w");
      
      if(fwrite($fHtml,$Modelhandle))
      {
        fclose($fModel);
        fclose($fHtml);
        //die("创建html成功");
      }
      else
      {
        fclose($fModel);
        fclose($fHtml);
      }
      
      //get email address and send email
      $sql="SELECT email,group_email from users WHERE id={$item['user_id']}";
      var_dump($sql);
      
      $result = $db->get_recordset($sql);
      
      if(SendEmail($result[0]['email'],$result[0]['group_email'],$projectName))
      {
        signFinishEmail($db,$item['id']);
      }
      
      $successNum = 0;
    }
    
    //get test case
    return true;
  }
  
  //sign finish send email flag
  function signFinishEmail($db,$TaskId)
  {
    $sql = "UPDATE tasks SET send_email='1' WHERE id='{$TaskId}'";
    //var_dump($sql);
    $db->exec_query($sql);
    return;
  }
  
  //create email conttent
  function CreateHtml()
  {
   $fModel = fopen("report.model","r");
    
    if($fModel)
    {
      $handle = fread($fModel,filesize("report.model"));
      //var_dump($handle);
      $fHtml = fopen("report.html","w");
      
      if(fwrite($fHtml,$handle))
      {
        fclose($fModel);
        fclose($fHtml);
      }
      else
      {
        fclose($fModel);
        fclose($fHtml);
        die("Create html sucess");
      }
    }
    return;
  }
  
    /*
   function: get_ts_name_details

   args :
   
   returns: map with key=TCID
       values= assoc_array([tsuite_id => 5341
                 [details] => my detailas ts1
                 [tcid] => 5343
                 [tsuite_name] => ts1)
  */
  function get_ts_name_details(&$db,$tcase_id)
  {
   $tables = array();
   $termCase = $tcase_id;

   $tables['testsuites'] = DB_TABLE_PREFIX . 'testsuites';
   $tables['nodes_hierarchy'] = DB_TABLE_PREFIX . 'nodes_hierarchy';
    
   $rs = '';
   $do_query = true;
   $sql = "SELECT TS.id AS tsuite_id, TS.details, TCS.status,
         NHA.id AS tc_id, NHA.name,NHB.name AS tsuite_name,TV.importance 
      FROM {$tables['testsuites']} TS, {$tables['nodes_hierarchy']} NHA, 
         {$tables['nodes_hierarchy']} NHB,tcversions TV,executions TCS
      WHERE TS.id=NHA.parent_id
      AND NHB.id=NHA.parent_id
      AND TCS.tcversion_id=NHA.id+1
      AND TV.id=NHA.id+1";

   if( is_array($tcase_id) && count($tcase_id) > 0)
   {
    //note start node
    $tcase_id[count($tcase_id)-1] -= 1;
  
    $in_list = implode("-1,",$tcase_id);
    
    $sql .= " AND NHA.id IN (" . $in_list . ")";
   }
   else if(!is_null($tcase_id))
   {
    $sql .= " AND NHA.id={$tcase_id}";
   }
   else
   {
    $do_query = false;
   }
   if($do_query)
   {
   var_dump($sql);
    $rs = $db->fetchRowsIntoMap($sql,'tc_id');
   }
   
   return $rs;
  }
  
  //send email
  function SendEmail($emailAdress,$groupEmail,$projectName)
  {
    $MailTital="HATP:".$projectName;
    var_dump($groupEmail);
    if($emailAdress=="")
    {
      return false;
    }
    
    if(null !=$groupEmail)
    {
      //var_dump("run here");
      $ReciveEmails = explode(";",$groupEmail);
    }
    
    //process email informaition
    $mail = new PHPMailer(true); //New instance, with exceptions enabled

    $body = file_get_contents('report.html');
    //var_dump($body);
    $body = preg_replace('/\\\\/','', $body); //Strip backslashes

    $mail->IsSMTP(); // tell the class to use SMTP
    $mail->SMTPAuth = true; // enable SMTP authentication
    $mail->Port = 25; // set the SMTP server port
    $mail->Host = "172.20.0.6"; // SMTP server
    $mail->Username = "bugfree@hojy.com"; // SMTP server username
    $mail->Password = "bugfree"; // SMTP server password
    $mail->From = "testlink";
    $mail->FromName = "testlink";
    $mail->Subject = $MailTital;
    $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
    $mail->WordWrap = 80; // set word wrap
    $mail->MsgHTML($body);
    $mail->IsHTML(true); // send as HTML
    
    //add tester
    $ReciveEmails[sizeof($ReciveEmails)] = $emailAdress;
    var_dump($ReciveEmails);
    foreach($ReciveEmails as $K=>$Item)
    {
      var_dump($Item);
      $mail->AddAddress($Item);//to send man
    }
    
    try 
    {
      $mail->Send();
    }
    catch (phpmailerException $e) 
    {
      echo $e->errorMessage();
      return false;
    }
    
    $ReciveEmails='';
    return TRUE;
  }

时间: 2024-10-28 22:24:54

PHP后台隔5分钟发送email邮件的相关文章

求bat批处理向http://localhost每隔1分钟发送一个http请求的代码

问题描述 求bat批处理向http://localhost每隔1分钟发送一个http请求的代码 求大神帮我写个批处理命令实现:向http://localhost每隔1分钟发送一个http请求的功能 解决方案 @echo off set str=""%time:~65%"" :: 标签,用于goto跳转 :next1 :: 判断str是不是空,如果不是则执行下边的语句 if ""%str%""==""00.0

magento 无法发送email邮件问题解决办法

问题一,magento 本身自带的邮件发送,有些邮件无法发送,安装了ASchroder_SMTPPro插件后,只能 使用gmail的服务器,原因在于插件问题 app/code/community/Aschroder/SMTPPro/controllers IndexController.php 90行  代码如下 复制代码 $mail->addTo($to) ->setFrom("veric@nieger.com") ->setSubject($sub) ->s

Zend Framework框架之Zend_Mail实现发送Email邮件验证功能及解决标题乱码的方法_php实例

本文实例讲述了Zend Framework框架之Zend_Mail实现发送Email邮件验证功能及解决标题乱码的方法.分享给大家供大家参考,具体如下: Zend Framework 里Zend_Mail这个组件用起来还是很方便的..它提供了通用化的编写与发送文本内容的邮件,当然它也兼容MIME标准的多个多个段的邮件消息的功能.Zend_Mail里通过默认的Zend_Mail_Transport_SendMail传输或能过Zend_Mail_Transport_Smtp来发送我们的电子邮件. Ze

android后台不借助Intent发送Email

 下面是对邮件发送功能的封装,使用这些方法可以很容易地发送电子邮件,甚至可以添加附件. import java.util.Date; import java.util.Properties; import javax.activation.CommandMap; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; impor

.net SMTP发送Email邮件且可带附件示例_实用技巧

复制代码 代码如下: public static void sendEmail(string toAddress, string emailbody) { var fromAddress = ConfigurationManager.AppSettings["EmailAddress"]; string fromPassword = ConfigurationManager.AppSettings["EmailPassword"].ToString(); const

C# Email邮件发送,功能是密码找回或者重置功能。

原文:C# Email邮件发送,功能是密码找回或者重置功能. 最近根据公司需求,写个邮件发送.   这里面的传入的地址信息的参数都是经过加密的.  主要是保证用户信息的安全.   帮助类   1 using System; 2 using System.Collections.Generic; 3 using System.Configuration; 4 using System.IO; 5 using System.Linq; 6 using System.Net.Mail; 7 using

SQL Server Alert发送告警邮件少了的原因

最近突然发现我们部署在数据库上面的告警(Alert),当错误日志里面出现错误时,并不是每个错误日志都会发送邮件出来.如下所示,设置了告警"SQL Server Severity Event 14"   USE [msdb] GO     IF NOT EXISTS(SELECT 1 FROM msdb.dbo.syscategories WHERE NAME='DBA_MONITORING' AND category_class=2) BEGIN   EXEC msdb.dbo.sp_

使用Spring邮件抽象层发送简单邮件

Spring提供了一个发送电子邮件的高级抽象层,它向用户屏蔽了底层邮件系统的一些细节,同时负责低层次的代表客户端的资源处理.Spring邮件抽象层的主要包为org.springframework.mail.它包括了发送电子邮件的主要接口MailSender和 封装了简单邮件的属性如from, to,cc, subject, text的值对象叫做SimpleMailMessage. 1.我们定义一个发送邮件的接口:OrderManager.java 1 public interface Order

在PHP中发送MIME邮件

综述:编写邮件系统或邮件列表程序是PHP应用的一个大的分支,既管PHP提供了简单的用于发email的函数,但在实际应用中,会涉及到发送带附件的邮件.测试用户输入的email地址的有效性,尤有必要用专门的章节来讲述. MIME是什么? MIME表示多用途Internet邮件扩允协议.MIME扩允了基本的面向文本的Internet邮件系统,以便可以在消息中包含二进制附件. RFC822在消息体的内容中做了一点限制:就是只能使用简单的ASCII文本.所以,MIME信息由正常的Internet文本邮件组