在Cronjob运行后,从MYSQL向收件人发送电子邮件

时间:2018-03-19 22:58:01

标签: php mysql email cron

我设置了一个每分钟运行一次代码的cronjob。此代码的目标是连接到Mysql并将某个列更新为新值(如果该值已在数据库中保留1分钟)。在并行中,我想要同时向同一行中存在的电子邮件地址发送电子邮件。表格的例子。

| id | title | status | email             |
+----+-------+--------+-------------------+
| 1  | title | 1      | email@example.com |
+----+-------+--------+-------------------+
| 2  | titl2 | 1      | email1@example.com|
+----+-------+--------+-------------------+

在cron作业运行后,表变为

| id | title | status | email             |
+----+-------+--------+-------------------+
| 1  | title | 2      | email@example.com |
+----+-------+--------+-------------------+
| 2  | titl2 | 2      | email1@example.com|
+----+-------+--------+-------------------+

我现在想要将电子邮件发送到行状态变为2的电子邮件

这是我尝试的代码。

<?php 
// Create connection
$conn = mysqli_connect('localhost', 'username', 'password', 'dbname');
// Check connection
if ($conn) {

mysqli_query($conn, "UPDATE jobs SET status = 2 WHERE created < (NOW() - INTERVAL 1 MINUTE)");
$em = mysqli_query($conn, "SELECT email FROM jobs WHERE status = '2' < DATE(NOW() - INTERVAL 1 MINUTE)");

}
mysqli_close($conn);
?>
<?
while ($row = mysqli_fetch_array($em)) {

    $from = 'email@myemail.com';
    $to = $row['email']; // The column where your e-mail was stored.
    $subject = 'Sample Form';
    $msg = 'Hello world!';
    mail($to, $subject, $msg, $from);
}
?>

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。用于获取所有电子邮件的代码,即使是很久以前状态= 2的电子邮件。

<?php 
// Create connection
$conn = mysqli_connect('localhost', 'username', 'password', 'dbname');
// Check connection
if ($conn) {

mysqli_query($conn, "UPDATE jobs SET status = 2 WHERE created < (NOW() - INTERVAL 1 MINUTE)");
    $em = mysqli_query($conn, "SELECT email, title FROM jobs WHERE status = 2 AND created BETWEEN (DATE_SUB(NOW(),INTERVAL 2 MINUTE)) AND NOW()");
}
mysqli_close($conn);?>
<?
while ($row = mysqli_fetch_array($em)) {

$from = 'email@myemail.com';
$to = $row['email']; // The column where your e-mail was stored.
$subject = 'Sample Form';
$msg = 'Hello world!';
mail($to, $subject, $msg, $from);
}
?>