应用场景

在用户注册时,对新注册的用户发一封邮件

设计模式

  • 1.注册成功时,对用户表插入一条数据
  • 2.用户表插入成功后,对应发送邮件队列表插入一条待发送状态的数据
  • 3.异步执行do_queue.php
  • 4.通过do_queue.php调用queue.php进行发送邮件
    调用关系如图所示:

微信截图_20200104164317.png

涉及两个表和一个开源类phpmailer

  • 注册页面index.php代码:
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>用户注册</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<?php
require_once 'DB.php';
require_once 'queue.php';
$link=new DB([
    'dsn'=>'mysql:dbname=mok;host=localhost;port:3306;',
    'user'=>'root',
    'password'=>'root',
    'charset'=>'utf8',
]);

if(isset($_POST['reg'])){
    $userEmail=htmlspecialchars(trim($_POST['email']),ENT_QUOTES);
    $userPwd  =htmlspecialchars(trim($_POST['password']),ENT_QUOTES);
    if(!empty($userEmail) && !empty($userPwd)){
        $sql="select * from user where email = '$userEmail'";
        if(!empty($link->query($sql))){
            echo "<script>alert('用户已存在!!!')</script>";
        }else{
            $sql="insert into user(email,password) VALUES ('$userEmail','$userPwd')";
            $res=$link->execOne($sql);
            if($res !== false){
            $sql="insert into task_list(user_email,status,create_time,update_time) values("."'$userEmail',0,"."'".date("Y-m-d H:i:s")."',"."'".date("Y-m-d H:i:s")."'".")";
            $res=$link->execOne($sql);
                if($res !== false){
                    ?>
                    <script type="text/javascript">
                       $.post("do_queue.php");
                    </script>
                <?php
                }
            }else{
                echo "<script>alert('注册失败!!')</script>";
            }
        }
    }


}


?>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-5">
            <form action="" method="post">
                <div class="form-group">
                    <label >注册邮箱</label>
                    <input type="email" class="form-control"  name="email">
                </div>
                <div class="form-group">
                    <label >注册密码</label>
                    <input type="password" class="form-control" name="password">
                </div>
                <div class="form-group">
                    <input type="submit" class="btn btn-primary" name="reg" value="注册">
                </div>

            </form>
        </div>

    </div>
</div>

<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>
</html>

异步执行do_queue.php代码

<?php
exec("C:\phpstudy_pro\Extensions\php\php5.6.9nts\php.exe queue.php");

发送邮件queue.php代码

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/1/4
 * Time: 14:28
 */

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Load Composer's autoloader
require 'vendor/autoload.php';
require_once 'DB.php';
$rootPath=dirname(__FILE__);
function halt($message){
    var_dump($message);
    exit();
}
function sendMail($host,$fromEmail,$fromPwd,$fromName,$toEmail,$toName,$subject,$content){
        $mail = new PHPMailer(true);
        $mail->isSMTP();
        $mail->CharSet    = 'utf-8';
        $mail->Host       = $host;
        $mail->SMTPAuth   = true;
        $mail->Username   = $fromEmail;
        $mail->Password   =$fromPwd;
        $mail->setFrom($fromEmail, $fromName);
        $mail->addAddress($toEmail, $toName);
        $mail->isHTML(true);
        $mail->Subject =$subject;
        $mail->msgHTML($content);
        return $mail->send();
    }

$link=new DB([
    'dsn'=>'mysql:dbname=mok;host=localhost;port:3306;',
    'user'=>'root',
    'password'=>'root',
    'charset'=>'utf8',
]);



while (true)
{
    $sql="select * from task_list where status='0' order by task_id ASC limit 5";
    $data=$link->query($sql);
//    halt($data);
    if(empty($data)){
        break;
    }else{
       foreach ($data as $k=>$v){
        if(sendMail("smtp.aliyun.com",
            "这里填写邮箱账号",
            "这是里填写邮箱密码",
           "aliyun",
            $v['user_email'],
            "sina",
            "hello".$v['user_email'],
            file_get_contents($rootPath.'/mailsend.html'))){
            $link->execOne("update task_list set status = 1 where task_id = ".$v['task_id']);
        }
           sleep(3);
       }


    }
}

本文由 admin 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论